I have a JSF/EJB/JPA application which uses container managed persistence. There is
one case where a call is made to paypal via HTTP which results in a balance being adjusted
for the user in a database. The thing is these paypal transactions can take ages, up to
30 seconds. To give me finer grained transaction control I'm using bean managed
transactions in this case. This is some pseudo-ish code for what I've got now:
So the idea is that I start a transaction, assume success and increase the user balance,
call the http service and commit if it succeeds or rollback otherwise.
I have an uneasy feeling that I may not be anywhere near the right ballpark with this design,
particularly having the lengthy http call (actually done using jax-rs) inside the pessimistic_write
transaction. I clearly can't write lock the user record for 30 seconds while the credit card is
being processed, but unless I make the paypal call within the transaction I could do the paypal
call, it succeeds, I then try to increase the user balance but the database is shutdown - no
This is new territory for me, can anyone point me in the right direction, is there an established
way of doing what I'm trying to do? I feel that I'm missing something obvious.
With your database and pay-pal you basically have two data sources that you need to commit as a single atomic transaction. But you don't have two-phase commit with PayPal, so you need to improvise.
The best option is to create a pending transaction table, and commit the record of the payment to this table first. Then commit to paypal, then commit you your normal table and remove from the pending table.
This way you always have a record of the transaction even in the event of a failure. Also, you avoid blocking your database for a long duration.
Another option is to flush the change to your database, but not commit the transaction until after the paypal succeeds. This reduces the failure window to be very unlike, which is really the best that you can ever get, as there could always be some sort of hardware or disk failure that wipes away data (this world is never perfect, worst case some see a bogus transaction on there paypal and calls to have it fixed).