Isolation Anomalies and Write Skew
See why stable snapshots do not automatically protect cross-row rules.
database, postgresql, isolation, write skew, serializable, concurrencyA stable view can still permit an unsafe decision
PostgreSQL READ COMMITTED can allow nonrepeatable reads across statements.
PostgreSQL REPEATABLE READ prevents nonrepeatable and phantom reads, but
still permits serialization anomalies. A business invariant spanning multiple
rows needs an appropriate concurrency strategy.
SQL illustration
Assume on_call(name, active) has Ada and Bo active, and at least one must
remain active. In this prepared two-session schedule, both transactions
use REPEATABLE READ; both count before either updates or commits. Each
application decides to turn off its own row only because it saw a count of 2.
No other constraint enforces the rule:
A: BEGIN ISOLATION LEVEL REPEATABLE READ;
B: BEGIN ISOLATION LEVEL REPEATABLE READ;
A: SELECT count(*) FROM on_call WHERE active; -- 2
B: SELECT count(*) FROM on_call WHERE active; -- 2
A: UPDATE on_call SET active = false WHERE name = 'Ada';
B: UPDATE on_call SET active = false WHERE name = 'Bo';
A: COMMIT;
B: COMMIT;
Because the writes affect different rows, both can commit in this schedule: zero people remain active. This is write skew, not a dirty read.
See the reasoning
Follow the example one step at a time
Trace a write-skew anomaly across two stable snapshots. This is a prepared teaching demonstration, not live code execution.
Start with two people on call
Ada: on call Bo: on call Rule: at least one must remain
Both rows are initially on call and each transaction will use REPEATABLE READ.
Protect the rule
When all relevant transactions use PostgreSQL SERIALIZABLE, the system
detects dangerous dependencies and may abort one transaction rather than
allow both to commit a nonserializable outcome. Handle 40001 by safely
retrying the complete transaction, including reads and decisions. Other
approaches can include an appropriate shared lock or a schema design that
enforces the rule; they must cover all writers and handle new or missing rows.
Choose and test a strategy for the actual invariant, not just this example.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
