Chapter 17 — Transactions, ACID, Isolation & Concurrency Anomalies
Part IV · Data & Storage | Prerequisites: Ch 15–Ch 16 | Builds: Pulsely's slot-booking + appointment write made correct under concurrency
Earlier you built a schema the engine will defend — keys, constraints, the database as a trust boundary that refuses bad rows — and learned to shape that schema around how it's read and written. This chapter is where both promises get tested by the one thing every previous chapter has been quietly circling: two requests arriving at the same instant. A single request, alone, against a correctly-modeled schema, is easy. The hard part of a backend — the part that makes it a backend and not a spreadsheet — is that the state is shared and accessed concurrently, as warned earlier. Two of those requests can each be individually correct and still, together, corrupt your data.
This is the single-node correctness chapter. Everything here — atomicity, isolation, the anomaly catalog, MVCC, locking — is the foundation that distributed consistency later generalizes to many machines. Get concurrency right on one box first, because the distributed version is strictly harder and assumes you already think in these terms. This is the deepest, most leverage-dense chapter in Part IV. Read it slowly; the 9:00 slot you couldn't double-book earlier finally gets booked correctly here.
Pulsely actually has three distinct concurrency problems, and they need three different tools — hold this map as you read:
- No double-booking — a finite appointment slot must go to exactly one patient (solved with slot locks or a constraint; the running example of this chapter).
- Exactly-once claim submission — a claim must reach the clearinghouse once, never twice, even under retries (solved with idempotency and, later, an outbox).
- Concurrent charting — two clinicians must not silently clobber each other's edits to the same note (solved with optimistic locking and note versioning).
1. The problem: two correct requests, one corrupted result
Back to the schedule. Pulsely has one open slot on Dr. Okafor's calendar — 9:00 AM, capacity = 1. Two front-desk coordinators — call them Ana and Boris — tap Book within the same 40-millisecond window, one booking a patient from the front-desk kiosk, one from the call-center laptop. Your handler does the obvious, reasonable thing:
// The naïve "book slot" handler. Every line is correct in isolation.
async function bookSlot(slotId: string, patientId: string) {
const { rows } = await db.query(
'SELECT capacity FROM appointment_slots WHERE id = $1', [slotId]);
const cap = rows[0].capacity; // (1) read
if (cap < 1) throw new SlotFull(); // (2) check
await db.query(
'UPDATE appointment_slots SET capacity = capacity - 1 WHERE id = $1', [slotId]); // (3) write
await db.query(
'INSERT INTO appointments (slot_id, patient_id) VALUES ($1, $2)', [slotId, patientId]);
}
Read the code in isolation and it is flawless. Read it as two copies running interleaved and it is a disaster:
time ──────────────────────────────────────────────────────────────▶
Ana : SELECT cap → 1 ── check 1≥1 ✓ ─────── UPDATE cap=0 ── INSERT appt
Boris : SELECT cap → 1 ── check 1≥1 ✓ ──────────── UPDATE cap=0 ── INSERT appt
▲
both read 1, both passed the check,
both decremented, both booked the slot
Final state: capacity = 0 (one decrement visibly "lost"), two appointments, one slot. Ana's patient keeps the room; Boris's patient shows up at 9:00 to find it already occupied, and the front desk eats an angry double-booking. Notice the shape of the bug: there is no line of code you can point to and call wrong. The defect lives between two correct executions, in the interleaving — which is precisely why it is invisible to the people who wrote it.
It was invisible in development, too, and that's not bad luck — it's structural. Your tests run one request at a time, on the happy path, single-threaded. A test that fires bookSlot once and asserts "one appointment, capacity 0" passes forever. The race needs concurrency plus timing to manifest, so it sails through CI, ships on a Tuesday, and detonates the first time a sought-after provider's calendar opens up or a flu-season surge doubles your call volume. The bug was always there; the conditions to express it weren't.
Now ask why this is even possible. The deeper answer is the reason transactions exist at all. "Book an appointment" is, to the clinic, one indivisible act. But to the storage engine it is several separate mutations — a read, an update of appointment_slots, an insert into appointments — and the engine, left to itself, only natively guarantees that each single statement is atomic. The gap between "one clinical operation" and "several engine operations" is the gap every concurrency bug lives in. A transaction is the construct that closes it: it lets you tell the engine "treat these several statements as one indivisible act, and protect it from everyone else's indivisible acts." This chapter is about what that protection actually does, where it's weaker than you think, and how to ask for exactly as much of it as you need.
🧭 A useful distinction. Wrapping the code above in
BEGIN ... COMMITmakes it atomic and durable — but at the default isolation level it does not fix the double-booking. Atomicity says "all three writes happen or none do." It says nothing about whether Boris's transaction can see, or must wait for, Ana's. Beginners conflate these. A transaction is necessary here, but it is not, by itself, sufficient. The sufficiency comes from isolation, and isolation is a dial — not an on/off switch.
2. The mental model: timelines, arbitration, and a dial
Hold three pictures.
A transaction is a proposed alternate timeline. When you BEGIN, you start writing a private branch of history: a sequence of reads and writes that the database will either splice into the one true global timeline all at once (COMMIT) or throw away entirely (ROLLBACK). There is no middle. Half a transaction never reaches the timeline — not after a crash, not after an error, not ever. Think of COMMIT as the moment your branch is fast-forward-merged into reality, atomically, as a unit.
Concurrency control is the database arbitrating between overlapping timelines. Many transactions propose branches at once. The engine's job is to weave the committed ones into a single global history that is equivalent to some serial order — some sequence in which the transactions ran one-at-a-time with no overlap. In plain terms, the final data looks exactly as if the transactions had politely queued and run one after another — even though they actually overlapped. If running Ana-then-Boris and Boris-then-Ana both give a legal result, and the real overlapped run matches one of them, the engine did its job at the strongest setting. Concurrency control is the referee that makes a chaotic pile of overlapping branches behave as if they'd queued politely.
Isolation level is the dial that controls how much of other in-flight timelines yours is allowed to see. Crank it high and the database does more bookkeeping, more locking, more aborting on your behalf, so your transaction behaves as if it were alone in the universe — at the cost of throughput. Turn it low and the database does less, runs faster, and exposes you to specific, named ways that other timelines can leak into yours. The whole craft of this chapter is choosing where to set that dial per transaction, on purpose.
🧭 Mental model. Two postures toward a possible conflict, and you will choose between them constantly:
- Pessimistic — "Assume there will be a fight. Grab a lock first, make everyone else wait their turn." Predictable, no wasted work, but it serializes contended rows and can deadlock.
- Optimistic — "Assume there won't be a fight. Don't lock; just check at the end whether anyone changed what I read, and if so, abort and retry." Free when conflicts are rare, wasteful when they're common. (If you've done optimistic UI updates in React — render the change immediately, roll back if the server rejects — this is the same bet, moved to the database.)
Same goal — a correct result — opposite default assumption about how likely conflict is. Pick by how contended the data actually is, not by taste.
The last reframe is the one that turns this from intimidating to learnable: anomalies are not database bugs. A dirty read, a lost update, a phantom — these are not the database malfunctioning. They are the documented, specified price of the isolation level you selected, very often without realizing you selected it (you took the default). Once you see anomalies as a published menu of "what this dial setting permits," the fear evaporates. You're not hunting mysterious corruption; you're reading the spec of a setting and deciding whether its price is acceptable for this operation.
3. Theory & invariants
ACID, stated precisely
People recite ACID; few state it sharply. The four letters are independent properties that engineers constantly conflate. Pull them apart.
Atomicity — all or nothing across the write set. Every write in the transaction lands, or none does. A crash, error, or rollback mid-transaction leaves the database as if the transaction never began. Atomicity is about the boundary of a single transaction, not about other transactions at all.
Consistency — the transaction moves the database from one valid state to another, with respect to declared constraints. This is the most over-sold letter. The database guarantees only that your declared invariants — primary keys, foreign keys, CHECK, UNIQUE, NOT NULL from your relational schema — hold at commit. It does not magically know your clinical rules. "A claim's total equals the sum of its line items" is consistency only if you encoded it as a constraint; otherwise consistency is your job, enforced by the logic inside the transaction. The "C" is mostly a promise you keep, with the engine guarding the subset you wrote down as constraints.
Isolation — concurrent execution yields a result equivalent to some serial schedule (at the strongest level). This is the letter this chapter is really about, and the only one that's a dial rather than a guarantee you either have or don't. Lower the dial and you get weaker equivalence — "equivalent to some serial order, except for the following named leaks."
Durability — once COMMIT returns success, the data survives a crash. Power loss, kernel panic, pulled plug — a committed transaction is still there on restart. This is purchased by the write-ahead log: the commit's WAL record is fsync'd to durable storage before COMMIT returns. Durability means "the log says it happened," not "the data page was written" — the mechanics are a later chapter's territory; here, just hold that COMMIT returning is a durability promise.
🔑 The independence invariant. Atomicity, Isolation, and Durability are separate knobs. The default configuration of nearly every database gives you atomic + durable + weakly isolated: your three writes are all-or-nothing and crash-safe, and yet Boris can still double-book the slot, because weak isolation let his timeline read stale truth. When someone says "I wrapped it in a transaction, so it's safe," they have bought atomicity and durability and assumed isolation they did not pay for. Always ask the isolation question separately.
The anomaly catalog
An anomaly is a specific way a weaker isolation level lets another transaction's timeline leak into yours, producing a result no serial order could. There are five you must be able to name, recognize, and reproduce. Learn them by their concrete Pulsely failure, not their textbook name.
Dirty read — you read another transaction's uncommitted write. Boris's booking reads an appointment Ana's transaction marked confirmed, then Ana's transaction rolls back (the patient's eligibility check came back inactive). Boris acted on a fact that never became true. Almost every database forbids this by default; it's the floor.
Non-repeatable read — you read the same row twice in one transaction and get two different committed values. Your billing transaction reads claim #42's charge amount as $1,200 (the fee for its CPT procedure code), does some work, reads it again to build the remittance summary — and a concurrent, committed edit changed it to $1,400 in between. Same row, same transaction, two answers. The "row" you're looking at shifted under you.
Phantom — you run the same query predicate twice and new rows appear. Your transaction counts "booked appointments for Dr. Okafor on this date" → 12, applies a rule that depends on the count (her daily cap is 13), re-counts → 13, because a concurrent transaction inserted a thirteenth matching booking. No row you read changed; the set of rows matching your predicate changed. Non-repeatable read is about a row mutating; a phantom is about the population mutating.
Lost update — two read-modify-write cycles overwrite each other. This is the double-booking from §1, named. Both transactions SELECT capacity → 1, both decide "1 is enough," both UPDATE capacity = 0. The final value reflects one decrement, not two. One update was silently lost. This is the single most common and most expensive concurrency bug in line-of-business code: counters that drift low, balances that double-spend, slots that double-book.
Write skew — the subtle one. Two transactions read the same rule, both see it satisfied, then each writes a different row. Individually both look safe — but the two writes together break the rule. (The two-provider example just below makes this concrete.) Pulsely requires "at least one on-call provider on duty at all times." Two providers, Mara and Nils, both want to go off-call at the end of their shift. Each transaction reads SELECT count(*) FROM providers WHERE on_call = true → 2, each reasons "2 ≥ 1, so it's safe for me to sign off," each updates its own row to on_call = false. Both commit. Now zero providers are on call — an invariant violated by two writes to disjoint rows, neither of which was individually wrong. There's no single row both touched, so simple row-locking doesn't catch it. Write skew is the anomaly that survives even snapshot isolation, and the reason "Serializable" exists as a distinct level.
🔑 The lost-update vs write-skew invariant. Lost update is a write-write conflict on the same row — two transactions clobber one cell. Write skew is a conflict across different rows that together break a constraint spanning them. The cure differs accordingly: lost update yields to a lock or atomic update on the row; write skew needs either a constraint that materializes the invariant, a lock on the thing being counted, or true Serializable isolation. Misdiagnosing one as the other is how engineers "fix" a bug that comes back.
Isolation levels and exactly what each prevents
Now the dial's settings. Four levels matter; learn each by the anomaly it stops.
- Read Committed — prevents dirty reads only. You never see uncommitted data, but each statement gets a fresh view of the world, so non-repeatable reads, phantoms, lost updates, and write skew are all still possible. This is PostgreSQL's default, and MySQL's and Oracle's. Most code you've ever written ran here without you knowing.
- Repeatable Read — prevents dirty and non-repeatable reads. Your transaction takes a consistent snapshot at its start, so every row you re-read returns the same value. In the SQL standard it still permits phantoms — but PostgreSQL's Repeatable Read is implemented as full snapshot isolation and also blocks phantoms. (Hold that thought; the vendor nuance below is the whole point.)
- Snapshot Isolation — every read sees a consistent snapshot as of the transaction's start; prevents dirty reads, non-repeatable reads, and phantoms. But it permits write skew — the two providers both sign off. Snapshot is fast and feels rock-solid until a multi-row invariant bites.
- Serializable — prevents everything above, including write skew. The committed result is guaranteed equivalent to some serial order, full stop. This is the strongest guarantee and the most expensive: the engine must either lock aggressively or track dependencies and abort transactions that would break serializability.
Here is the matrix to burn into memory:
│ dirty │ non-repeat │ phantom │ lost │ write
│ read │ read │ │ update │ skew
───────────────────┼───────┼────────────┼─────────┼────────┼───────
Read Committed │ ✗ │ allowed │ allowed │ allowed│ allowed
Repeatable Read* │ ✗ │ ✗ │ allowed*│ ✗** │ allowed
Snapshot Isolation │ ✗ │ ✗ │ ✗ │ ✗** │ allowed
Serializable │ ✗ │ ✗ │ ✗ │ ✗ │ ✗
───────────────────┴───────┴────────────┴─────────┴────────┴───────
✗ = prevented. * SQL-standard RR allows phantoms; PostgreSQL RR = snapshot, blocks them.
** Snapshot — and PostgreSQL's RR, which *is* snapshot — blocks the classic lost update via first-updater-wins; still permits write skew. (Standard RR also excludes lost update, by holding read locks to commit.)
🔑 The vendor-semantics invariant. The SQL standard's level names specify a minimum guarantee — "at least this strong" — not an implementation. Real engines diverge wildly under the same label. PostgreSQL "Repeatable Read" is snapshot isolation (stronger than the standard requires). Oracle "Serializable" was historically snapshot isolation (weaker than the name — it permits write skew). MySQL InnoDB's Repeatable Read uses next-key locking that blocks many phantoms the standard allows. Never reason from the label. Read your engine's actual documented semantics and, ideally, reproduce the anomaly to confirm. The name on the dial is marketing; the behavior is what ships.
📎 Borrowed on credit: distributed consistency. Everything in this beat assumes one database that sees every transaction and can impose a single serial order. The moment your data lives on several machines — replicas, shards, multiple regions — "equivalent to some serial order" becomes a far harder, sometimes impossible, guarantee, and you meet the CAP theorem, linearizability, and replication lag. That is the explicit subject of Chapter 23, and it is built directly on the single-node vocabulary you're learning now. Master serializability on one node first; the distributed version is this chapter with the ground removed.
4. Under the hood: MVCC, snapshots, and locks
How does PostgreSQL let many readers and writers loose on the same rows without them constantly blocking each other? The answer — MVCC, Multi-Version Concurrency Control (the engine keeps several versions of a row alive at once so different readers can each see the one that was current when they started) — is the most important storage mechanism in this chapter, and it explains nearly every behavior above.
Versions, not in-place mutation
The core trick: an UPDATE does not overwrite a row. It writes a new version of the row and leaves the old one in place. Each row version (each tuple) carries two hidden system columns:
xmin— the ID of the transaction that created this version.xmax— the ID of the transaction that deleted or superseded it (0/null while live).
A transaction has a snapshot: the set of transaction IDs whose effects are visible to it. Think of each row version as a React list item carrying a createdBy and a deletedBy stamp. Your snapshot is a filter over those stamps. When you read, the engine shows you the one version whose creator had already committed before you started, and whose deleter had not yet committed — that is the row exactly as it looked the instant your transaction began. In xmin/xmax terms: the version whose xmin is visible to your snapshot and whose xmax is not. Different transactions, holding different snapshots, looking at the same logical row, legitimately see different versions of it at the same wall-clock instant.
logical row: claim #42, charge amount edited twice
┌────────────────────────────────────────────────────────┐
│ v1 charge=1200 xmin=100 xmax=140 (superseded) │ ◀─ Txn with old snapshot still sees v1
│ v2 charge=1400 xmin=140 xmax=170 (superseded) │
│ v3 charge=1500 xmin=170 xmax=0 (live / current) │ ◀─ Txn with new snapshot sees v3
└────────────────────────────────────────────────────────┘
dead versions (v1, v2) wait to be reclaimed by VACUUM
The payoff is the headline property of MVCC: readers never block writers, and writers never block readers. A biller writing version v3 doesn't stop a report from reading v2; it simply sees the version its snapshot points at. This is why a long analytics query can read a consistent snapshot of the whole table while writes pour in around it — they're writing new versions it can't see, not blocking on it.
🏭 Those dead versions don't vanish on their own. Every
UPDATEandDELETEleaves tombstones that accumulate as bloat until a background process reclaims them. In PostgreSQL that process isVACUUM, and managing it — autovacuum tuning, transaction-ID wraparound, table bloat — is real operational work. That whole operational surface belongs to Chapter 19; here you only need the concept that versions are created cheaply and reclaimed later, which is the price MVCC pays for never blocking reads.
When the snapshot is taken is the isolation level
Here is the single most elegant fact in the chapter. The difference between Read Committed and Repeatable Read is almost entirely one decision: when do you take your snapshot?
- Read Committed: a fresh snapshot is taken at the start of each statement. So a second
SELECTin the same transaction sees everything committed up to that statement's moment — which is exactly why values can change between two reads (non-repeatable read). - Repeatable Read / Snapshot: the snapshot is taken once, at the first statement of the transaction, and frozen. Every read for the rest of the transaction sees that one consistent moment — which is exactly why re-reads repeat and phantoms vanish.
That's it. "Repeatable read" is not a pile of extra locks; it's "take the snapshot once and keep it." Understanding this turns the isolation table from memorization into derivation.
Locks: where versions aren't enough
MVCC elegantly handles read/write conflicts via versions. But write/write conflicts can't be waved away — two transactions cannot both write the canonical next version of the same row and both win. So writes still take row locks.
When Ana's transaction UPDATEs slot #42, it takes an exclusive lock on that row. If Boris's transaction tries to UPDATE the same row, it blocks until Ana commits or rolls back — then proceeds against the new version. This blocking is the mechanism that, used deliberately, fixes lost update.
SELECT ... FOR UPDATE lets you take that exclusive row lock at read time, before you've decided to write, so a read-modify-write becomes serialized:
BEGIN;
SELECT capacity FROM appointment_slots WHERE id = $1 FOR UPDATE; -- lock the row NOW
-- ... app checks capacity >= 1 ...
UPDATE appointment_slots SET capacity = capacity - 1 WHERE id = $1;
INSERT INTO appointments (slot_id, patient_id) VALUES ($1, $2);
COMMIT; -- lock released here
Now Boris's SELECT ... FOR UPDATE blocks until Ana commits, then reads capacity = 0, fails the check, and correctly rejects his booking. The race is gone because the read-check-write is forced into a serial order on that row. Useful variants:
FOR NO KEY UPDATE— weaker, allows concurrent foreign-key checks against the row; the right default for "I'll update a non-key column."FOR SHARE— a shared lock: "others may read-lock too, but nobody may write until I'm done."NOWAIT— fail immediately instead of blocking if the row is already locked (surface a fast 409 rather than make the user wait).SKIP LOCKED— skip already-locked rows instead of waiting, so concurrent workers grab disjoint rows.
📎 Borrowed on credit:
SKIP LOCKEDjob queues. That last variant is the backbone of building a correct work queue on top of plain SQL — many workers eachSELECT ... FOR UPDATE SKIP LOCKED LIMIT 1to claim a job nobody else holds. It's a beautiful pattern, but it belongs to Chapter 26, where queues and background processing get their full treatment. Here, just note thatSKIP LOCKEDexists and why it composes from the row-locking primitives above.
Catching write skew: Serializable Snapshot Isolation
Row locks fix lost update because both transactions fight over the same row. But write skew — the two on-call providers — touches different rows, so neither blocks the other and snapshot isolation lets both commit. How does PostgreSQL's Serializable catch it?
In plain terms, Postgres lets both providers' transactions run optimistically, but quietly writes down who-read-what and who-wrote-what. If it later spots that Mara read a count that Nils then invalidated (and vice-versa) — a loop that no one-at-a-time ordering could have produced — it kills one transaction with error 40001 and expects you to retry. The mechanism has a name: SSI — Serializable Snapshot Isolation — which runs on top of snapshot isolation and monitors the dependency edges between transactions. Specifically it tracks when transaction A reads data that transaction B then writes — that read-then-someone-else-wrote pattern is called a "read-write antidependency." When it detects a cluster of these edges that could only arise from a non-serializable schedule (a "dangerous structure"), it picks a victim and aborts it with a serialization failure (40001). The application is expected to retry. This is how Serializable catches the on-call bug that snapshot misses: it doesn't need a shared row to lock; it notices that the pattern of reads and writes couldn't have happened in any serial order, and breaks the tie by aborting.
The cost: SSI does more tracking, and under contention it aborts more transactions — which is fine, because abort-and-retry is the contract. But it means Serializable is only correct if your code retries 40001. Set the dial to Serializable and ignore the retries, and you've built a system that "randomly" 500s under load.
How the driver and ORM expose all this (Node/TS primary)
In raw pg, a transaction is a sequence of statements on one connection. The critical trap: your app uses a connection pool (a fixed, shared set of reusable DB connections the whole server borrows from), and a transaction is pinned to a single checked-out connection. You cannot scatter BEGIN, your queries, and COMMIT across separate pool.query() calls — each may grab a different connection, so your UPDATE runs outside the BEGIN's connection and isn't in the transaction at all.
// CORRECT: one connection for the whole transaction.
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('SELECT capacity FROM appointment_slots WHERE id = $1 FOR UPDATE', [id]);
// ... checks ...
await client.query('UPDATE appointment_slots SET capacity = capacity - 1 WHERE id = $1', [id]);
await client.query('INSERT INTO appointments (slot_id, patient_id) VALUES ($1, $2)', [id, patientId]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release(); // give the connection back to the pool
}
Setting the isolation level is per-transaction: BEGIN ISOLATION LEVEL SERIALIZABLE. In Prisma, prisma.$transaction(async (tx) => { ... }, { isolationLevel: 'Serializable' }) gives you an interactive transaction whose tx client is correctly pinned to one connection — use tx, never the global prisma, inside the callback, or your statements escape the transaction. (The sequential-array form $transaction([q1, q2]) is for independent queries, not interactive read-modify-write.) TypeORM exposes the same via a QueryRunner you must connect, startTransaction, and release yourself. The through-line across all of them: a transaction is bound to one connection, and every ORM's convenience layer is hiding — or occasionally leaking — that fact.
🏭 Skippable if you don't touch the JVM. The Java/Spring contrast still teaches one transferable lesson. Spring's
@Transactionalmakes the transaction declarative — an annotation on a method opens and commits the boundary, withpropagation(REQUIREDjoins an existing transaction;REQUIRES_NEWsuspends it and starts a fresh one) and anisolationattribute. JPA bakes in optimistic concurrency: annotate a field@Version, and Hibernate automatically addsAND version = ?to every update and bumps it, throwing on conflict — the §5 pattern, free. The famous trap:@Transactionalworks via a proxy, so a method calling another@Transactionalmethod on the same object bypasses the proxy and the inner annotation does nothing — the transaction boundary isn't where you think. The payoff to carry back to Node, ignoring the Java vocabulary: always know exactly where the transaction boundary actually starts and which connection it owns, because every framework has some way of making that boundary lie to you.
5. In production: choosing and operating concurrency control
The most important production habit: decide concurrency strategy per operation, not per application. There is no global right answer. Match the tool to the contention.
- Hot, single-row contention (a sought-after provider's next open slot): pessimistic —
SELECT ... FOR UPDATEor an atomic conditionalUPDATE. Conflicts are frequent, so optimistic retries would thrash. - Rarely-contended edits (a clinician amending their own draft note): optimistic — a version check. Conflicts are vanishingly rare, so paying for locks on every edit is waste.
- Multi-row invariants with write-skew risk (the on-call providers, a department's shared visit budget): Serializable with a retry loop, or materialize the invariant as a constraint.
The two atomic fixes for lost update
The cleanest fix for the double-booking needs no explicit lock and no transaction ceremony at all — push the check into the write so it's a single atomic statement:
-- One statement. The engine locks, checks, and decrements atomically.
UPDATE appointment_slots SET capacity = capacity - 1
WHERE id = $1 AND capacity >= 1;
-- If rowCount = 0, the slot was already full: reject the booking.
Because a single UPDATE is atomic and acquires the row lock for its own duration, two concurrent copies cannot both pass capacity >= 1 and both decrement — the second sees the decremented value. You inspect the affected-row count: 1 means you won the slot and may insert the appointment; 0 means it's full, reject. This is the most robust, highest-throughput fix, and it should be your default reflex for "decrement a counter under a floor." The SELECT ... FOR UPDATE version from §4 is equivalent and necessary when the decision is more complex than a single predicate (you need to read several columns and run real logic before deciding to write).
Optimistic concurrency in practice
For low-contention edits — the concurrent-charting problem, where two clinicians rarely touch the same note at the same second — add a version integer column and make the write conditional on the version you read:
// read → compute → conditional write
const { rows } = await db.query(
'SELECT note_text, version FROM encounter_notes WHERE id = $1', [id]);
const current = rows[0];
const newText = amend(current.note_text); // arbitrary charting logic
const result = await db.query(
`UPDATE encounter_notes SET note_text = $1, version = version + 1
WHERE id = $2 AND version = $3`,
[newText, id, current.version]);
if (result.rowCount === 0) {
// Another clinician committed between our read and write. We lost.
throw new ConflictError(); // surface 409; the caller re-reads and retries
}
No locks are held between the read and the write, so concurrent readers and unrelated writers never wait on you. The price is that a detected conflict means wasted work and a retry — acceptable precisely because conflicts are rare here. This is exactly the shape of an HTTP If-Match/ETag update, and of an optimistic UI update in React: act on the version you last saw, and reconcile if the world moved under you. (updated_at can stand in for version, but a monotonic integer is unambiguous and immune to clock issues.)
Retry loops, done right
Serializable failures (40001) and deadlocks (40P01) are expected, retryable outcomes, not bugs. Production code that uses either must wrap transactions in a bounded retry:
async function withRetry<T>(fn: () => Promise<T>, max = 3): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await fn(); // fn runs the WHOLE transaction
} catch (e: any) {
const retryable = e.code === '40001' || e.code === '40P01';
if (!retryable || attempt >= max) throw e;
await sleep(jitter(attempt)); // exponential backoff + jitter
}
}
}
Three rules make this safe: retry the whole transaction (never a partial — the aborted one left nothing behind, by atomicity); make the transaction body idempotent so re-running it is harmless; and cap attempts with jittered backoff so a contention spike doesn't become a retry storm hammering the hot row in lockstep.
Keep transactions short and lock-narrow
The cardinal operational sin is a long transaction holding locks. While a transaction is open and holding row locks, everyone contending for those rows waits. So:
- Never make an HTTP call (say, to the clearinghouse or a lab partner), publish to a queue, or wait on user input inside an open transaction. External side effects go after
COMMIT. - Do the minimum work between
BEGINandCOMMIT; acquire locks as late and release them as early as the logic allows. - Set
statement_timeoutand especiallyidle_in_transaction_session_timeout, so a transaction that someone forgot to commit (or a hung connection) can't pin locks indefinitely and take the system down.
🏭 Choose the dial deliberately, escalate surgically. Don't globally raise isolation to Serializable "to be safe" — you'd tax every query with SSI tracking and abort overhead, most of which need nothing of the sort. Default to your platform's default (PostgreSQL: Read Committed), make individual contended operations atomic with conditional
UPDATEs orFOR UPDATE, and escalate a specific transaction to Serializable only where a genuine multi-row, write-skew-prone invariant demands it. Isolation is a per-transaction decision, applied where the risk lives, not a global lever.
Operationally, watch four signals: pg_stat_activity for long-running and idle in transaction sessions (the lock-pinners), pg_locks for blocking chains (who's waiting on whom), deadlock entries in the log, and — treat this as a first-class metric — your serialization-failure rate. A rising 40001/40P01 rate is not "retry harder"; it's a contention hotspot telling you to redesign (shard the counter, batch the reservation), because retries are amplifying load, not absorbing it.
6. Common pitfalls
Read-then-write race (lost update). Signature: double-booked slots, double-dispensed meds, counters that drift low under traffic; passes every single-threaded test. Fix: make it atomic — UPDATE ... SET capacity = capacity - 1 WHERE id = $1 AND capacity >= 1 in one statement, or SELECT ... FOR UPDATE before the modify. Never "read in app, decide in app, write back" on contended state.
"We set SERIALIZABLE so we're safe" — but never handle 40001. Signature: sporadic 500s under load; transactions that "randomly fail" with no pattern; fine in dev, ugly in prod. Fix: serialization failures are part of the contract of Serializable. Add the bounded retry loop or you haven't actually deployed a usable Serializable system.
Long transaction holding locks. Signature: p99 latency cliff, idle in transaction rows piling up, cascading timeouts the moment a third-party call inside the transaction (clearinghouse, lab, eligibility) is slow. Fix: move all side effects out of the transaction; shorten its scope to the bare writes; set idle_in_transaction_session_timeout.
Inconsistent lock ordering → deadlock. Signature: deadlock_detected (40P01) in the logs; two code paths that lock rows A then B versus B then A, each holding one and waiting for the other forever (until the engine kills one). Fix: impose a global lock-acquisition order — e.g., always lock slot rows in ascending id order — so a cycle can't form. Retry the victim on 40P01. Prevention beats detection.
Assuming Repeatable Read = Serializable. Signature: write skew slips through despite "high" isolation — double-approved refunds, budget overruns, both on-call providers signing off. Fix: know your engine's real semantics. Snapshot/RR does not stop write skew. Use true Serializable, or materialize the invariant as a constraint or an explicit lock on the counted thing.
Transaction silently split across pool connections (Node/ORM). Signature: "BEGIN had no effect," writes that don't roll back, intermittent and maddening. Fix: run every statement of the transaction on the same checked-out connection — use pool.connect()'s client, or the ORM's transaction-scoped client (tx, the QueryRunner), never the global pool/client, inside the transaction.
Relying on app-side uniqueness instead of a constraint. Signature: duplicate appointments, duplicate claim submissions, or clashing MRNs appear only under concurrent load — the "check then insert" both passed before either committed (the check-then-insert race). Fix: push the invariant into a DB UNIQUE/CHECK/exclusion constraint. The engine enforces it atomically regardless of isolation level; let the insert fail and handle the error. A constraint is cheaper and more bulletproof than any isolation level for invariants you can express declaratively.
7. Tradeoffs
Pessimistic (FOR UPDATE) ↔ optimistic (version). Pessimistic is predictable and wastes no work, but it serializes contended rows and risks blocking and deadlocks. Optimistic holds no locks and shines when conflicts are rare, but it wastes work on retries and degrades badly under high contention (everyone retries, everyone conflicts again). The crossover is empirical: when your measured conflict rate climbs past a few percent, the wasted optimistic retries cost more than the pessimistic blocking, and you should switch. Reverse the choice as the contention on a given operation changes — it's per-operation, and it can change over a product's life.
Higher isolation ↔ throughput. Serializable eliminates a whole class of bugs and the cognitive burden of reasoning about anomalies — you get "as if serial" for free in your head. The bill is more aborts and the CPU of SSI dependency tracking. Read Committed is fast and usually fine — but only if you make individual contended operations atomic yourself. Default low, escalate surgically per transaction; don't pay the Serializable tax on the 95% of queries that don't need it.
DB-native locking ↔ application-level coordination. Database row locks are transactional: they auto-release on commit or rollback, including after a crash, with no orphaned-lock failure mode. An external lock service (or a Redis lock) adds coordination across resources the DB doesn't own, but introduces a new failure mode: the lock not being released when a holder crashes. Prefer DB-native locks whenever the contended state lives in the DB. Reach for external coordination only when you must serialize access to something the database can't see.
Constraint ↔ isolation level. For any invariant expressible as a constraint — uniqueness, a range check, "these two appointments can't overlap on the same provider" (an exclusion constraint) — the constraint is cheaper, race-free, and enforced regardless of isolation. Reserve isolation level as the tool for invariants that cannot be written declaratively: write skew across rows, a count threshold, a sum-must-stay-positive rule spanning many rows. Constraint first; isolation only for what constraints can't express.
🚫 A framing this book rejects. "Just add a mutex in Node to serialize the booking endpoint." It works on your laptop — one process, one mutex — and fails the instant you run a second instance behind the load balancer (the server is plural), because the mutex is per-process and the two instances share nothing. This is the deepest lesson of the chapter wearing different clothes: correctness must live where the shared state lives — in the database — not in the memory of one app process. An in-process lock guarding shared, durable state is a bug that passes every test on one box and corrupts data the day you scale to two. The database is the single serialization point precisely because it's the single owner of the truth.
8. Security & scale notes
Concurrency correctness is a security property, not just a UX one. The races in this chapter are exploitable on purpose. A TOCTOU (time-of-check-to-time-of-use) gap — check a claim hasn't been submitted, then submit it; check a prior-authorization token is unused, then consume it — is a vulnerability an attacker exploits by deliberately firing concurrent requests to slip between the check and the use. Claims submitted (and paid) twice, a prior-auth consumed twice, the last slot booked by two patients: these are the same lost-update bug weaponized. Treat "is this read-modify-write atomic under concurrency?" as a line item in your security review, not just your correctness review.
📎 Borrowed on credit: idempotency keys. The request-level complement to a database transaction is the idempotency key: the client sends a unique key with "submit claim," and a
UNIQUEconstraint on that key makes a retried or duplicated request a safe no-op — the second insert fails the constraint, and you return the original result instead of submitting the claim to the clearinghouse twice. This is the right defense against network retries and double-submits, above the isolation layer. It interacts deeply with exactly-once-vs-at-least-once delivery, so it gets its own treatment in Chapter 25. Note here only that a uniqueness constraint and a transaction are complementary defenses, not substitutes.
Contention is super-linear under load. A single hot row — the one open slot every coordinator races for, or the counter on a single high-volume monitoring device — serializes all of them: each FOR UPDATE waits for the previous, so throughput on that row collapses toward "one request at a time," and lock waits plus serialization aborts spike together. Worse, naïve retries create a thundering herd: aborted transactions all retry at once, re-collide, abort again — load amplifying itself. Backoff with jitter and a hard retry cap are not optional polish; they're what stop a contention spike from becoming an outage.
A correctness bug becomes an availability incident through the connection pool. This is the failure that surprises people. A long or blocked transaction holds its connection (§5). Under contention, many transactions block on the hot row, each pinning a connection, and the pool drains. Now requests to completely unrelated endpoints — endpoints that touch none of the contended data — start timing out, because there are no free connections left to serve them. The slow slot booking takes down the unrelated patient-search page. This is the earlier lesson that saturation is a chain property, made concrete: a localized correctness/contention problem propagates into a system-wide availability problem through a shared, finite resource.
Hot-row mitigations exist — name them, don't deep-dive them. Once your booking path is correct but contended, the next level is reducing the contention: shard a hot counter into N sub-rows and sum them; reserve slots in batches rather than one unit per transaction; or queue claims with SKIP LOCKED so workers pull disjoint units. These are scaling patterns that presuppose the correct version exists first — you earn them once the slot books correctly but that provider's openings are so sought-after that serialized booking becomes the bottleneck.
📎 Borrowed on credit: the rest of the scale stack. Sharded counters and queue-based reservation lean on patterns developed later — horizontal scaling building blocks in Chapter 29, tail-latency reasoning in Chapter 30, and the queue mechanics in Chapter 26. Here, the obligation is only to recognize that the correct solution and the scalable solution are sequential goals: correctness first, on one node, with the tools of this chapter.
🛑 What we deliberately did not explain. How the WAL achieves durability byte-by-byte and how MVCC versions are physically laid out on pages (Chapter 18). How
VACUUM, autovacuum, and transaction-ID wraparound keep MVCC bloat in check operationally (Chapter 19). HowSKIP LOCKEDbuilds a real job queue (Chapter 26). How consistency survives when the data is replicated across machines and a single serial order may be impossible (Chapter 23). We named where each lives on the map; we didn't open the rooms.
9. Interview lens & exercises
Interview questions
"Two coordinators book the last open slot simultaneously — walk me through how you guarantee no double-booking."
- Junior answer: "Wrap it in a transaction." (Correct that you need one; doesn't explain that at Read Committed a transaction alone doesn't stop the lost update.)
- Senior answer: names the lost-update anomaly explicitly, reaches for an atomic conditional
UPDATE ... WHERE capacity >= 1(orSELECT ... FOR UPDATEif the decision is complex), explains why it's atomic, addresses retry/deadlock handling, and notes that an app-level mutex fails across multiple instances because the shared state lives in the DB.
"What's the difference between Repeatable Read and Serializable, concretely?"
- Junior: recites the standard's level names with no anomaly that actually distinguishes them.
- Senior: gives the write-skew example RR/snapshot misses (the two on-call providers, or a shared budget across disjoint rows), explains that Serializable catches it via dependency tracking (SSI) and aborts with
40001, and adds the vendor nuance — "PostgreSQL's Repeatable Read is snapshot isolation."
"When would you choose optimistic over pessimistic locking?"
- Junior: states a blanket preference ("optimistic is more scalable").
- Senior: frames it by measured conflict probability and the cost of wasted work versus blocking — optimistic when conflicts are rare (no locks held), pessimistic when contention is high (no thrashing) — and shows the
version-column mechanism with therowCount = 0conflict check.
"How do you handle deadlocks in production?"
- Junior: "The database handles it." (It detects and kills one — but then what?)
- Senior: prevent with consistent lock-acquisition ordering (always lock rows by ascending id), survive the rest with a retry on
40P01, and monitor the deadlock rate as a signal to redesign the contended path.
"Your service uses SERIALIZABLE and throws intermittent errors under load — what's happening?"
- Junior: treats the errors as bugs to log and ignore.
- Senior: recognizes serialization failures (
40001) as the expected contract of Serializable, requiring a bounded retry loop with jittered backoff; a rising rate signals a contention hotspot to redesign, not retry harder.
Exercises & the Pulsely increment
-
Reproduce the race empirically. Write a failing integration test that fires N concurrent
bookSlotrequests at one open slot (capacity = 1) and asserts that exactly one appointment exists andcapacity = 0. With the naïve §1 handler it must fail — proving the bug exists before you fix it. A concurrency fix you can't first make fail is a fix you can't trust. -
The Pulsely increment — fix it three ways and compare. Make slot booking correct via (a) the atomic conditional
UPDATE ... WHERE capacity >= 1checkingrowCount; (b)SELECT ... FOR UPDATEthen decrement; (c) an optimisticversioncolumn with a bounded retry. Run each against the concurrent test from exercise 1 (all three should now pass) and record their throughput and abort rates under load. You'll see (a)/(b) win on the hot single row and (c) shine only when contention is low — feel the tradeoff rather than memorizing it. -
Induce and fix a deadlock. Craft two transactions that lock two slot rows in opposite order (T1: lock A then B; T2: lock B then A). Observe
40P01. Fix it by imposing a consistent ordering (both lock the lower id first) and confirm the deadlock is gone. -
Demonstrate write skew. Build the dual-on-call scenario: two transactions each
SELECT count(*) ... WHERE on_call = true, each find it ≥ 1, each set their own row tofalse. Run it under PostgreSQL Repeatable Read — both commit, invariant violated. Re-run under Serializable — observe the40001abort and that the retry restores correctness. Then express the same invariant as a constraint or an explicit lock on the count and compare the approaches. -
Write the ADR. Document the chosen isolation level and concurrency-control strategy for Pulsely bookings: Read Committed + atomic conditional
UPDATE(withSELECT ... FOR UPDATEreserved for the multi-column decision path) as the decision; the rejected alternatives (global Serializable — too costly per query; in-app mutex — fails across instances; optimistic version — wrong for a hot contended row); and the operational consequences — the bounded retry policy for40001/40P01, the consistent lock-ordering rule,idle_in_transaction_session_timeout, and the serialization-failure rate as a monitored metric.
Key takeaways
- A transaction turns several engine-level writes into one atomic clinical act; but a transaction alone, at the default isolation, does not prevent concurrency anomalies — atomicity, isolation, and durability are independent properties people fatally conflate.
- The anomaly catalog is a published menu, not mysterious corruption: dirty read, non-repeatable read, phantom, lost update (same-row write-write — the double-booking), and write skew (disjoint rows breaking a shared invariant — survives snapshot isolation).
- Isolation levels are the dial: Read Committed stops dirty reads; Repeatable Read/Snapshot adds repeatable reads and (in PostgreSQL) phantom protection but permits write skew; Serializable stops everything. Read your engine's real semantics — the standard's labels are minimums, and vendors diverge.
- MVCC keeps a row's old versions (
xmin/xmax) so readers never block writers and writers never block readers; when the snapshot is taken (per-statement vs per-transaction) is the difference between Read Committed and Repeatable Read. - Pessimistic (
FOR UPDATE, atomic conditionalUPDATE) for hot contention; optimistic (versioncolumn) for rare conflicts like concurrent charting; Serializable + retry for multi-row write-skew invariants. Decide per operation, escalate isolation surgically. - Serialization failures (
40001) and deadlocks (40P01) are expected and retryable — bounded retries, jittered backoff, idempotent transaction bodies, consistent lock ordering. Prevent deadlocks by ordering; survive them by retrying. - Correctness must live where the shared state lives — the database — never in one app process's memory; an in-process mutex passes every test on one box and corrupts data on two. This single-node correctness is the ground Chapter 23 builds distributed consistency on.
← Previous: Ch 16 — Data Modeling as a Discipline · Up: Part IV overview · Master TOC · Next: Ch 18 — How Databases Store Bytes →