Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Two doctors must always be on call. Each transaction checks that at least two are on call, then sets one doctor off call. Both run concurrently under READ COMMITTED and both succeed, leaving nobody on call. Name the anomaly and the ways to prevent it.

Try it yourself

Isolation levels: what a second read sees

Step through two transactions and see exactly when read committed and repeatable read give different answers.

Read this example as text

T1 at read committed

  1. T1 begins. Transaction T1 starts with isolation level READ COMMITTED. The row holds balance 100.
  2. T1 reads the balance. T1 reads 100. Under read committed each statement looks afresh at what is committed when the statement starts.
  3. T2 changes the row. A second transaction, T2, sets the balance to 150 but has not committed. The database keeps both versions: 100 is still the committed one.
  4. T1 reads again, before T2 commits. T1 reads 100 again. Neither level shows another transaction's uncommitted change, so there is no dirty read. T1 does not wait for T2 either.
  5. T2 commits. T2 commits. The committed balance is now 150.
  6. T1 reads a third time. T1 reads 150. The same query, inside one transaction, returned 100 and then 150. This is a non-repeatable read, and read committed allows it.
  7. T1 commits. T1 ends. A transaction that starts now reads 150 at either level.

T1 read 100, 100, then 150: a non-repeatable read.

T1 at repeatable read

  1. T1 begins. Transaction T1 starts with isolation level REPEATABLE READ. The row holds balance 100.
  2. T1 reads the balance. T1 reads 100. Under repeatable read this first read fixes T1's snapshot: T1 will keep seeing the data as it was committed at this moment.
  3. T2 changes the row. A second transaction, T2, sets the balance to 150 but has not committed. The database keeps both versions: 100 is still the committed one.
  4. T1 reads again, before T2 commits. T1 reads 100 again. Neither level shows another transaction's uncommitted change, so there is no dirty read. T1 does not wait for T2 either.
  5. T2 commits. T2 commits. The committed balance is now 150.
  6. T1 reads a third time. T1 still reads 100. Its snapshot was fixed at its first read, so T2's commit is invisible to it. The read is repeatable.
  7. T1 commits. T1 ends. A transaction that starts now reads 150 at either level.

T1 read 100 three times: its reads were repeatable.

What this example leaves out
  • Modelled on PostgreSQL and MySQL InnoDB, where a plain SELECT reads a snapshot and never waits for a writer.
  • SQL Server's default read committed uses locks instead: there, T1's second read would wait for T2 to finish.
  • Only reads are compared. What happens when T1 also writes the row (a lost update, or an error in PostgreSQL) is not modelled.

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.

Java
@Transactional // READ COMMITTED, PostgreSQL's default
public void goOffCall(long shiftId, String doctorId) {
long onCall = repo.countByShiftIdAndOnCallTrue(shiftId); // both sessions: 2
if (onCall < 2) throw new IllegalStateException("you are the last one on call");
repo.setOffCall(shiftId, doctorId); // A updates row A, B updates row B
}
// A and B click at the same moment: both commits succeed
// SELECT count(*) FROM on_call WHERE shift_id = 7 AND on_call; -- 0
Step throughTwo checks, two different rows, no conflict
Doctor A txDatabaseDoctor B tx
count on call for shift 7
2
count on call for shift 7
2
set row A off call, commit
set row B off call, commit

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.

Java
@Transactional(isolation = Isolation.SERIALIZABLE)
public void goOffCall(long shiftId, String doctorId) { ... same code ... }
// One of the two, at its UPDATE or COMMIT:
// ERROR: could not serialize access due to read/write dependencies among transactions
// SQLSTATE 40001

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.

Java
@Query(value = "SELECT * FROM on_call WHERE shift_id = :shift AND on_call FOR UPDATE", nativeQuery = true)
List<OnCall> lockOnCall(long shift);
// or with JPA: @Lock(LockModeType.PESSIMISTIC_WRITE) on a derived query
@Transactional
public void goOffCall(long shiftId, String doctorId) {
List<OnCall> rows = repo.lockOnCall(shiftId); // B waits here until A commits
if (rows.size() < 2) throw new IllegalStateException("you are the last one on call");
repo.setOffCall(shiftId, doctorId);
}
// A: sees 2, goes off call. B: waits, then sees 1, refused

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.

SQL
UPDATE shift SET on_call_count = on_call_count - 1
WHERE id = 7 AND on_call_count >= 2; -- rows affected: 1 for A, 0 for B
-- in Java: if rows affected == 0, refuse; otherwise set my on_call row to false
Step throughChoosing the fix
  1. Can every transaction on this rule retry?
    YesSERIALIZABLE on all of themNoUse explicit locking
  2. Do the rows that decide the rule already exist?
    YesSELECT ... FOR UPDATE on themNoMaterialise the rule in one row
  3. 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.

What to say in the interviewAbout 90 seconds aloud

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.
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/