Lesson 3 of 9 · 20m
Invariants and State Machines: Making Illegal States Unreachable
The defender's core trick: define the invariant, encode valid transitions, and force concurrent operations through those transitions instead of patching individual races.
Race fixes fail when they focus on the two requests you observed. Next month a third client, a retry worker, or an admin tool finds another interleaving. Durable fixes start one level up: what must always be true, and what transitions are legal? Once those are explicit, concurrency becomes a design constraint instead of a surprise.
Start with invariants, not locks
Useful invariants are blunt and testable:
account_balance >= 0
order has exactly one successful payment
seat_count >= confirmed_attendees
invoice state moves forward, never backward
a withdrawal id is processed at most onceA lock is only a mechanism. The invariant is the thing being protected. Teams that cannot state the invariant usually add locks in the wrong place: around reads instead of decisions, around application code while the database remains exposed, or around one process while other writers remain free.
Model states before writing code
A payment is not a boolean. It is a state machine:
created -> authorized -> captured -> settled
| +-- failed
+-- expiredIllegal transitions should be impossible at the storage layer, not merely unlikely in application code. In SQL, transition guards can live in the UPDATE itself:
UPDATE payments
SET state = 'captured', captured_at = now()
WHERE id = 'pay_123'
AND state = 'authorized';If zero rows update, the transition did not happen. Two concurrent capture requests can both try; only one can move the row out of authorized. The loser must inspect the current state rather than blindly retrying or reporting failure to the user.
Compare-and-swap is the general pattern
The SQL above is compare-and-swap: mutate only if the current state still matches expectations. The same pattern appears as CompareAndSwap in atomics, optimistic concurrency tokens in REST APIs, ETag/If-Match in HTTP, and conditional writes in cloud storage.
PUT /orders/ord_71 HTTP/1.1
If-Match: "v18"
{"status":"packed"}The server accepts the write only if version v18 is still current. A stale client loses cleanly instead of overwriting a newer state.
Separate decision from side effect carefully
Sometimes the side effect cannot be transactional — charging a card, sending email, provisioning a VM. In that case make the transition record authoritative first, then have exactly one worker perform the external effect for that transition. Do not let every request that observes authorized independently call the payment gateway.
Field notes
- "Status" columns without transition rules are invitations to race bugs.
- State machines should be small enough to draw on one whiteboard; if not, split the aggregate.
- Every retry path is part of the state machine, whether you designed it or not.
- Log lost compare-and-swap races with both expected and actual state; they are gold during incident review.
Was this lesson helpful?