Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A hospital rule says at least one doctor must stay on call per shift. Two doctors who are both on call press 'go off call' at the same moment. Each transaction runs SELECT count(*) FROM on_call WHERE shift_id = 7 AND on_call = true, sees 2, and updates its own row to false. Both commit at PostgreSQL REPEATABLE READ. Explain why this is possible and how 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.

Both transactions read the same two on-call rows, each decides it is safe to leave, and each updates a different row. PostgreSQL's REPEATABLE READ only stops two transactions that write the same row, so both commit and the rule breaks. This is called write skew, and we prevent it with SERIALIZABLE isolation, with SELECT ... FOR UPDATE on the rows we read, or by locking one shared row for the shift.

Why this question is asked

Most concurrency bugs we hear about involve two people changing the same thing. This one is different: the two transactions change different rows, and that is exactly why the database lets it happen. Interviewers ask it to see whether we know what an isolation level really promises, and how to protect a rule that spans more than one row. In this answer, we will recap how snapshot isolation works, reproduce the problem with two sessions, see why PostgreSQL allows it, and then go through three ways to prevent it.

1A Quick Recap of Snapshot Isolation

When transactions run at the same time, the isolation level decides how much each one is affected by the others. In PostgreSQL, REPEATABLE READ gives each transaction a snapshot: a frozen view of the database as it was when the transaction started. Whatever other transactions commit afterwards, ours keeps seeing its own snapshot.

Snapshot isolation does stop one kind of clash: two transactions updating the same row. The second one waits, and as soon as the first commits, its update fails with a serialization error (could not serialize access due to concurrent update). It does not compare what each transaction read with what the other wrote. That gap is where write skew lives.

The rule in our question, at least one doctor on call per shift, is called an invariant: something that must always be true. The database knows nothing about it unless we give it a way to see it.

2Reproducing the Problem With Two Sessions

We can reproduce the problem with two psql sessions side by side. Doctors A and B start on call for shift 7.

SQL
-- Session A -- Session B
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call
WHERE shift_id = 7 AND on_call; -- 2
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call
WHERE shift_id = 7 AND on_call; -- 2
UPDATE on_call SET on_call = false
WHERE shift_id = 7 AND doctor_id = 'A';
UPDATE on_call SET on_call = false
WHERE shift_id = 7 AND doctor_id = 'B';
COMMIT; -- succeeds
COMMIT; -- also succeeds
SELECT count(*) FROM on_call WHERE shift_id = 7 AND on_call; -- 0
Step throughTwo doctors go off call at the same moment
Session ADatabaseSession B
count on-call doctors for shift 7
2 (from A's snapshot)
count on-call doctors for shift 7
2 (from B's snapshot)
update row A to off call
update row B to off call
commit: no conflict, different rows
commit: no conflict, different rows

8 messages in order. Play them, or step through them one at a time.

Each session decided on a picture that was out of date. Nobody is left on call.

Notice that each session saw two doctors on call, so each decided it was safe to leave. Both commits succeed, and the shift is left with nobody on call.

3Why PostgreSQL Allows It

Each transaction made a correct decision based on its snapshot. The trouble is that each snapshot was out of date by the time the transaction acted on it, because the other transaction was changing the same group of rows.

PostgreSQL only checks for conflicts on the rows each transaction writes. Session A wrote row A and session B wrote row B. There is no overlap, so at REPEATABLE READ there is nothing to stop. The connection between the two changes exists only in our rule about the group, and the database was never told about it.

4Fix 1: Run the Transaction at SERIALIZABLE

At SERIALIZABLE, PostgreSQL also tracks what each transaction read. It notices that A read the rows B changed and B read the rows A changed, which could never happen if the two had run one after the other, and it aborts one of them.

SQL
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- same SELECT and UPDATE as above
COMMIT;
-- In one of the two sessions (at its UPDATE or its COMMIT):
-- ERROR: could not serialize access due to read/write dependencies among transactions
-- SQLSTATE 40001

Our application must catch this error and run the whole transaction again. On the retry, that doctor sees only one colleague on call and is refused. SERIALIZABLE is the most general fix, because it protects every rule we did not think to protect by hand, at the cost of more aborted transactions under heavy contention.

5Fix 2: Lock the Rows We Read With FOR UPDATE

Instead of only counting, we select the on-call rows with FOR UPDATE. That locks them, so the second transaction has to wait until the first one finishes, and then it reads the fresh data.

SQL
BEGIN;
SELECT doctor_id FROM on_call
WHERE shift_id = 7 AND on_call
FOR UPDATE; -- session B waits here until A commits
-- in the application: if fewer than 2 rows came back, ROLLBACK and refuse
UPDATE on_call SET on_call = false
WHERE shift_id = 7 AND doctor_id = :me;
COMMIT;

Notice that we select the rows themselves and count them in our code. PostgreSQL rejects SELECT count(*) ... FOR UPDATE with the error FOR UPDATE is not allowed with aggregate functions, because a count is not a row it can lock.

6Fix 3: Lock One Row That Stands for the Rule

We can also lock a single shared row, such as the row for shift 7 in a shifts table, at the start of every 'go off call' request. Requests for the same shift then queue up one at a time.

SQL
SELECT id FROM shift WHERE id = 7 FOR UPDATE; -- every change to shift 7 waits its turn here
Step throughChoosing a fix for a rule across rows
  1. Can we afford retries under contention?
    YesSERIALIZABLE protects every ruleNoLock explicitly instead
  2. Do the rows that decide the rule already exist?
    YesSELECT ... FOR UPDATE on those rowsNoLock a parent row or add an exclusion constraint
  3. Retry the whole transaction when the database refusesfor every fix

3 steps in order. Play them, or step through them one at a time.

This approach also covers a harder case: rules about rows that do not exist yet. If the rule were 'no two bookings may overlap in one room', both transactions would insert new rows, so there would be nothing to lock with FOR UPDATE and both would pass. For those cases we lock a parent row like this, use SERIALIZABLE, or let the database enforce the rule with an exclusion constraint.

7Retrying the Whole Transaction

Whichever fix we choose, a transaction can now fail or wait because of another one, so the application must be ready to run it again from the start. In Spring, serialization failures and lock failures are translated into subclasses of ConcurrencyFailureException, which makes a retry easy to write (check your Spring version for the exact subclass).

Java
for (int attempt = 1; ; attempt++) {
try {
goOffCall(shiftId, doctorId); // @Transactional method on another bean
break;
} catch (ConcurrencyFailureException e) {
if (attempt == 3) throw e; // give up after a few tries
}
}

8Follow-up questions

Write the exclusion constraint for a room booking table.

With the btree_gist extension enabled: ALTER TABLE booking ADD CONSTRAINT no_overlap EXCLUDE USING gist (room_id WITH =, tstzrange(starts_at, ends_at) WITH &&); The database then refuses any booking whose time range overlaps an existing booking for the same room, even when both arrive at the same moment.

Why does FOR UPDATE work here but not for double booking?

Here the rows that decide the rule already exist, so locking them makes the second transaction wait. In double booking, the conflicting row is the other transaction's new insert, which does not exist yet when we read, so there is nothing to lock.

Does MySQL behave the same way?

Yes, for plain reads. In InnoDB's REPEATABLE READ, an ordinary SELECT reads from a snapshot, so the same write skew can happen. Locking reads (SELECT ... FOR UPDATE) or SERIALIZABLE prevent it there too.

9Conclusion

In this answer, we saw that write skew happens when two transactions read the same rows, decide independently, and write different rows. PostgreSQL's REPEATABLE READ only detects two writes to the same row, so it lets both commit. We can prevent it with SERIALIZABLE, by locking the rows we read with FOR UPDATE, or by locking one shared row that stands for the rule, and in every case the application must retry the whole transaction when the database refuses it.

What to say in the interviewAbout 50 seconds aloud

Open with

This is write skew. Under PostgreSQL's REPEATABLE READ each transaction reads from its own snapshot, so both see two doctors on call, and each updates a different row.

Then, if they want more

Snapshot isolation only detects conflicts when two transactions write the same row, so both commit and the rule across rows breaks.

To prevent it I would either run the operation at SERIALIZABLE, where PostgreSQL tracks read-write dependencies and aborts one transaction with SQLSTATE 40001, or lock the rows I read with SELECT FOR UPDATE so the second transaction waits and then sees the new state.

If the rule depended on rows that may not exist yet, such as overlapping bookings, I would lock a parent row, use SERIALIZABLE, or use an exclusion constraint. In each case the application retries the whole transaction.

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 "A hospital rule says at least one doctor must stay on call per shift. Two doctors who...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/72d4893b57/