I have a spacer that reaches from the top of the stem and over the top of the steerer tube. I am able to lock it down with the top cap, but I was wondering if it is safe to ride like this, or if I should get a smaller spacer so that the spacer and top cap is flush with the top of the steerer tube. The picture below illustrates the situation (hopefully).
You actually need something sticking up above the top of your steer tube. It can be either a spacer or the stem itself. This is because the top cap squeezing down onto the stem/spacer stack is what keeps the headset bearings snugly in their cups. If the top cap is flush with the steer tube, there will be play in the headset which is bad.
Park Tools has a very detailed set of instructions about headsets that you might want to look over. The following image is from those instructions and shows the amount of space that you need. More than that is acceptable as well, as long as it's not so much that the stem or spacer at the top is barely holding on. In your case, as long as the steer tube protrudes 2/3 of the way through your top spacer, you're probably ok. If you shuffle it around and put the stem on top of the stack, you'll want to make sure that the steer tube is well above the pinch bolts.
It would seem to be safe to me as long as the stem is properly installed. The clamp bolts of the stem on the steerer tube in a threadless headset setup are what holds the whole assembly together. Spacers below the stem are required to eliminate vertical play. Spacers above the stem are only required for aesthetics.
The only risk I see is that if the bolts on the stem loosen then the cap screw will be at increased risk of shearing and will not provide any real backup security of the assembly, but you shouldn't be relying on that anyway.