Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction and sending an email

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:

  1. The web controller calls a service method, which creates the user account and sends the email, both within a single transaction.
  2. 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.
  3. 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!

like image 811
Spiff Avatar asked Dec 02 '10 03:12

Spiff


1 Answers

Another option I am currently using to solve this problem:

http://download.oracle.com/javaee/6/api/javax/transaction/Synchronization.html

like image 117
qtxo Avatar answered Sep 22 '22 03:09

qtxo