Navigation

Engineering

Preventing overselling under concurrent checkout in PostgreSQL

How 600 competing checkout requests reserved exactly the 40 units that exist, in each of 20 runs, using one conditional UPDATE under READ COMMITTED, an INSERT-only stock ledger and CHECK constraints instead of SERIALIZABLE retries.

On this page

StockPoint is a retail showcase I built as an independent engineering demo: a fictional NZ homewares retailer with eight stores and a distribution centre replays Black Friday. Orders, stock counts, late suppliers and a broken promotion all land on promises customers were already given. Underneath sits one rule: never commit more stock than exists, even when hundreds of checkouts want the same last units. Here is how the database enforces it, what I rejected, and how I proved it holds.

Test setup. Symfony 8.1 on PHP 8.6, PostgreSQL 19. The contention test and the local benchmark ran in Docker with 8 CPUs on 2026-11-23. The production benchmark ran on the live host: a shared 4-vCPU server, 4 worker processes. Every worker is a separate PHP process with its own connection, and every request or order is its own transaction through the code the demo uses. Each benchmark figure is one recorded run; the contention test is 20 runs.

The problem: two shoppers, one last unit

The obvious implementation reads the available quantity, checks it in application code, then writes a reservation:

SELECT on_hand - reserved - picked FROM stock WHERE ...;   -- both shoppers see 1
-- application: 1 >= 1, fine
INSERT INTO reservation ...;                                 -- both insert

Under PostgreSQL’s default isolation level, READ COMMITTED, both transactions can read “1 available” before either writes. Both pass the check, both commit, and the same unit is promised twice. Nothing errors; the bug surfaces later as a cancelled order. In a flash sale, hundreds of requests sit in that gap between read and write.

Options I considered (ADR 0008)

I wrote the decision up as ADR 0008 before building it. Stock was already an append-only ledger of movements per location, so every option had to keep balances derivable from that history.

Option How it stays correct What it costs
1. Key lock + ledger sum SELECT … FOR UPDATE on a per-key row, SUM the ledger, insert; a deferred constraint trigger re-checks at commit Every reservation reads a growing history; the trigger adds commit-time work and still has to serialise
2. Balance row + conditional update (chosen) One balance row per key is the gate; the ledger is written in the same transaction The balance is a mutable row, so drift is possible in principle and must be prevented and detected
3. SERIALIZABLE with retries PostgreSQL aborts conflicting transactions; the app retries On a hot key, contention turns into retry storms, and the benchmark ends up measuring the retry policy

These costs are reasoning from the ADR, not measurements: I benchmarked only the option I built.

The design: append-only ledger and a balance gate

rt_stock_balance holds one row per stock key (session, location, SKU) with three buckets, on_hand, reserved and picked, plus a revision. rt_stock_movement is the ledger, one row of deltas per change.

Admission is one statement. This is the real reservation query from the stock ledger class:

UPDATE rt_stock_balance
   SET reserved = reserved + :q, revision = revision + 1
 WHERE location_id = :l AND sku = :s
   AND on_hand - reserved - picked - :p >= :q
RETURNING revision

There is no session_id in the WHERE clause on purpose: every StockPoint table has a forced row-level security policy on the demo session, so PostgreSQL adds that filter itself.

:p is the channel’s protection: stock a store holds back for walk-in shoppers. Because the check and the write are one statement, plain READ COMMITTED is enough. Competing updates on the same row queue on its lock, and when the first commits, PostgreSQL re-evaluates the waiting update’s WHERE against the newest row version. If the units are gone, it matches nothing: no row returned means “not enough stock for this channel”, and the order is back-ordered or refused with a reason. No retry loop and no lost update on this path.

Everything else follows the same discipline.

  • Same transaction. Every write path changes the balance and inserts its movement legs together.
  • INSERT-only ledger, enforced by privileges. Requests run under a restricted role with only SELECT, INSERT on rt_stock_movement, and on the balance table it can update only the bucket columns, the revision and the count flag. Application code can’t rewrite history, even by mistake.
  • CHECK constraints are the last guard. If a future code path forgets the conditional WHERE, the database still refuses reserved + picked > on_hand or a negative bucket. A ledger CHECK gives each movement kind a fixed shape: a reserve only raises reserved; a pick moves units from reserved to picked.
  • Canonical lock order. Multi-key operations lock keys sorted by (location id, SKU), so two multi-line orders can’t deadlock on stock rows.
  • Reconciliation. A ledger check compares every balance with the sum of its movements. It runs in tests after every scenario, after every benchmark, and as “Ledger check” in the demo.

The CHECKs earned their place during development. An update to a supplier’s advance shipping notice lowered the confirmed inbound quantity before moving the orders committed against it, and the inbound capacity constraint refused the statement. I fixed the statement order; without the constraint, the bug would have been silent.

How I proved it

Test A: the last units. An integration test (StockPointContentionTest) seeds a fresh session with 40 eligible units of one SKU, then starts 32 worker processes that wait for a shared start instant and fire 600 single-unit reservations between them. It asserts exactly 40 commits, 560 refusals and zero errors; a final balance of 40 on hand and 40 reserved; exactly 40 reserve rows in the ledger; and a clean ledger check. It repeats this 20 times, each on a new session, and all 20 pass. Latency across all 12,000 requests: p50 0.9 ms, p95 130 ms, p99 334 ms (local Docker, 8 CPUs). The tail is the queue on one hot row: requests wait their turn instead of failing and retrying.

Test B: peak hour. A console command (app:retail:peak-benchmark) seeds 5,000 SKUs × 9 locations (45,000 stock keys) and pushes 20,000 orders through parallel workers. Each order has 1–4 lines, SKUs are chosen with a Zipf-like distribution (s = 1.1), and the 20 hottest SKUs are deliberately under-stocked (the distribution centre holds 0.6× their expected demand) so real contention happens. Each order reads balances, picks sources, reserves in canonical key order, and rolls back and re-plans on fresh balances if it loses a race.

Metric Local Docker (8 CPUs, 16 workers) Production (shared 4 vCPU, 4 workers)
Total time 13.0 s 24.9 s
Throughput (orders processed, including refused) 1,535 orders/s 804 orders/s
Latency p50 / p95 / p99 3.2 / 48 / 115 ms 4.0 / 12.0 / 18.6 ms
Re-plans after a lost race 61 9
Deadlocks / lock timeouts 0 / 0 0 / 0
Ledger check consistent consistent (45,000 keys, 66,343 movements)

On production, 15,165 orders committed and 4,835 were refused because a line had no source, with a maximum latency of 50 ms. My reading: 16 workers on 8 CPUs buy throughput with more queueing, so the tail is longer; 4 workers queue less. Either way, no deadlocks and the ledger matched.

Trade-offs and limitations

  • One hot row is one queue. The last units of one SKU are handed out one at a time. Test A’s 334 ms p99 is that queue. I chose it over retry storms, but it is a ceiling.
  • The projection can drift in principle. It’s a mutable row next to an immutable ledger. The write discipline, CHECKs and reconciliation prevent and detect drift; they are tested, but they are a discipline, not a proof.
  • The pattern lives in one module. The ADR says to extract it when a second inventory-like module needs it, not before.
  • Synthetic load on a demo. Fictional retailer and data, no real checkout or payment, and a shared production host.

What I’d do differently or next

  • Write the reconciliation as an aggregate from day one. An earlier, join-based ledger check degraded on a freshly seeded session, where PostgreSQL has no table statistics yet. The current one is a single hash aggregate over balances UNION ALL movements, so its plan doesn’t depend on statistics.
  • Measure against the stated budget. The spec budgets p99 under 250 ms per order on a 2-vCPU shared host. The production run used 4 vCPUs, so that budget is unmeasured, and I’d repeat the run rather than rely on one.

Takeaways

  • Put the check and the write in the same statement. A conditional UPDATE … WHERE available >= q closes the race without raising the isolation level.
  • Keep the history immutable and the balance cheap. An INSERT-only ledger is the audit trail; a balance row keeps each reservation’s cost constant however long the history grows.
  • Let the database say no. Privileges and CHECK constraints catch the code path you forgot, and one of mine caught a real bug.
  • Prove it under contention, repeatedly. “Exactly 40 of 600, in each of 20 runs” is a claim someone can check. “It handles concurrency” is not.

You can launch the guided demo and watch the flash sale stop at exactly the stock that exists. The engineering page shows the last peak-hour result stored on that deployment, and the StockPoint case study covers allocation, recovery and pricing.