Quick revision
The short answer
Java evaluates method arguments before the call, so createUser(id) runs while the pipeline is being assembled, before findUser has even been subscribed, and because createUser sends the email as soon as it is called, the email goes out whether or not the user exists. switchIfEmpty only decides whether to subscribe to the Mono it was given; it cannot stop the method that built it from running. The fix is switchIfEmpty(Mono.defer(() -> createUser(id))), and the better fix is to make createUser itself lazy, so its side effects only happen when its Mono is subscribed.
What to remember
In this answer, we saw that createUser(id) runs during assembly because Java evaluates the argument of switchIfEmpty before the call, so a side effect performed before createUser returns its Mono happens whether or not the user exists. We fixed the call site with switchIfEmpty(Mono.defer(() -> createUser(id))), and then made createUser itself lazy, putting the save and the email inside the returned pipeline, in the right order, so that its side effects only occur on subscription.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Java evaluates method arguments before the call, so createUser(id) runs while the pipeline is being assembled, before findUser has even been subscribed, and because createUser sends the email as soon as it is called, the email goes out whether or not the user exists. switchIfEmpty only decides whether to subscribe to the Mono it was given; it cannot stop the method that built it from running. The fix is switchIfEmpty(Mono.defer(() -> createUser(id))), and the better fix is to make createUser itself lazy, so its side effects only happen when its Mono is subscribed.
Why this question is asked
This bug is a classic in reactive code reviews because the code reads perfectly: find the user, and if there is none, create one. The tests usually check that a new user gets the email, and nobody checks that an existing user does not. Interviewers ask it to see whether we can reason about when code runs in a reactive pipeline, which is different from when it appears to run. In this answer, we will reproduce the bug, see exactly why the email is sent, fix it with Mono.defer, and then make createUser safe for every caller.
1Reproducing the Bug
Here is a simplified version of the code. createUser does some work immediately, including sending the welcome email, and then returns a Mono that saves the user.
Notice that the save did not happen for the existing user, which is why the bug is easy to miss: the database looks right. Only the side effect that ran before the Mono was returned leaked out.
2Why createUser Runs Even When the User Exists
A reactive pipeline has two phases. During assembly, our code calls findUser, switchIfEmpty and flatMap, and each call returns a new Mono that describes a step. During subscription, data actually flows. switchIfEmpty(other) is designed for the second phase: at runtime, if the source completes without a value, it subscribes to other; if the source emits a value, it never subscribes to other.
But to call switchIfEmpty(other), Java must first have the argument other, so it calls createUser(id) during assembly, before switchIfEmpty even exists, and long before anyone knows whether the user is there. Everything in createUser's body before the return statement runs at that moment. The returned Mono is lazy, so the save waits; the email is not inside that Mono, so it does not wait.
7 messages in order. Play them, or step through them one at a time.
The email was sent during assembly, before the pipeline knew the answer.
3Fix 1: Wrap the Fallback in Mono.defer
Mono.defer takes a supplier of a Mono and calls it only when the deferred Mono is subscribed. Wrapping the fallback delays the call to createUser until switchIfEmpty actually needs it.
This fixes the call site, and it is the pattern to use whenever the argument of switchIfEmpty, or of a similar operator that takes a ready-made publisher, is produced by a method call that does work. But it relies on every caller remembering to do it.
4Fix 2: Make createUser Itself Lazy
The better fix moves the side effect inside the returned Mono, so that calling createUser only describes the work. Then createUser is safe no matter how it is used. It is also more correct in another way: in the original code, the email was sent before the save, so a failed save still sent an email. Ordering the steps inside the pipeline lets us send the email only after the user is stored.
If the email client is blocking, we wrap it with Mono.fromRunnable or Mono.fromCallable plus subscribeOn(Schedulers.boundedElastic()) instead of calling it in the method body. The rule is that a method returning a Mono should not do anything observable until that Mono is subscribed. Many teams also move the welcome email to an event published after the user is created, so that a retry of the pipeline cannot send it twice.
5Finding Other Cases of the Same Bug
The same mistake appears anywhere a method call, rather than a lambda, is passed as an operator argument. Writing defaultIfEmpty(loadDefault()) or onErrorReturn(computeFallback()) runs the method during assembly in exactly the same way, while onErrorResume(e -> fallback()) is safe, because Reactor only calls the lambda when an error actually arrives. A quick review rule is to look at every argument of switchIfEmpty, defaultIfEmpty, onErrorReturn and Mono.just and ask whether it calls a method with side effects or blocking work. Tests should check the negative case too, for example verifying with a mock that sendWelcome was never called for an existing user.
6Follow-up questions
Why does the save not happen for the existing user when the email does?
Because the save is inside the returned Mono, which is lazy and only runs if subscribed, and switchIfEmpty never subscribes to it when the source emits a value. The email was outside the Mono, in the method body, so it ran when the method was called.
Would switchIfEmpty(Mono.fromCallable(() -> createUser(id)).flatMap(m -> m)) also work?
It would delay the call, but it is a roundabout way of writing Mono.defer, which exists exactly for suppliers that return a publisher. Mono.defer is clearer and idiomatic.
How do you test that the fix works?
Use StepVerifier with a findUser stub that returns a user, then verify with a mock that sendWelcome was never called; and a second test with an empty findUser that verifies the save and exactly one email. Testing the negative case is what would have caught the original bug.
7Conclusion
In this answer, we saw that createUser(id) runs during assembly because Java evaluates the argument of switchIfEmpty before the call, so a side effect performed before createUser returns its Mono happens whether or not the user exists. We fixed the call site with switchIfEmpty(Mono.defer(() -> createUser(id))), and then made createUser itself lazy, putting the save and the email inside the returned pipeline, in the right order, so that its side effects only occur on subscription.
Open with
The pipeline looks lazy but the argument isn't. When Java builds the expression findUser(id).switchIfEmpty(createUser(id)), it has to evaluate createUser(id) first to pass it in, so createUser runs during assembly, before findUser is even subscribed and long before we know whether the user exists. switchIfEmpty works correctly at runtime: if findUser emits a user, it never subscribes to the fallback Mono, so the save inside that Mono doesn't happen.
Then, if they want more
But the email is sent in createUser's method body, before it returns the Mono, so it has already gone out. The quick fix is to wrap the fallback: switchIfEmpty(Mono.defer(() -> createUser(id))). Now createUser is only called if the source is empty.
The better fix is to make createUser itself lazy so it's safe for every caller: return Mono.defer around the save, and send the email in a flatMap after the save succeeds, then thenReturn the saved user. That also fixes an ordering problem, because before, a failed save would still have sent an email.
If the email client blocks, I'd wrap it with fromRunnable and subscribeOn boundedElastic. And I'd add a test for the negative case, verifying the email is never sent for an existing user, since that's the test that would have caught this.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring WebFlux, Project Reactor reference guide
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "In this code, sendEmail is called even when the user exists...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-fundamentals/54e21ad433/