Let's take an example scenario for a simple buy operation where a user can pay from his wallet or from credit card or in case the amount exceed from the amount he has in his wallet then the remaining amount will be billed to his credit card. SO in that scenario there are two distinct transactions one to debit the wallet and then also charge the credit card. And let's assume that wallet is a DB operation while Credit card is a call to third party, is it okay to do both these operations in a single DB transaction so that if an one fails the entire operations rollsback or should I do it in parallel as most modern apps now utilize parallel operations. If I do both operations in parallel then how would I ensure the atomicity of the entire operation?
How do we implement such kind of functionality in a microservices architecture or distributed applications?
Thanks in advance.
No, it won't work like you hope it will. Assuming you do db write, API call, db commit then what happens if the API succeeds and then the db aborts? Notice that this is exactly the same as if the entire db transaction is after the API call.
The only way to do this like you want is to have commit and rollback operations on the API and then drive the cross-system transaction with 2PC/3PC/Consensus.
Or you can simplify and turn the transaction into a workflow/fsm: there is a state in the database row for each system being updated (+1 for COMPLETE). After the driving system updates each external system it moves the fsm to the next state, that of the system it will update next. If the remote call fails, the driver will retry calling the system until it succeeds