Quick revision
The short answer
This anomaly is write skew: each transaction reads a shared condition (two doctors on call), decides it is safe, and writes a different row, so neither conflicts with the other and both commit. READ COMMITTED and snapshot-based REPEATABLE READ both allow it. We prevent it with SERIALIZABLE isolation, where PostgreSQL's serializable snapshot isolation detects the pattern and fails one transaction for retry, by locking the rows we read with SELECT ... FOR UPDATE, or by materialising the condition in a single row that both transactions must update; in every case the application needs retry logic.
What to remember
In this answer, we reproduced write skew: two transactions read the same on-call count, each wrote a different row, and both committed under READ COMMITTED, which only blocks same-row writes; snapshot-based REPEATABLE READ allows it as well. We prevented it with SERIALIZABLE, where PostgreSQL detects the read and write dependencies and aborts one, with SELECT ... FOR UPDATE on the rows we read, or by materialising the rule in one row updated conditionally, and we added retry logic for the failures each fix can produce.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
This anomaly is write skew: each transaction reads a shared condition (two doctors on call), decides it is safe, and writes a different row, so neither conflicts with the other and both commit. READ COMMITTED and snapshot-based REPEATABLE READ both allow it. We prevent it with SERIALIZABLE isolation, where PostgreSQL's serializable snapshot isolation detects the pattern and fails one transaction for retry, by locking the rows we read with SELECT ... FOR UPDATE, or by materialising the condition in a single row that both transactions must update; in every case the application needs retry logic.
Why this question is asked
Most concurrency bugs we learn about involve two transactions writing the same row, and databases are good at stopping those. Write skew is different because the two transactions write different rows, so the usual protection never fires. Interviewers like this scenario because it shows whether we understand what each isolation level actually checks, and whether we know how to protect a rule that spans several rows. In this answer, we will reproduce the problem at READ COMMITTED, name the anomaly and see why higher-but-not-highest levels still miss it, and then go through three fixes and the retry logic they all need.
1Reproducing It at READ COMMITTED
The table on_call has one row per doctor per shift. Doctors A and B are both on call for shift 7, and the rule is that at least one must stay. The code checks the count and then goes off call.
6 messages in order. Play them, or step through them one at a time.
Each decision was based on a count the other transaction was about to change.
Each transaction counted before the other had committed, so each saw 2. Each then updated only its own row. Under READ COMMITTED, a row lock only blocks someone writing the same row, and these are different rows, so there is nothing to block.
2Naming the Anomaly: Write Skew
Write skew happens when two transactions read an overlapping set of data, make decisions based on it, and then write to disjoint rows. Each write is valid given what that transaction saw, but the combination breaks an invariant, a rule that must always hold, that involves several rows.
READ COMMITTED allows it because each statement sees the latest committed data and only same-row writes conflict. Snapshot-based REPEATABLE READ, as in PostgreSQL, allows it too: each transaction works from its own snapshot, and the first-committer-wins check only covers rows both transactions wrote. Only true SERIALIZABLE, or explicit locking, tells the database that the reads matter.
3Fix 1: SERIALIZABLE Isolation
At SERIALIZABLE, PostgreSQL uses serializable snapshot isolation (SSI). It records what each transaction read, through predicate locks that do not block anyone, and notices the dangerous pattern: A read data that B then changed, and B read data that A then changed. No serial order of A and B could produce that, so PostgreSQL aborts one of them.
The aborted transaction must be retried from the start. On retry it counts again, sees 1, and refuses with our own message. SERIALIZABLE is the most general fix, because it protects every multi-row rule in the transaction, including ones we did not think of. The cost is more aborts under contention, and it must be applied to every transaction that takes part in the rule. InnoDB's SERIALIZABLE works differently, by making plain reads take shared locks, which typically turns this case into a deadlock that InnoDB resolves by rolling one back, so it also needs a retry.
4Fix 2: Lock the Rows We Read
We can make the reads conflict by locking them. SELECT ... FOR UPDATE takes a row lock on every row the query returns, so the second transaction waits at its read until the first commits, and then sees the new state.
Notice that we lock the rows and count them in Java; PostgreSQL refuses FOR UPDATE with an aggregate such as count(*). This fix works at READ COMMITTED because, after the wait, PostgreSQL re-checks the locked rows against their latest version. It only works when the rows that decide the rule already exist; if the rule were about rows being inserted, there would be nothing to lock.
5Fix 3: Materialise the Condition in One Row
The third option turns the multi-row rule into a single-row conflict. We add a row that represents the condition, such as shift.on_call_count, and every transaction that changes the rule must update it. Two concurrent updates of the same row always conflict, so the database serialises them.
- Can every transaction on this rule retry?YesSERIALIZABLE on all of themNoUse explicit locking
- Do the rows that decide the rule already exist?YesSELECT ... FOR UPDATE on themNoMaterialise the rule in one row
- Retry on 40001 or deadlock in every case
3 steps in order. Play them, or step through them one at a time.
The conditional update makes the check and the change one atomic statement: B's update waits for A's, re-evaluates on_call_count, finds 1, and affects 0 rows. The cost is that the counter must be kept correct by every write path, so it suits rules that are central enough to deserve their own row. A database CHECK constraint on the column, on_call_count >= 1, adds a final guard.
6Retry Logic Is Part of the Fix
With SERIALIZABLE, one transaction is aborted by design; with locking, a deadlock or lock timeout is possible. In both cases the right response is to run the whole transaction again. In Spring, those failures arrive as subclasses of ConcurrencyFailureException, so a small retry loop, or Spring Retry's @Retryable, placed outside the @Transactional method with two or three attempts and a short backoff, completes the fix. Without it, users see random errors instead of a clear 'you are the last one on call'.
7Follow-up questions
Would optimistic locking with a version column fix it?
Not on the individual on_call rows, because A and B update different rows with different versions. It works only if both update a shared row with a version, such as the shift row, which is the materialised condition approach.
Why not just check again after the update?
A second check in the same transaction still cannot see the other transaction's uncommitted change, so both would pass again. The check and the protection must be enforced by the database, through locks or serialisability.
Does this affect bookings that insert rows?
Yes, and it is harder there: two transactions both check that a room is free and both insert a booking. There is nothing to lock with FOR UPDATE, so we use SERIALIZABLE, lock a parent row, or an exclusion constraint in PostgreSQL that rejects overlapping ranges.
8Conclusion
In this answer, we reproduced write skew: two transactions read the same on-call count, each wrote a different row, and both committed under READ COMMITTED, which only blocks same-row writes; snapshot-based REPEATABLE READ allows it as well. We prevented it with SERIALIZABLE, where PostgreSQL detects the read and write dependencies and aborts one, with SELECT ... FOR UPDATE on the rows we read, or by materialising the rule in one row updated conditionally, and we added retry logic for the failures each fix can produce.
Open with
This is write skew. Each transaction reads the same condition, two doctors on call, decides it's safe, and writes a different row. Because the writes don't touch the same row, nothing conflicts, so under READ COMMITTED both commit and nobody is on call.
Then, if they want more
Snapshot-based REPEATABLE READ, like PostgreSQL's, allows it too, because it only detects conflicts on rows both transactions wrote. There are three ways I'd prevent it. First, SERIALIZABLE: PostgreSQL's serializable snapshot isolation tracks what each transaction read, sees that each read what the other changed, and aborts one with SQLSTATE 40001; that transaction retries, sees only one doctor and is refused.
It's the most general fix but every transaction on that rule has to use it. Second, lock what we read: select the on-call rows with FOR UPDATE, count them in code, and the second transaction waits until the first commits and then sees the new state. That works because the rows exist; for inserts it wouldn't.
Third, materialise the rule in a single row, like an on-call counter on the shift, and do a conditional update where the count is at least two, so the two transactions conflict on that one row. In every case I'd add a retry around the transactional method for serialization failures and deadlocks, which Spring surfaces as ConcurrencyFailureException subclasses.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Two doctors must always be on call. Each transaction checks that at least two are on...": https://scrivio-interview-library.netlify.app/databases/transactions/b0340d90d7/