Sub topic 11
Write skew: the anomaly snapshots allow
This chapter assumes you know what a snapshot is in MVCC, what REPEATABLE READ promises in PostgreSQL, and how lost updates and phantom reads work. You should also be comfortable with BEGIN, COMMIT and ROLLBACK.
What write skew is
Write skew happens when two concurrent transactions each read an overlapping set of rows, decide something from what they read, and then write to different rows. Each transaction's decision was valid in its own snapshot. Both commit, and together they break a rule that neither one broke alone.
Snapshot isolation misses this anomaly because it only checks write-write conflicts. Two transactions that update the same row collide, and one of them waits or aborts. Two transactions that update different rows never collide, even when one's write would have changed the other's read.
Write skew is the standard example of an anomaly that REPEATABLE READ allows in snapshot-based engines. It appears because the snapshot is stable (the transaction keeps seeing its own view) while the world moves on underneath it.
A worked example
The application rule is that at least one doctor must stay on duty. The setup is:
CREATE TABLE on_call (
doctor text PRIMARY KEY,
on_duty boolean NOT NULL
);
INSERT INTO on_call VALUES ('alice', true), ('bob', true);Alice and Bob each try to go off duty at the same moment. Each transaction checks that a colleague remains, then updates its own row.
Here is the same schedule in SQL:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call WHERE on_duty; -- 2
-- Session B
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call WHERE on_duty; -- 2
-- Session A
UPDATE on_call SET on_duty = false WHERE doctor = 'alice';
COMMIT;
-- Session B
UPDATE on_call SET on_duty = false WHERE doctor = 'bob';
COMMIT; -- succeeds
SELECT count(*) FROM on_call WHERE on_duty; -- 0Neither transaction had a dirty read, a non-repeatable read, or a lost update. Each one saw a consistent snapshot, and each update touched a row the other never wrote. The result still cannot come from any serial order. If A ran first, B would have read a count of 1 and stopped.
Why snapshots miss it
Snapshot isolation (the first-committer-wins rule in PostgreSQL's REPEATABLE READ) detects one thing: two concurrent transactions wrote the same row version. In the example the write sets are {alice} and {bob}. They do not overlap, so nothing is flagged.
The dependency runs the other way. A read something that B later wrote, and B read something that A later wrote. These are called read-write dependencies (or anti-dependencies). Snapshot isolation does not track them. A cycle of two such dependencies, with each transaction reading what the other overwrites, cannot be serialized.
Write skew is also a phantom problem in disguise. The check count(*) WHERE on_duty reads a predicate, not a single row. The conflicting write changes which rows match that predicate. Row locks on rows you already read do not protect a predicate. That is why a snapshot cannot help you here and why some fixes lock more than you might expect.
Variants you will meet
The shape is always the same: read a set, decide, write elsewhere. These are typical forms:
- Booking a resource. Two users check that a room is free for a time range, then each inserts a reservation. The rows inserted are different, but the ranges overlap.
- Unique names without a constraint. Two sessions check that a username does not exist, then each inserts it. A
UNIQUEconstraint would catch this, but a rule like "at most five bookings per day" has no simple constraint. - Spending against a total. Two transactions each read the sum of several accounts, confirm the sum is positive after a withdrawal, and withdraw from different accounts.
- Double-spending a counter. Two transactions each read a count of open slots and insert a row to take one.
Fixes
You have four main options. They differ in cost and in how much of the problem they hide from application code.
1. Use SERIALIZABLE
In PostgreSQL, SERIALIZABLE uses serializable snapshot isolation (SSI). It runs on top of ordinary snapshots and watches read-write dependencies. When it finds a dangerous pattern, it aborts one transaction with SQLSTATE 40001 (serialization_failure).
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM on_call WHERE on_duty;
UPDATE on_call SET on_duty = false WHERE doctor = 'alice';
COMMIT;If both sessions run this at the same time, one of them fails with an error similar to could not serialize access due to read/write dependencies among transactions. The failure can come from a statement or from COMMIT itself, so your code must handle it in both places. The aborted transaction must be retried from the start, and on retry it reads a count of 1 and stops.
A retry wrapper looks like this (Python with psycopg 3):
import psycopg
from psycopg import errors
def go_off_duty(conninfo, doctor, attempts=5):
for _ in range(attempts):
try:
with psycopg.connect(conninfo) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
on_duty = conn.execute(
"SELECT count(*) FROM on_call WHERE on_duty"
).fetchone()[0]
if on_duty < 2:
return False # rule would be violated
conn.execute(
"UPDATE on_call SET on_duty = false WHERE doctor = %s",
(doctor,),
)
return True # leaving the with-block commits
except errors.SerializationFailure:
continue # retry the whole transaction
raise RuntimeError("gave up after repeated serialization failures")The retry must repeat the reads as well as the writes, because the decision depends on them.
2. Lock the rows you read
If you read the rows with SELECT ... FOR UPDATE, concurrent transactions that read the same rows queue behind each other. Lock the whole set the decision depends on:
BEGIN; -- READ COMMITTED is enough here
SELECT doctor FROM on_call WHERE on_duty FOR UPDATE;
-- The application counts the rows returned. If fewer than 2, ROLLBACK.
UPDATE on_call SET on_duty = false WHERE doctor = 'alice';
COMMIT;Session B's SELECT ... FOR UPDATE blocks until A commits. Under READ COMMITTED, B then re-checks the locked rows. It sees that alice is no longer on duty and gets only bob. Its count is 1, so it stops.
Two limits apply:
- PostgreSQL rejects
FOR UPDATEwith aggregates such ascount(*), so you select the rows and count them in the application. - The lock covers only rows that exist. If the rule depends on rows that might be inserted (the room booking case), there is nothing to lock yet.
Under REPEATABLE READ in PostgreSQL, FOR UPDATE on a row changed after your snapshot fails with 40001 instead of waiting and re-reading. You must retry in that case too.
3. Materialize the conflict
When there are no rows to lock, create one. Add a row that represents the shared resource and lock it first. Every transaction that touches the resource takes the same lock:
CREATE TABLE rooms (room_id int PRIMARY KEY);
INSERT INTO rooms VALUES (7);
BEGIN;
SELECT room_id FROM rooms WHERE room_id = 7 FOR UPDATE; -- serializes bookers of room 7
-- check for overlapping reservations, then INSERT the new one
COMMIT;This turns a phantom conflict into an ordinary row-lock conflict. It is simple and portable, but you must remember the lock in every code path that touches the resource.
4. Push the rule into the database
Where possible, let the database enforce the rule. A UNIQUE constraint, a foreign key, or an exclusion constraint is checked at write time and works under every isolation level. For overlapping reservations in PostgreSQL, an exclusion constraint with a range type removes the whole problem. Not every rule can be written this way. "At least one doctor on duty" cannot, which is why the example needs the other fixes.
How engines treat write skew
| Engine | Level you ask for | Write skew possible? | Notes |
|---|---|---|---|
| PostgreSQL | REPEATABLE READ | Yes | Snapshot isolation. |
| PostgreSQL | SERIALIZABLE | No | SSI. One transaction aborts with `40001`. |
| MySQL InnoDB | REPEATABLE READ | Yes for plain reads | Locking reads (`FOR UPDATE`) see the latest data and take locks. |
| MySQL InnoDB | SERIALIZABLE | No | Plain `SELECT` becomes a shared locking read. Expect deadlocks and lock waits instead of `40001`. |
| SQL Server | SNAPSHOT | Yes | Also an optimistic snapshot model. |
| SQL Server | SERIALIZABLE | No | Range locks. Blocking, not aborting. |
| Oracle | SERIALIZABLE | Yes | Implemented as snapshot isolation, so the name overstates the guarantee. |
Do not assume a level named SERIALIZABLE prevents write skew. Check what the engine does.
Detection and testing
Write skew is a race. It rarely appears in single-user tests, and it can stay hidden for months. To reproduce it, open two sessions and run the schedule by hand, as in the worked example. The ordering that matters is both reads before either commit.
In an automated test, use two connections and a barrier so each transaction finishes its read before either one writes. Then assert the invariant at the end. With the fix in place, the test should show one of three outcomes: a 40001 error, a blocked session that then reads fresh data, or a rejected write.
Under SERIALIZABLE, SSI can raise false positives. It aborts some transactions that would have been safe, because it tracks dependencies conservatively. Plan for a few extra retries. An index on the columns you filter by also reduces false positives, since SSI tracks reads at a finer granularity when it can use an index.
Common errors
- Using REPEATABLE READ and assuming it is serializable. It stops phantoms in PostgreSQL but not write skew.
- Locking only the row you update. In the example, locking alice's row does not stop Bob's transaction, because Bob never touches it.
- Using SERIALIZABLE with no retry. Users see sporadic
40001errors that look like bugs. - Retrying only the failed statement. The whole transaction must run again, including its reads.
- Retrying forever. Cap the attempts and add a short randomized delay.
- Checking the rule in application code before
BEGIN. The check and the write must sit inside the same protected transaction.
Exercise
Two transactions run at REPEATABLE READ in PostgreSQL on a table seats(seat_id int PRIMARY KEY, taken_by text). Each runs SELECT count(*) FROM seats WHERE taken_by IS NOT NULL, sees 99 of a 100-seat limit, and then updates a different free seat to a different user. Both commit. Is this a lost update or write skew, and name two ways to prevent it.
Show answer
It is write skew. The write sets are different rows, so there is no write-write conflict and snapshot isolation allows both commits, which gives 101 taken seats. Two fixes: run the transactions at SERIALIZABLE and retry on 40001, or have every booking transaction first lock a single shared row (for example a venues row) with SELECT ... FOR UPDATE, which materializes the conflict and serializes the bookings.
Exercise
Why can SELECT count(*) FROM on_call WHERE on_duty FOR UPDATE not be used in PostgreSQL to fix the doctor example, and what do you write instead?
Show answer
PostgreSQL does not allow FOR UPDATE with aggregate functions. Write SELECT doctor FROM on_call WHERE on_duty FOR UPDATE, which locks the matching rows, and count the returned rows in the application before deciding whether to update.