liveBook · Manning

Concurrency control

As explained in Crack Any Codebase with AI

Concurrency control is the set of mechanisms that coordinates simultaneous operations to preserve correctness when they access shared data.

Concurrency control coordinates simultaneous writes so a race cannot create incorrect shared data. When two people book one open slot, the backend must decide which write wins at the moment of persistence. section 8.5

Look for the guard that stops the second writer:

  • Pessimistic locking makes the first writer lock the row while the second waits; it is simple but serializes writers. section 8.5
  • Optimistic version checks let writers race; a zero-row update identifies the loser, which must retry. section 8.5
  • A unique constraint lets both insert, then atomically rejects the duplicate; it is cheapest when a natural unique identifier exists. section 8.5

One booking from two requests

A slot-and-host-derived idempotencyKey gives two competing booking requests the same value. The first insert succeeds; the database rejects the second, preventing a duplicate booking or charge. section 8.5

Table 8.4 Strategies for resolving a write race
Mechanism
How it resolves the race
What it buys
What it costs
SELECT … FOR UPDATE (pessimistic)
First writer locks the row; the second blocks until the first commits
Strong, simple to reason about; no retry logic
Holds a lock across the critical section; serializes writers, lowering throughput
Version column (optimistic)
Both write with WHERE version = N; the loser's update affects 0 rows and retries
No lock held; high throughput when conflicts are rare
The app must detect the 0-row update and retry, more code, worse under contention
Unique constraint
Both INSERT; the database rejects the second with a duplicate-key error
Cheapest, fully atomic, leans on a guarantee the DB already enforces
Only works when there's a natural unique identifier to constrain on

Compare each write-race strategy by its mechanism, correctness trade-off, throughput impact, and required application logic. section 8.5

How Crack Any Codebase with AI covers it

How deep it goes
Compares locks, version checks, and unique constraints with their correctness, retry, locking, and throughput trade-offs.
Examples
Uses competing slot bookings, double-clicked confirmations, idempotency keys, duplicate-key errors, and database write guards.
What you can do after
Diagnose a write race by locating the lock, version check, or unique constraint that rejects or delays the second writer.
How it connects
Connects database transactions, pessimistic locking, optimistic concurrency, version columns, unique constraints, and idempotency.

Also explained in

Compare how 2 books explain concurrency control →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Crack Any Codebase with AI. The section links point to the parts of the book it draws on.