Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Your platform has dozens of services on PostgreSQL READ COMMITTED, and incident reviews show several write skew bugs: double-booked rooms, overlapping discount campaigns, and two primary addresses per customer. Define an approach that teams can follow to find and prevent this class of bug.

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.

Write skew bugs share one shape: a transaction reads a set of rows, decides something, and writes a different row, so READ COMMITTED and even snapshot isolation see no conflict. The approach I would give teams is to recognise that shape, express the rule as a database constraint wherever possible, and otherwise protect it with SERIALIZABLE or an explicit lock on a parent row, with a shared retry wrapper, concurrency tests and production reconciliation queries to catch what slips through.

Why this question is asked

One write skew bug is an incident. Three different ones in a few months, a double-booked room, overlapping discount campaigns and two primary addresses, is a pattern, and it tells us the platform is missing a standard rather than one team missing a fix. Interviewers ask this at senior level to see whether we can turn a database concept into something dozens of teams can apply without becoming isolation experts. In this answer, we will recap what write skew is, show how to spot it in code reviews, and then build a layered approach: constraints first, then isolation or locks, then retries, tests and detection in production.

1A Quick Recap of Write Skew

Write skew happens when two transactions read the same data, each makes a decision that is correct on its own, and each writes a different row. Because the rows written do not overlap, the database sees no conflict and lets both commit. The rule that connected them, such as one primary address per customer, is broken.

At READ COMMITTED it is even easier to hit, because there is no snapshot protection at all. Take the address case. Two requests both run SELECT count(*) FROM address WHERE customer_id = 42 AND is_primary, both get 0, and both insert a new primary address. Nothing in the database knew about the rule, so nothing refused it.

2Teaching Teams to Recognise the Pattern

The first part of the approach is education with a very concrete rule of thumb: read a set, decide, write somewhere else. Any check-then-insert or check-then-update whose check reads rows other than the ones it writes is suspect. That covers the room booking (check for overlapping bookings, insert a new one), the campaigns (check for active campaigns in the date range, insert another) and the addresses (check for a primary, insert or flag another).

We teach it with the three incidents themselves, because engineers remember their own outages far better than textbook examples. Code reviewers get one question to ask: what stops two of these requests from running at the same moment? If the answer is nothing but the Java if statement, the code needs one of the protections below.

3Layer 1: Let the Database Enforce the Rule

Declarative constraints come first because they work regardless of isolation level, transaction design or which service writes the data. They are checked at the moment of the write, under the database's own locking, so two concurrent inserts cannot both pass.

SQL
-- One primary address per customer: a partial unique index
CREATE UNIQUE INDEX one_primary_address ON address (customer_id) WHERE is_primary;
-- No overlapping bookings for a room: an exclusion constraint
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE booking ADD CONSTRAINT no_overlap
EXCLUDE USING gist (room_id WITH =, tstzrange(starts_at, ends_at) WITH &&);
-- No overlapping campaigns for a product, same idea
ALTER TABLE campaign ADD CONSTRAINT no_overlapping_campaigns
EXCLUDE USING gist (product_id WITH =, daterange(starts_on, ends_on) WITH &&);
-- the second concurrent insert now fails:
-- ERROR: duplicate key value violates unique constraint (SQLSTATE 23505)
-- ERROR: conflicting key value violates exclusion constraint (SQLSTATE 23P01)

Notice that all three incidents from the question are expressible this way. The application still keeps its friendly check so users get a good message in the normal case, but the constraint is what makes the rule true. Foreign keys belong in the same layer for rules about references. The service maps 23505 and 23P01 to a clear conflict response.

4Layer 2: SERIALIZABLE or a Lock Row When a Constraint Cannot Say It

Some rules are too rich for a constraint, for example at least one doctor on call per shift, or total discounts in a campaign not above a budget. For those, the standard offers two tools. The first is to run only those transactions at SERIALIZABLE. PostgreSQL then tracks what each transaction read and aborts one of two transactions whose reads and writes could not have happened in any serial order, with SQLSTATE 40001. The rest of the service stays at READ COMMITTED.

The second is an explicit lock on a row that stands for the rule: SELECT id FROM campaign_group WHERE id = :g FOR UPDATE or SELECT id FROM shift WHERE id = :s FOR UPDATE at the start of the transaction. Every request that could break the rule for that group must take the same lock first, so they run one at a time. This is cheap and predictable, but it only works if every code path remembers to take the lock, which is why constraints are preferred.

Step throughChoosing protection for a cross-row rule
  1. Can a constraint express the rule?
    YesUnique, partial unique, exclusion or FKNoGo on
  2. Is there a natural parent row to lock?
    YesSELECT ... FOR UPDATE on itNoUse SERIALIZABLE for those transactions
  3. Wrap the transaction in the shared retry40001 and 40P01, new transaction each time
  4. Add a two-transaction concurrency testand a reconciliation query

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

5Layer 3: One Shared Retry Wrapper

SERIALIZABLE and locks both produce failures that are normal, not bugs: serialization failures (40001) and deadlocks (40P01). Teams should not each write their own retry loop, because the subtle parts are easy to get wrong. The platform library provides one that retries only those two SQL states, starts a brand-new transaction for every attempt, caps the attempts at a small number such as three, waits a little with jitter between them, and emits a metric per failure.

Java
public <T> T inTransaction(Supplier<T> work) {
for (int attempt = 1; ; attempt++) {
try {
return tx.execute(status -> work.get()); // new transaction per attempt
} catch (ConcurrencyFailureException e) { // Spring's parent for 40001 and 40P01
metrics.counter("db.retry", "attempt", String.valueOf(attempt)).increment();
if (attempt == 3) throw e;
sleep(ThreadLocalRandom.current().nextLong(20, 100) * attempt);
}
}
}

The reason the retry must sit outside the transaction is that PostgreSQL marks a failed transaction as aborted; retrying a statement inside it can never succeed.

6Layer 4: Tests and Detection in Production

Write skew does not appear in ordinary tests because requests run one after another. The standard gives teams a test template that forces the race. Both transactions read, then wait at a latch, then write, so the interleaving is guaranteed rather than lucky.

Finally, we assume something will slip through. For each critical invariant, a reconciliation query runs on a schedule and alerts when it finds a violation, for example SELECT customer_id FROM address WHERE is_primary GROUP BY customer_id HAVING count(*) > 1. A non-empty result is an incident ticket, and over time the count of findings tells us whether the approach is working. The review checklist, the test template and the reconciliation queries together make the standard something teams follow by default rather than something they have to remember.

7Follow-up questions

How would you write a test that reliably reproduces write skew?

I use two threads, each with its own transaction, against a real PostgreSQL in Testcontainers. Each thread runs the read part, the count of primary addresses, and then waits on a CountDownLatch or CyclicBarrier until both have read. Only then do both do their write and commit. That forces the dangerous interleaving every time. Without protection, the test asserts that the invariant is broken, which proves the test can see the bug. With the constraint or SERIALIZABLE, one thread must fail with 23505 or 40001 and the final state must hold the rule. Running it a few hundred times in a loop also shakes out timing assumptions.

Why not just make SERIALIZABLE the default everywhere?

It is a reasonable long-term goal, but it needs every entry point to retry, short transactions and no side effects inside them. Starting with constraints and targeted SERIALIZABLE fixes the known bugs now without a platform-wide migration.

Do advisory locks have a place here?

Yes, when there is no parent row to lock, pg_advisory_xact_lock on a key such as the room id gives the same serialising effect and is released automatically at commit. It has the same weakness as a lock row: every writer must use it.

8Conclusion

In this answer, we saw that write skew comes from reading a set, deciding and writing somewhere else, and that teams can learn to spot that shape in review. The approach puts declarative constraints first, such as partial unique indexes and exclusion constraints, then SERIALIZABLE or a lock on a parent row where constraints cannot express the rule, a shared retry wrapper for 40001 and 40P01, latch-based concurrency tests, and reconciliation queries that catch violations in production.

What to say in the interviewAbout 80 seconds aloud

Open with

All three incidents have the same shape: read a set, decide, write a different row. Neither READ COMMITTED nor snapshot isolation sees a conflict when the rows written don't overlap, so I'd give teams an approach in layers.

Then, if they want more

First, teach the pattern with our own incidents and add one review question: what stops two of these from running at once? Second, push rules into declarative constraints wherever possible, because they work at any isolation level.

A partial unique index on customer_id where is_primary fixes the addresses, and exclusion constraints with btree_gist and range overlap fix the rooms and the campaigns. Third, where a constraint can't express the rule, run just those transactions at SERIALIZABLE, or lock a parent row, like the shift or campaign group, with select for update at the start.

Fourth, give everyone one shared retry wrapper that retries 40001 and 40P01 in a new transaction each time, with a bounded number of attempts and metrics.

And finally, a concurrency test template that uses a latch to force both transactions to read before either writes, plus reconciliation queries in production that alert when an invariant is violated, so we learn about the next bug before customers do.

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 "Your platform has dozens of services on PostgreSQL READ COMMITTED, and incident reviews...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/dd93d3a63b/