Handling semi-transactional cases in spring programmatically

Consider a case in which you are updating information in local database and need to publish the same information some where on the remote application over network. You don’t have control over the transactional behavior of the remote application but some how get to know that the publishing/operation is not successful.

There can be scenarios when the remote operation is successful but you local database update fails, in such a situation you must be aware of what reverse operation should be done on remote application to revert it. The following cases can arise in semi-transaction cases:

Local operation

Remote Operation

Transaction Behavior

Remote App-State

Successful

Failure

Rollback

Remote App will handle it

Failure

Failure

Rollback

Remote App will handle it

Failure

Successful

Rollback

Revert call to be send

Successful

Successful

Commit

Successful

Now how to handle such kind of scenarios and reverse transaction programmatically. I will walk you through small example to handle it.

Interface ReverseTransactionCallback:

***************

public interface ReverseTransactionCallback {

void executeTransaction();

void executeReverseTransaction();

}
****************

This interface contains two methods to execute in transaction or if the transaction fails then this is called to rollback stuff on remote application.

Look at the implementation of executeTransaction() method which will update local database and will publish to remote application. Lets go through each scenario in case of exception:

Local operation fails before commit: Local operation is done first, so in case of exception the rollback will be done on local side and no communication with remote app.

Local operation successful but Remote operation fails: the transaction is rolled back on local side.

Local operation successful and remote operation successful but the commit fails: the transaction is rolled back on local side and executeReverseTransaction() method is called for reversal command on remote application. This is the only scenario where we need to send reversal call to remote application.