Video in progress
The service runs on two instances and one order got paid twice. Why didn't synchronized help, and what do you do?
synchronized only coordinates threads inside one JVM, and a thread in the second pod can't see it at all. The fix has to live in a shared resource: a unique constraint or a conditional UPDATE in the DB, an optimistic version, and if needed a distributed lock and an idempotency key.
📖 Answer
Typical code:
@Transactional
public synchronized void pay(long orderId) {
Order o = repo.findById(orderId).orElseThrow();
if (o.getStatus() == Status.NEW) {
gateway.charge(o);
o.setStatus(Status.PAID);
}
}
This is wrong even on a single instance: the lock is released when the synchronized method returns, but the transaction commits after that, in the proxy. A second thread can still read the old NEW state. With two pods, they don't know about each other at all.
Reliable ways:
- A conditional UPDATE, which makes the state transition atomic:
UPDATE orders SET status = 'PAYING'
WHERE id = :id AND status = 'NEW';
-- 1 row updated: you won; 0: someone got there first
- Optimistic locking: a
@Versionfield; the second commit gets anOptimisticLockException. - Pessimistic lock:
SELECT ... FOR UPDATE, for short transactions. - An idempotency key: write to the payment provider and to your own table with a unique key. A retry and a double-clicked button then give the same result.
- A distributed lock (Redis, ShedLock, Zookeeper), mostly for "only one instance should run this" cases like cron. The lock can expire while its old owner keeps working, so you need a fencing token or a DB check anyway.
Don't hold an external payment call inside a DB transaction: move the state to PAYING and commit, then call the gateway, and write the result separately. That way neither the lock nor the connection is held for long.
Sign up to mark studied questions and save your progress.