Considering the common use case of a user creating a new account on a web application and the application sending a confirmation email to the user's address. From what I've seen, this is typically implemented in one of 3 ways:
- The web controller calls a service method, which creates the user account and sends the email, both within a single transaction.
- The web controller calls a service method (with tx propagation = never), which invokes a 1st method on itself to create the user account within a transaction, and then invokes a 2nd method on itself to send the email.
- The web controller calls a 1st service method, which creates the user account within a transaction, then a 2nd service method that sends the email.
The 1st approach is simple and straightforward, but there is a risk that the transaction is rolled back after the email was sent, thereby making the email invalid. The 2nd approach is more complicated, but it guarantees that the email is sent only if user creation has actually succeeded. The 3rd approach is simple but burdens the web layer with business logic that it shouldn't need to know.
Isn't there a simpler approach, maybe AOP-driven, that guarantees that the email will be sent only if the user creation transaction actually succeeded? Am I paranoid in thinking that the 1st approach could fail?
We're using a Java EE + Spring stack and are willing to integrate additional APIs (AOP? Spring Integration?) to achieve this.
Cheers!