Video in progress
While saving an order you have to send an HTTP request to an external payment provider. How do you design the transaction boundaries?
I don't make the external call inside a database transaction. I split the process into states: first save in PENDING and commit, then make the payment call without a transaction, then write the result in a new short transaction. For failures there is an idempotency key and a reconciliation job.
📖 Answer
The approach of "let's put everything in one @Transactional" gives three kinds of problems. If the provider doesn't respond for 10 seconds, the connection and row locks are held for 10 seconds. The provider charged the money, then our commit failed: the money is taken and there is no order. If you retry, it is charged twice.
With a state machine:
public PaymentResult checkout(CheckoutCommand cmd) {
Order order = tx.execute(s -> orders.save(Order.pending(cmd))); // transaction 1
ProviderResponse resp = provider.charge(order.getId().toString(), // idempotency key
order.getTotal()); // no transaction
return tx.execute(s -> { // transaction 2
Order o = orders.findById(order.getId()).orElseThrow();
return resp.ok() ? o.markPaid(resp.ref()) : o.markFailed(resp.error());
});
}
Important details:
- The idempotency key is the order ID. If the request to the provider is sent again, it won't charge a second time.
- If the pod dies between transaction 1 and transaction 2, the order stays PENDING. A reconciliation job periodically finds old PENDING orders and asks the provider for their status. A webhook leads to the same state.
- Optimistic lock in transaction 2: the webhook and the main flow can update at the same time, and
@Versionplus a check that "only PENDING can be transitioned" makes this safe.
It is more complex, but with money I don't know another reliable way. For multi-step processes this turns into a saga.
Sign up to mark studied questions and save your progress.