Quick revision
The short answer
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.
What to remember
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.
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.
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.
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.
- Can a constraint express the rule?YesUnique, partial unique, exclusion or FKNoGo on
- Is there a natural parent row to lock?YesSELECT ... FOR UPDATE on itNoUse SERIALIZABLE for those transactions
- Wrap the transaction in the shared retry40001 and 40P01, new transaction each time
- 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.
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.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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/