ADR-00035 — Conditional-Update Reservation vs. Row-Locked Consumption, and the Redis/Token-Bucket Scaling Decision

By Engineering Team•October 8, 2026•8 min read
  • Status: Approved / Implemented (reservation & consumption); Deferred (Redis/token-bucket scaling layer — see Option 3)
  • Date: 2026-10-08
  • Authors: Engineering Team

Context

BRD-018 commits the business to guaranteeing that the same unit of stock can never be claimed by two concurrent orders, without checkout slowing down for everyone else while that contention is being resolved. inventory-service’s StockBalanceService (SR-019) has to make that guarantee hold at two structurally different moments in an order’s life: reservation (ReserveInventory, at order placement — set stock aside, provisional) and consumption (ConsumeInventory, after payment and shipment creation have both succeeded — permanently deduct it, final). This ADR answers two separate but related questions: first, why these two moments use two different concurrency-control mechanisms rather than one uniform strategy applied to both; second, whether a Redis-backed, in-memory, token-bucket-style fast-reject layer should sit in front of the database for both moments today, to handle a much larger concurrent-demand spike than ordinary contention.


Decision Drivers (FRs & NFRs)

See SR-019 for the full requirement list.

  • FR-01/FR-02 (Reservation Fails Fast on a Single Conditional Update): reservation must reject an unsatisfiable request on its first attempt, with no retry loop and no separate lock step.
  • FR-04/FR-05 (Consumption Locks Rows Deterministically): consumption must acquire an actual row lock (multiple balance fields mutate together) and must never deadlock across concurrent multi-SKU calls.
  • NFR-01 (No Application-Level Locking Primitive): both steps’ correctness must come from PostgreSQL’s own guarantees, not a hand-built mutex or version column.
  • NFR-02 (No Deadlocks Regardless of Arrival Order): a hard constraint specifically on the consumption side, where more than one row can be touched per call.
  • FR-11 / BRD-018 BR-04 (The Redis/Scaling Layer Is a Named, Deliberate Decision Point): whether to build a pre-database fast-reject layer is framed as a business investment decision with a clear trigger, not an immediate requirement.

Options Evaluated — Part 1: Reservation’s Concurrency Mechanism

Option 1 — Conditional-update guard (UPDATE ... WHERE quantity_available >= :qty) (CHOSEN)

Reservation is a single UPDATE whose WHERE clause both re-checks and moves the quantity in one atomic statement — no separate read, no explicit lock acquisition, no version column.

  • Pros:
    • One round trip, no lock held across two statements. A separate “read current quantity, decide in application code, then write” sequence would need an explicit lock (or a version-column CAS retry) spanning the gap between the read and the write; folding the check into the UPDATE’s own WHERE clause closes that gap entirely — there is no window where a second transaction could observe a quantity that’s about to become stale.
    • Fails fast, with the failure mode PostgreSQL already gives for free. A WHERE clause that matches zero rows is exactly what happens when quantity_available has already dropped below what’s being requested — the caller gets a definite, immediate answer (zero rows affected) without a retry loop or a second query to distinguish “row doesn’t exist” from “row exists but guard failed.”
    • No version column to maintain. A classic optimistic-locking CAS pattern (WHERE version = :expected_version, then increment version on success) needs a column whose entire purpose is concurrency control, plus retry logic for the case where the CAS fails because someone else won the race first. The conditional UPDATE achieves the same non-blocking, no-lost-update guarantee directly against the business column (quantity_available) itself — the column being protected is the column doing the protecting.
  • Cons & Accepted Trade-offs:
    • No retry on guard failure — a transient, genuinely-recoverable contention loss (not just “actually sold out”) still surfaces as an immediate failure to the caller. Accepted because reservation sits inside a Temporal saga activity (SR-014); if a retry were ever warranted, that is the saga’s own RetryPolicy to apply, not logic duplicated inside inventory-service itself.
    • Doesn’t generalize to a multi-statement reservation that needs to hold a lock across other work. Not a real constraint today — every reservation line’s guard and ledger write happen inside the same transaction as the conditional update itself (SR-019 FR-03), so no cross-statement lock-holding is ever needed.

Option 2 — Pessimistic row lock for reservation too (SELECT ... FOR UPDATE, then a separate application-level check-and-write)

Lock the row first, read the current quantity, decide in application code whether enough is available, then write the new quantity — mirroring what consumption does (Part 2, Option 1 below).

  • Cons (Why Rejected):
    • Adds a lock-hold window for no additional safety. The conditional UPDATE in Option 1 already gets the identical atomicity guarantee in one statement; adding an explicit SELECT ... FOR UPDATE beforehand only adds a window during which the row is locked and other reservation attempts for the same SKU queue up waiting on it, with no correctness benefit over the single-statement form.
    • Directly works against FR-01/FR-02’s fail-fast requirement. A request that would have failed the availability check still has to wait in line for the lock first, under high contention for a popular SKU — exactly the latency risk BRD-018 BR-03 (checkout stays fast under contention) exists to avoid.

Options Evaluated — Part 2: Consumption’s Concurrency Mechanism

Option 1 — Pessimistic row lock via INSERT ... ON CONFLICT (warehouse_id, sku_id) DO UPDATE ... RETURNING (CHOSEN)

Consumption’s balance mutation runs through the same upsert-as-lock pattern the admin Stock Entry flow already uses for every transaction mode (ProcessWarehouseStockBalance): an upsert against inventory_balances acquires the row (creating it with zero balances if it somehow doesn’t exist yet), returns the locked row’s current values, and only then applies the mutation — all inside the caller’s transaction. SR-019 FR-05’s deterministic SKU-ID sort runs before this loop for any multi-SKU call.

  • Pros:
    • A single mechanism that already handles “row might not exist yet.” Reservation’s conditional UPDATE can assume the balance row already exists (opening stock already created it); consumption’s shared mutation routine is also the one every admin stock-entry transaction mode uses, including modes that legitimately run against a SKU/warehouse pair for the first time — the upsert’s DO UPDATE branch is what makes locking and first-touch row creation the same statement instead of two.
    • Reuses a lock discipline that already has deadlock avoidance solved. Because ConsumeInventory calls the exact same routine the admin flow already relies on (SR-019 FR-06), it inherits FR-05’s sorted-SKU-ID lock ordering for free — there is no second, independently-maintained deadlock story to get right for the checkout path specifically.
    • A genuine multi-field mutation, which is exactly what a row lock (not a single-column conditional UPDATE) is for. Consumption changes quantity_physical and quantity_reserved together while deliberately leaving quantity_available untouched (it was already moved at reservation time) — a single-column guarded UPDATE like reservation’s doesn’t naturally express “lock this row, then apply a multi-field, mode-dependent mutation to it,” which is exactly the shape every other Stock Entry transaction mode already needs.
  • Cons & Accepted Trade-offs:
    • A lock is actually held for the duration of the upsert-plus-mutation, unlike reservation’s single-statement form — accepted because consumption only ever runs on lines already known-reserved (the stock is already provisionally spoken for), so lock contention here reflects genuine, unavoidable write contention on the same balance row, not customers racing to be first.

Option 2 — Conditional-update guard for consumption too (mirroring reservation’s own mechanism)

Apply the same single-statement UPDATE ... WHERE ... pattern consumption’s sibling, reservation, uses.

  • Cons (Why Rejected):
    • Consumption isn’t a single guarded column decrement — it’s an unconditional, multi-field mutation on a row already known to be reserved. There’s no “does enough exist” check left to perform at consumption time (that check already happened, successfully, at reservation); a conditional guard clause would be checking a condition that’s structurally always already true, adding complexity without protecting anything.
    • Would have forced ConsumeInventory to maintain its own, parallel mutation path instead of reusing ProcessWarehouseStockBalance (SR-019 FR-06) — the one mutation routine every other Stock Entry transaction mode already shares, including its already-solved deadlock-avoidance ordering.

Options Evaluated — Part 3: High-Concurrency Scaling Layer

Option 1 — Database-only concurrency control for every scale of demand (CHOSEN, for current scale)

Rely on the two mechanisms above — conditional-update reservation and upsert-locked consumption — as the complete concurrency story, for ordinary contention (a handful to a moderate number of simultaneous orders racing for the same SKU).

  • Pros:
    • Zero additional infrastructure, and the guarantee is already proven correct — both mechanisms above are implemented and already provide the exact “exactly one winner” guarantee BRD-018 BR-01 requires, at the database’s own consistency boundary.
    • No new failure mode introduced. A cache-based fast-reject layer that falls out of sync with the database (even briefly) risks under- or over-rejecting; the database-only approach has no second source of truth to keep consistent.
  • Cons & Accepted Trade-offs:
    • Every rejected reservation still costs a full database round trip, and at a large enough burst of simultaneous requests against one SKU, PostgreSQL’s own row-lock queuing (for consumption) and write contention (for reservation) becomes the platform’s bottleneck for that SKU specifically — acceptable at today’s observed demand, not yet validated at flash-sale scale.
    • No fairness ordering beyond whichever request’s UPDATE the database happens to serialize first — acceptable for ordinary contention, but not a designed first-come-first-served guarantee as BRD-018 BR-05 would require at larger scale.

Option 2 — Redis/token-bucket pre-reservation layer in front of the database, built now (NOT CHOSEN — deferred)

An in-memory, atomically-decremented token bucket per SKU, consulted before the database is touched at all: a request that finds the bucket empty is rejected immediately (sub-database-round-trip latency, commonly surfaced as an HTTP 429), and a sequential token per accepted request gives a genuine first-come-first-served ordering; a background process reconciles the bucket’s count against the authoritative database balance.

  • Pros:
    • Directly satisfies BRD-018 BR-03 (checkout stays fast under heavy contention) and BR-05 (fairness ordering) at a scale Option 1 alone cannot guarantee.
    • Fast-fails the overwhelming majority of “doomed to lose” requests before they ever reach the database, sparing PostgreSQL’s row-lock queue from absorbing load that was never going to succeed anyway.
  • Cons (Why Not Built Now):
    • No scheduled high-concurrency event exists today that this platform’s current, database-only mechanism has actually failed to handle. Building a second, cache-based source of truth for stock availability — with its own reconciliation process, its own staleness window, and its own operational surface — ahead of an actual need duplicates ADR-00026’s already-accepted reasoning for deferring Redis adoption on the checkout-session side: real infrastructure cost, paid before the scale that justifies it exists.
    • Introduces exactly the kind of speculative, ahead-of-need complexity this platform’s own coding standards caution against — a reconciliation process between two sources of truth is nontrivial to get right, and getting it wrong (bucket and database disagreeing) would be a self-inflicted correctness bug in a system that today has none.
    • BRD-018 itself frames this as a deliberate, business-owned investment decision tied to a known future event (e.g. a scheduled flash sale) — not a default to build speculatively. See Technical Debt — TD-00013 for the full remediation direction, kept ready rather than built.

Final Decision

Reservation and consumption deliberately use two different concurrency-control mechanisms, not one uniform strategy. Reservation uses a single, non-blocking conditional UPDATE (Part 1, Option 1) because it is a single-column, fail-fast availability check where a held lock would only add latency under exactly the contention it’s trying to survive. Consumption uses a pessimistic row lock acquired via INSERT ... ON CONFLICT DO UPDATE (Part 2, Option 1) because it is an unconditional, multi-field mutation on a row already known to be reserved, and because reusing the admin Stock Entry flow’s existing lock-and-mutate routine inherits that routine’s already-solved deadlock-avoidance ordering for free. The Redis/token-bucket pre-reservation layer (Part 3, Option 2) is deferred, not rejected outright — today’s database-only mechanism (Part 3, Option 1) is accepted as sufficient for current demand, with the Redis layer’s full design kept as a named, ready-to-build remediation direction in TD-00013 for the business to trigger ahead of a specific future high-concurrency event, per BRD-018 BR-04.