Video in progress
How does the SERIALIZABLE level work in PostgreSQL, and what has to change in Java code if you use it?
@Transactional(isolation = Isolation.SERIALIZABLE)
public void bookDoctor(long doctorId, LocalDate day) {
long onCall = repo.countOnCall(day); // 2 right now
if (onCall > 1) {
repo.setOffCall(doctorId, day); // what if both leave at the same time?
}
}
PostgreSQL implements SERIALIZABLE through SSI: without taking locks, it tracks dangerous dependencies between transactions and, if there's a risk of an anomaly, cancels one with error 40001. So the application must have a retry mechanism that re-runs the whole transaction.
📖 Answer
This is the classic write skew: two doctors say "I'm going off call" at the same time. Under REPEATABLE READ both see "there are 2", both leave, and nobody is left on call. Because they updated different rows, there's no lock collision either.
Under SERIALIZABLE, PostgreSQL records what each transaction read as predicate locks (SIReadLock). They don't block, they only track. If two transactions modified what the other read (a cycle of rw-conflicts), one of them gets it at commit time or before:
ERROR: could not serialize access due to read/write dependencies among transactions
SQLSTATE: 40001
What changes on the Java side (people often slip up here in interviews):
- The retry has to be outside the
@Transactionalmethod: the whole transaction starts over from the beginning with a new snapshot. Use@Retryablefrom Spring Retry or a plain loop, only for40001(in Spring, theCannotSerializeTransactionException/PessimisticLockingFailureExceptionfamily). - There should be no external side effects (email, Kafka) inside the transaction, since a retry would execute them twice.
- Marking read-only transactions as
readOnly = truehelps, and withDEFERRABLElong reports are never canceled.
The cost: the percentage of cancellations grows under load, and predicate locks take memory. I put SERIALIZABLE not on the whole application but on a few flows where the invariant matters, and I watch the number of 40001 errors in metrics.
Sign up to mark studied questions and save your progress.