Highlights

Contents

Part V
05

Concurrency control

We stop two requests that edit the same row from destroying each other’s work. The database will happily let both succeed unless the code asks for protection in the right way. We will cover the lost update, pessimistic locks with SELECT FOR UPDATE and SKIP LOCKED, optimistic locking with a version column, and atomic statements and constraints that need no lock at all.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Connections and pools2Queries from code3Inside an ORM4Transactions in code5Concurrency control6Schema migrations7Zero-downtime migrations8Scaling database access9The order write end toend

#Section 15The lost update

Restaurant 9 has five portions of biryani left, tracked in menu_items.stock. Two customers order at the same moment. Wren’s first version of the code read the stock, checked it was above zero, and wrote back the stock minus one. Both requests read 5. Both decided there was enough. Both wrote 4. Two biryanis were sold and the stock dropped by one. The second write silently replaced the first, a lost update, and nothing in the logs looks wrong, because each transaction did exactly what it was told.

The pattern behind it is called read-modify-write. The code reads a value into the application, computes a new value, and writes it back, assuming nothing changed in between. Under PostgreSQL’s default read committed level, that assumption is false. The two transactions do not see each other’s uncommitted work, and when the second one’s UPDATE runs, it waits for the first to commit and then overwrites the row with the value it computed from stale data.

LOST UPDATE: TWO READ 5, BOTH WRITE 4, ONE SALE VANISHESLOST UPDATE: TWO READ 5, BOTH WRITE 4, ONE SALE VANISHEST1T2timeread stock 5write 4COMMITread stock 5write 4COMMITstock54should be 3two biryanis sold, one decrement survived; both transactions believed they were right
Figure 6.27Both read 5, both write 4. The counter should say 3.

The same bug appears wherever two writers touch one record. Two support agents edit the same order’s delivery note and the slower one wins. A user taps “add tip” twice on two devices. Two background workers both mark a job as started. In each case the fix belongs to one of four families, and the rest of this part covers them in turn.

The first family uses pessimistic locking. Lock the row when you read it so nobody else can change it until you finish. The second, optimistic locking, lets everyone read freely and checks at write time whether the row changed. The third is the atomic statement, where you never read the value into the application at all and let one SQL statement compute and write it. The fourth is the constraint, a rule inside the database that refuses any write breaking an invariant, however the race happened.

Repeatable read, from Part IV, also catches this case, since the second transaction fails with 40001 instead of overwriting. That works, but it means every such transaction needs a retry loop, and it does not protect code that someone later moves to a read committed path. Wren prefers making the protection explicit in the statement itself.

#Section 16Pessimistic locking with SELECT FOR UPDATE

SELECT ... FOR UPDATE reads rows and takes a row lock on them, held until the transaction ends. Any other transaction that tries to update, delete or lock those rows waits. Wren’s order flow runs SELECT stock FROM menu_items WHERE id = 17 FOR UPDATE, checks the value, updates it and commits. The second customer’s transaction blocks at its own SELECT ... FOR UPDATE until the first commits, then reads 4, not 5, and writes 3. Plain readers without FOR UPDATE are not blocked, because PostgreSQL’s multiversion design lets them read the last committed version.

SELECT ... FOR UPDATE: THE SECOND BUYER WAITS AT THE PADLOCKSELECT ... FOR UPDATE: THE SECOND BUYER WAITS AT THE PADLOCKitem 17, stock 5T1 holdsT2reads 4, writes 3NOWAIT fails instead of waiting; SKIP LOCKED moves on to the next rowlocks last until COMMIT or ROLLBACK, so keep these transactions short
Figure 6.28The first buyer holds the padlock. The second waits, then sees the true stock.

Two variants change what happens when the row is already locked. NOWAIT fails immediately with an error instead of waiting, useful for an interactive action where “someone else is editing this, try again” beats a frozen screen. SKIP LOCKED, added in PostgreSQL 9.5 in 2016, silently skips rows that are locked and returns the next ones. It is made for job queues.

Wren keeps a table of background jobs, sending receipts and notifying kitchens. Four workers poll it. Each runs SELECT * FROM jobs WHERE status = 'ready' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED, processes the job, marks it done and commits. Worker 1 locks job 501, worker 2 skips 501 and locks 502, worker 3 takes 503, and worker 4 skips all three and takes 504. No two workers ever process the same job, and no worker waits for another.

SKIP LOCKED: THREE WORKERS DRAIN ONE JOBS TABLE WITHOUT TRIPPING OVER EACH OTHERSKIP LOCKED: THREE WORKERS DRAIN ONE JOBS TABLE WITHOUT TRIPPING OVER EACH OTHERjob 501 send receiptjob 502 notify kitchenjob 503 send receiptjob 504 refundjob 505 notify kitchenjob 506 send receiptw1w2w3w4w4 skips locked rowsand takes job 504SELECT ... ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED
Figure 6.29Each worker locks a different row. Locked rows are skipped, not waited on.

Pessimistic locks have costs. Locks are held for the length of the transaction, so a slow transaction stalls everyone who needs the same row, and the rules from Part IV about short transactions apply with double force. Locking several rows in different orders invites deadlocks. And a lock lives in the database session, so it cannot span an HTTP request, a user thinking for a minute, or two services. For those cases, optimistic locking fits better.

#Section 17Optimistic locking with a version column

Optimistic locking assumes conflicts are rare and checks for them only at write time. Each row carries a version integer. A transaction reads the row, remembers its version, and writes with a condition, UPDATE orders SET tip = 30, version = 8 WHERE id = 123 AND version = 7. If nobody changed the row, the condition matches, one row is updated, and the version becomes 8. If someone else got there first, the version is already 8, the condition matches nothing, and the update reports 0 rows. The code then knows its data was stale.

OPTIMISTIC LOCKING: A VERSION NUMBER CATCHES THE SECOND WRITEROPTIMISTIC LOCKING: A VERSION NUMBER CATCHES THE SECOND WRITERorder 123tip 20, version 7tip 30, version 8T1: UPDATE orders SET tip = 30, version = 8 WHERE id = 123 AND version = 7→ 1 row updatedT2: UPDATE orders SET note = 'x', version = 8 WHERE id = 123 AND version = 7→ 0 rows: someone changed itT2 reloads version 8 and retries, or returns 409 or 412 to the clientno lock is held between read and write; the check happens in the UPDATE itself
Figure 6.30T1’s update matches version 7 and wins. T2’s matches nothing and must reload.

What to do on 0 rows depends on who is asking. A background job reloads the row and retries its change. An API request from a human usually returns 409 Conflict, or 412 Precondition Failed when the client sent the version as an ETag in an If-Match header, as Unit I described. The client then shows “this order changed while you were editing” with the fresh data. ORMs support the pattern directly, through Hibernate’s @Version, Rails’ lock_version column and SQLAlchemy’s version_id_col.

The big advantage is that no lock is held between read and write. The read can happen in one HTTP request and the write ten minutes later in another, with the version travelling through the client. That makes optimistic locking the natural choice for edit forms, mobile apps that sync, and anything that crosses a network boundary.

Its weakness is contention. Each conflict costs a wasted attempt. If the chance that a write conflicts is p, the expected number of attempts per success is 1 ÷ (1 − p). At p = 5% that is about 1.05 attempts, nearly free. At p = 50% it is 2, and on a single very hot row it can spiral. Pessimistic locking costs roughly the same whatever the contention, since writers queue rather than retry.

OPTIMISTIC WINS WHEN CONFLICTS ARE RARE (ILLUSTRATIVE COST MODEL)OPTIMISTIC WINS WHEN CONFLICTS ARE RARE (ILLUSTRATIVE COST MODEL)chance a write conflictscost per successful updatep ≈ 23%optimistic: 1 ÷ (1 − p) triespessimistic: a flat 1.3 for lockingthe 1.3 is an assumption; the shape, not the crossing point, is the lesson
Figure 6.31An illustrative cost model. Optimistic is cheaper until conflicts become common.

With a flat illustrative cost of 1.3 for locking, the curves cross near p = 23%. The real crossing depends on the workload, but the shape gives the rule. Use optimistic locking where conflicts are rare and work crosses requests, and pessimistic locking for short, hot, server-side critical sections.

#Section 18Atomic statements and constraints

Often the best lock is none. The stock problem disappears if the application never reads the value at all.

sql
UPDATE menu_items SET stock = stock - 1
WHERE id = 17 AND stock > 0
RETURNING stock;

The database reads, checks and writes the row in one statement while holding the row lock for microseconds. Two concurrent executions queue on the row, the second re-evaluates stock > 0 against the new committed value, and the last portion can only be sold once. If the statement updates 0 rows, the item is sold out, and the service returns 409 ITEM_SOLD_OUT. This is an atomic update, and it is the first tool to reach for with counters, balances and quotas.

LET THE DATABASE DO READ, CHECK AND WRITE IN ONE STATEMENTLET THE DATABASE DO READ, CHECK AND WRITE IN ONE STATEMENTread, decide in code, writeSELECT stockif stock > 0in appUPDATE stockother transactions slip into the gapsone statementUPDATE menu_items SET stock = stock - 1WHERE id = 17 AND stock > 0RETURNING stock; -- 0 rows means sold out
Figure 6.32Read, decide and write in code leaves gaps. One statement leaves none.

The second tool is a constraint, a rule the database enforces on every write. A CHECK (stock >= 0) constraint makes negative stock impossible, whatever bug or race tries it. A unique index on idempotency_key makes it impossible for two retries of the same request to create two orders. Code that checks first, if not exists(key): insert(key), races, because both requests can pass the check before either inserts. The unique index cannot be raced, because PostgreSQL checks it while inserting, under its own locks. The second insert fails with SQLSTATE 23505, unique violation, and Wren catches that specific error and returns the stored response from the first request.

A UNIQUE INDEX IS A BOUNCER THAT NO RACE CAN SNEAK PASTA UNIQUE INDEX IS A BOUNCER THAT NO RACE CAN SNEAK PASTUNIQUE (idempotency_key)key K7 #1key K7 #2row K723505 unique_violation→ return the stored responsechecks in code race; constraints are checked inside the database, under its locks
Figure 6.33Two inserts with the same key. The index lets one through and turns the other away.

PostgreSQL’s INSERT ... ON CONFLICT DO NOTHING or DO UPDATE wraps this pattern into one statement, called an upsert, which avoids the error entirely when a duplicate is expected. Exclusion constraints go further, for example forbidding two bookings of one table whose time ranges overlap.

Constraints are the last line of defence and the cheapest. Wren puts invariants in the database whenever SQL can express them, and keeps application checks for friendly error messages, not for correctness.