Skip to main content
Two invariants live together on this page because they are enforced by the same transaction:
An order moves only along legal state transitions, and its history never diverges from its state. A retried request produces at most one order and returns the same response both times.
The first invariant prevents orders from entering impossible states, such as shipping before payment. The second prevents network retries from turning one customer action into two orders or two charges.

The lifecycle as an explicit state machine

Define the states and the legal transitions, and enforce them in the database rather than documenting them only in a diagram.
The legal graph for this guide:

Enforce transitions with compare-and-set

Do not read the status, decide in application code, and then write the new status. That sequence is a lost-update race. Instead, make the expected current state part of the WHERE clause. A stale or illegal transition matches zero rows and is rejected atomically.
The version column provides general optimistic concurrency for edits that are not a simple status change: read version, then UPDATE ... WHERE id = $id AND version = $v.
[!NOTE] Enum vs STRING + CHECK, and triggers A STRING + CHECK is the most evolvable encoding (adding a state is a constraint change). A native ENUM gives stronger type safety but altering its values is a schema change. If you prefer to centralize transition rules in the database, triggers can reject illegal transitions server-side, at the cost of more coupling. Application-side compare-and-set is portable and explicit; it’s the default this guide uses.

History that cannot drift

Write the audit event in the same transaction as the state change. Because the two commit atomically, state and history can never disagree: there is no window where the order says paid but no event records it.
[!TIP] Audit is also your recovery log Because order_events is append-only and ordered by seq, you can reconstruct or verify any order’s current state by folding its events. Combined with idempotency (below), this is what lets you safely resume after a crash.

Idempotent order creation

A client that times out does not know whether the order was created, so it retries. Without protection, the retry creates a duplicate order. The solution is a caller-supplied idempotency key, recorded in the same transaction as the effect.
The first request inserts the key and performs the work. A retry matches the primary key and returns the stored response without performing the work again.
[!NOTE] The key’s scope and the fingerprint The caller owns the key; you define its scope (per customer, per endpoint). Store a request_fingerprint so you can detect the dangerous case where the same key is reused with a different body. That’s a client bug, and you should reject it rather than silently return the old response. Expire old keys with Row-Level TTL so the table doesn’t grow forever.
[!TIP] The key is also a claim The idempotency row doubles as a claim/lease: the first writer inserts the key in in_progress state and does the work, then flips it to done and stores the response. A concurrent or retried request that collides on the primary key either returns the cached response (state done) or learns the operation is already in flight (state in_progress). Because the primary key is unique, two workers, even in different regions, cannot both process the same request. Track attempt_count to see how often clients actually retry.

Concurrency, ordering, and the role of SERIALIZABLE

The default isolation level is what makes the patterns on this page safe. SERIALIZABLE prevents the lost updates and write skew that would otherwise let two concurrent transitions both succeed, or let an idempotency check and its insert interleave incorrectly. The cost is that a contended transaction may return a 40001 retry error, so every transaction here runs inside a client retry loop.
Event ordering. Inside the database, order events are totally ordered per order by seq (and globally by HLC timestamps). Across a changefeed, only per-key ordering is guaranteed and duplicates are possible, so any consumer of order events must dedupe by key + updated timestamp and tolerate reordering across different orders. See External integration.

Recovery

Idempotency keys + append-only order_events make the system resumable. After a crash or ambiguous outcome:
  • A retried create with the same key is a no-op that returns the original result, with no duplicate.
  • The current state is whatever the last committed transition set it to; you can verify it by folding order_events.
  • An operation that committed but whose caller never saw the response is safely replay-able.

Tradeoffs

[!CAUTION] Anti-patterns
  • Read status → decide → write status in separate steps (lost-update race). Always put the expected state in the WHERE.
  • Creating the order and recording the idempotency key in separate transactions: a crash between them double-creates. One transaction, always.
  • Assuming changefeed events arrive in global order. They don’t.