State machines in database rows
An entity's lifecycle kept as a status column, each transition applied by an update that names the state it expects to leave. A zero row count means re-read the row before deciding what happened.
What it is
A finite-state machine is a model with a fixed set of states that sits in one of them at a time and moves to another in response to an input; each move is a transition, and the machine is described by its states, its starting state and the inputs that trigger each transition. Kept in a database, the machine is a row: a status column holds the current state, and the other columns hold what that state needs (who holds the reservation, when the hold expires). The transition table lives in code or in a small lookup table: from this state, on this event, go to that state. An event that doesn't appear in the table for the row's current state is refused rather than applied.
The transition itself is a single conditional write that names the state it expects to find. In PostgreSQL 17 an UPDATE reports a count of the rows it matched and updated, including rows whose values happened not to change, and a count of zero is a normal outcome rather than an error. So the code reads the count: one row means the transition happened; zero means no row was updated, and there are several reasons that can happen: the row wasn't in the expected state, the id doesn't exist, another condition such as the deadline failed, or, as the PostgreSQL documentation notes, a BEFORE UPDATE trigger suppressed the change. Telling them apart is why the next step is a re-read rather than a guess. DynamoDB offers the same tool as a ConditionExpression on UpdateItem: when the condition is false the call fails with ConditionalCheckFailedException, and if ReturnValuesOnConditionCheckFailure is set to ALL_OLD the exception carries the item's current attributes, so the code can see the item's state without a second read. A failed condition still consumes write capacity, so rejected events aren't free.
-- Move a hold to confirmed, from 'held' and before its deadline.
-- last_event records which request produced the current state.
UPDATE reservations
SET status = 'confirmed',
confirmed_at = clock_timestamp(),
last_event = $2
WHERE id = $1
AND status = 'held'
AND expires_at > clock_timestamp();
-- 1 row changed: the transition happened.
-- 0 rows changed: re-read the row and decide:
-- status = 'confirmed' AND last_event = $2 -> same request again, return the earlier result
-- status = 'confirmed', other last_event -> a different confirmation got there first
-- no row, or any other status -> may have lost the race, arrived late, used a bad id,
-- or succeeded earlier and moved on; report what you foundWhat makes this hold up under concurrency is how the store treats two writers on one row. Under Read Committed, PostgreSQL 17's default level, a second update that reaches a row another transaction has already changed waits for that transaction to finish; if it committed, the second update re-checks its WHERE clause against the new version of the row, and when the status no longer matches, it changes nothing. Two events that arrive in the same second are serialized by the row itself: one gets a count of one, the other a count of zero, with no lock in application code. Under Repeatable Read the loser gets a serialization error instead, and the documented remedy is to retry the whole transaction, which lands on the same decision by a different route.
Duplicates go through the same mechanism, with one addition: the row records which event moved it, in a column such as last_event or in the history table. If a confirmation is delivered twice, the second attempt finds the row already in the target state and changes zero rows; the re-read then compares the stored event id with the incoming one. Our advice: when they match, return the same response as the first time; when the state matches but the id doesn't, a different event got there first, and the caller needs to know that. Target state on its own doesn't settle it, because a row can reach the same state again by another path. DynamoDB's documentation makes a related point: a conditional write can be idempotent when its condition checks the attribute being written, and a status guard is that case: once the write has landed, the equality condition stops matching, so a retry after a lost response applies nothing.
Deadlines are a column, not a state that a timer flips. An expiry is an event like the others; it just happens to be raised by a clock. The guard expires_at > clock_timestamp() in the SQL above does one job: in this design, a confirmation that reaches the database after the deadline is meant to match no row, whether or not the sweeper has visited yet. Keep the transition in a short transaction of its own, so the time the guard compares against is close to the time the write lands. Moving the row from held back to free is a separate guarded update, run by a periodic sweeper over rows whose deadline has passed, or by the next request that reads the row and finds the deadline behind it. Because each path is a guarded row write, the outcome depends on each update's predicate at the moment it runs, not on application code comparing clocks: a confirmation that runs before the deadline can win, a late one should find nothing to change, and the sweeper reclaims the row whenever it gets there.
A product example: Stripe documents a PaymentIntent as a set of statuses, from requires_payment_method through requires_confirmation, requires_action and processing to succeeded or canceled. Its table shows the shape of a real transition table: a failed payment attempt sends the intent back to requires_payment_method so it can be retried, cancellation is allowed before processing or succeeded and is final, and an intent confirmed too many times can move to canceled on its own. A strong answer draws the same shape: a few named states, loops back for retries, and terminal states with no way out.
When to use it
Use a status column with guarded transitions when one row stands for a thing with a lifecycle that several actors can touch at once: a reservation, a payment, an order, a device, a background job, or a worker whose own row holds its current assignment, so that two assigners compete for one row. It fits best when the state set is small, when "what is it right now" is asked far more often than "how did it get here", and when the correctness that matters is that two events don't both win. It also fits a key-value store that supports conditional writes, as DynamoDB does with a condition expression on a put or update.
In a round, name the states first, then the events, then the guard, and then say aloud what a count of zero means for each event. Three cases are worth rehearsing because the design answers all of them with the same move: two events in the same second, an event delivered twice, and a deadline that passes in the middle of a user's action. Each comes down to one guarded write plus one re-read, so you can take each in a sentence or two instead of inventing a new mechanism for each.
When not to
Skip the machinery when there is one writer and no race to settle: an admin screen that edits a single record, a batch job that owns its rows for the run. A plain update is clearer, and a guard that can't fail teaches the next reader nothing about why it's there.
A status column in one database is a poor fit for a workflow that spans several services and stores, where each step commits somewhere else; there the coordinating record is an orchestrator or saga, and the row in each service holds its own local state. It's also the wrong tool when the quantity is really a count rather than a state, such as seats left or stock on hand. DynamoDB describes an atomic counter for that: an UpdateItem that increments a number without a condition, applied in arrival order, which is not idempotent, so a blind retry can overcount. Pair the counter with an idempotency check instead of forcing it into states; see Idempotency keys.
When one row takes far more transitions than the rest of the table, the guarded update serializes them one at a time and that row can become the bottleneck; split the entity or move the hot part elsewhere. And when the store you must write to has no conditional write, the guard has to come from somewhere else, such as a lease in a lock service in front of the write, paired with a fencing token that the store itself checks on each write, so that the store can reject a late write from a holder whose lease has expired; see Distributed locks and leases.
Compared
| Approach | How a transition is applied | Pick it when | Cost or risk |
|---|---|---|---|
Read, decide in code, write without a condition | Read the row, choose the next state, write it | One writer, no concurrent events: an admin edit, a batch run that owns its rows | Two writers both read |
Guarded update on | One update with | The default: several actors, a small state set, a decision that fits in one row | A zero count needs a re-read to tell a duplicate from a conflict; in DynamoDB a failed condition still costs a write |
| Lock the row, read other rows or call out, then write | The decision needs several rows or a computation before the write | The lock is held for the transaction and waiters queue behind it |
Version column (optimistic locking) |
| Many columns change together and the status alone doesn't show the row moved | More retries under contention; callers must carry the version |
Append-only event log | Append the event; derive the state by replaying | The audit trail or replay is itself the product | Current state needs a projection; more moving parts to keep in step |
Lease in a separate lock store | Acquire a key with a lifetime, then write | The store has no conditional write, or the hold must span several requests | Two systems to keep consistent; a lease can expire while the work is still running |