SR-019 — Concurrent Demand: Stock Integrity Under Simultaneous Orders System Requirements
| Metadata | Details |
|---|---|
| System Name | inventory-service — StockBalanceService Reservation & Consumption |
| Document ID | SR-2026-INV-001 |
| Author | Engineering Team |
| Status | Approved |
Traces back to BRD-018 — Concurrent Demand: Stock Integrity Under Simultaneous Orders and the Scaling Decision.
This document specifies inventory-service’s gRPC StockBalanceService — ReserveInventory/ReleaseInventory/ConsumeInventory (grpc/stockbalance.proto), called by order-service’s checkout saga (ReserveInventoryActivity/ConsumeInventoryActivity, see SR-014) — not that saga’s own sequencing, which SR-014 already specifies.
Functional Requirements
Reservation — Non-Blocking, Conditional-Update Guard
- FR-01 (Reservation Succeeds or Fails on a Single Conditional Update, Never a Separate Lock Step): reserving stock for an order line MUST be implemented as one
UPDATEstatement per SKU that both checks and moves the quantity atomically —SET quantity_reserved = quantity_reserved + :qty, quantity_available = quantity_available - :qty WHERE warehouse_id = :warehouse_id AND sku_id = :sku_id AND quantity_available >= :qty— so that two concurrent reservation attempts for the same SKU can never both succeed against a stock level that only has room for one of them. The database’s own row-level write serialization is the sole concurrency guarantee here; no application-level lock, retry loop, or version column is used or required. - FR-02 (An Unsatisfiable Reservation Fails Immediately, With No Retry): when the conditional update’s
WHEREguard matches zero rows (insufficientquantity_available), reservation for that order MUST fail immediately as a validation error — there is no retry loop, no backoff, and no re-check of a stale read. A customer whose order line can’t be satisfied finds out on the same attempt, directly satisfying BRD-018 BR-02. - FR-03 (All Lines of One Order Reserve Inside a Single Database Transaction): every order line’s conditional update, plus its reservation-guard row and ledger entry (see FR-05, FR-06), MUST execute inside one database transaction per
ReserveInventorycall — a failure on any line rolls back every line already reserved for that same call, so an order never ends up holding a partial reservation.
Consumption — Row-Locked, Deadlock-Avoided Batch Update
- FR-04 (Consumption Acquires a Row Lock via Upsert, Not a Separate Lock Statement): permanently deducting stock for an order’s already-reserved lines MUST acquire its row lock through
INSERT ... ON CONFLICT (warehouse_id, sku_id) DO UPDATE ... RETURNING quantity_physical, quantity_reserved, quantity_availableagainstinventory_balances— this upsert is the pessimistic lock; consumption MUST NOT use a separateSELECT ... FOR UPDATEstatement to achieve the same effect. Once locked,quantity_physicalandquantity_reservedboth decrease by the consumed quantity;quantity_availableis left unchanged, because it was already decremented at reservation time (FR-01) and must not be double-counted. - FR-05 (Multi-SKU Consumption Locks Rows in a Deterministic Order): when one consumption call touches more than one SKU, the distinct SKU IDs MUST be sorted (lexicographic, e.g. Go’s
sort.Strings) before acquiring their row locks one at a time — this fixed ordering is what guarantees two concurrent multi-SKU transactions can never deadlock against each other by locking the same two rows in opposite order. - FR-06 (Consumption and Reservation Share One Balance-Mutation Path):
ConsumeInventoryMUST reuse the same warehouse-scoped balance-mutation routine the admin Stock Entry flow already uses for a sale-mode transaction, rather than maintaining a second, independently-written mutation path for the checkout flow — the checkout path gets the identical row-locking and deadlock-avoidance guarantee the admin flow already relies on, by construction rather than by parallel re-implementation.
Idempotency — Append-Only Reservation Guard, Not Retry-Count Tracking
- FR-07 (Reservation State Is Tracked as Append-Only Guard Rows, Keyed for Safe Re-Delivery): each
(tenant_id, order_id, sku_id, warehouse_id)reservation line’s lifecycle MUST be recorded as a sequence of insert-only guard rows (RESERVED→RELEASEDorRESERVED→CONSUMED) rather than by updating one row’s status in place — the originalRESERVEDrow is never mutated or deleted once aRELEASED/CONSUMEDrow exists for the same line, preserving a full, auditable history of what happened to every reservation and directly satisfying BRD-018 BR-06. The write path reads the latest row per(sku_id, warehouse_id)(ordered bycreated_at DESC) to decide current state, rather than assuming a single row per tuple. - FR-08 (At Most One Active Row Per Status, Per Line): the guard table MUST enforce, at the database level, that a given
(tenant_id, order_id, sku_id, warehouse_id)line has at most one row in each of theRESERVED,RELEASED, andCONSUMEDstates at any time — enforced as three separate partial unique indexes (one per status), not a single table-wide uniqueness constraint, since all three rows for one line’s full lifecycle legitimately coexist. - FR-09 (A Redelivered Reservation Request Is a No-Op, Not a Duplicate Reservation): if
ReserveInventoryis called again for an order that already has aRESERVEDguard row for every line it’s asking to reserve (a saga-activity retry after an already-successful attempt), the call MUST return success without performing a second conditional update or writing a second ledger entry. The same no-op rule applies toReleaseInventorywhen nothing is currently in theRESERVEDstate for that order (covers both “never reserved” and “already released”). - FR-10 (Every Balance Mutation Writes an Immutable Ledger Entry): every successful reservation, release, and consumption mutation MUST append one
stock_ledger_entriesrow (quantity_changed,balance_before,balance_after,transaction_name,transaction_type,reference_id) in the same transaction as the balance mutation itself — the ledger is never written outside, or independently retried from, the transaction that moved the balance.
The reservation-hold expiry (what happens if a reservation is never consumed or released within a bounded time) is a saga-level durable-timer concern specified by SR-018’s retry/timer primitives and SR-014’s 15-minute payment-wait timer — not a database-level TTL on the reservation row itself, and not re-specified here.
High-Concurrency Scaling — Named Gap
- FR-11 (A Pre-Reservation Fast-Reject Layer for Large-Scale Contention Is Not Yet Built):
StockBalanceServiceas specified above handles correctness under concurrent contention at the database level, but has no in-memory, pre-database fast-reject layer for absorbing a much larger burst of simultaneous requests against the same SKU (a scheduled flash-sale-scale event) with first-come-first-served fairness and sub-database-round-trip rejection latency. (Gap — tracked as technical debt, see TD-00013).
History Retrieval — Named Gap
- FR-12 (No Query Surface Exists Over a Reservation’s Recorded History): FR-07’s append-only guard rows make a complete reservation lifecycle durable in
order_inventory_reservations, butStockBalanceServiceexposes no method — andinventory-servicehas no repository, service, or transport-layer code anywhere — that reads that history back out for a given order or SKU. The three existing RPCs (ReserveInventory/ReleaseInventory/ConsumeInventory) only read the latest row per tuple internally, as a write-path idempotency check; none of them, nor any other endpoint, returns the fullRESERVED→RELEASED/CONSUMEDsequence to a caller. Satisfying BRD-018 BR-06 for customer support or Finance & Operations today requires direct database access, bypassing normal tenant-scoped, audited access. (Gap — tracked as technical debt, see TD-00015).
Non-Functional Requirements
Correctness Under Concurrency
- NFR-01 (No Application-Level Locking Primitive Is Used for Either Step): neither reservation nor consumption MUST rely on an application-managed mutex, distributed lock, or optimistic-concurrency version column — both steps’ correctness under concurrent access MUST come entirely from PostgreSQL’s own row-level write guarantees (a guarded
UPDATE’s atomicity for reservation, a row lock acquired viaINSERT ... ON CONFLICT DO UPDATEfor consumption). - NFR-02 (Consumption Never Deadlocks Regardless of Request Arrival Order): two concurrent multi-SKU consumption calls that share any SKU in common MUST NOT deadlock against each other, under any arrival order or interleaving — guaranteed by FR-05’s deterministic lock-acquisition ordering, not by database-level deadlock detection and retry.
Multi-Tenancy & Auth Propagation
- NFR-03 (Tenant/User Context Travels as gRPC Metadata, Never in the Request Payload): every
ReserveInventory/ReleaseInventory/ConsumeInventorycall fromorder-serviceMUST carrytenant_id/user_id/roleas gRPC metadata sourced from the calling saga activity’s own auth context, per the platform’s security standards —inventory-service’s server-side interceptor populates these from metadata, never from the message body.
Composition & Reuse
- NFR-04 (DTO-Based Entry Points): every
StockBalanceServicemethod and its underlying service-layer call MUST take a single input DTO rather than positional parameters, per the platform’s coding standards. - NFR-05 (Consumption Composes the Existing Stock-Mutation Routine Rather Than Forking It): per FR-06, the checkout-driven consumption path MUST be implemented as a caller of the existing warehouse-scoped stock-mutation routine the admin Stock Entry flow already uses, not as an independently-maintained second implementation of the same balance-update logic.
Related Documents
- BRD-018 — Concurrent Demand: Stock Integrity Under Simultaneous Orders and the Scaling Decision
- SR-014 — Checkout Completion: Payment Capture & Fulfillment Handoff System Requirements — the saga activities (
ReserveInventoryActivity/ConsumeInventoryActivity) that call this spec’s gRPC surface, and the 15-minute payment-wait timer that bounds how long a reservation can sit unconsumed - SR-018 — Dependable, Auditable Multi-Step Order Transaction Coordination: System Requirements — the retry/timer/signal primitives this spec’s idempotency (FR-09) is designed to be safe under
- ADR-00035 — Conditional-Update Reservation vs. Row-Locked Consumption, and the Redis/Token-Bucket Scaling Decision
- Technical Debt — High-Concurrency Stock Contention Scaling Gap — FR-11’s gap, in full
- Technical Debt — Order Inventory Reservation History Has No Query Surface — FR-12’s gap, in full
- Architecture — Inventory Stock Reservation, Consumption, and Concurrency Control — the component topology and end-to-end flow implementing every FR/NFR in this spec
- Architecture — Checkout Completion: Payment Capture and Fulfillment Handoff
- Technical Debt — Checkout Completion Payment Flow Gaps — TD-05’s related, downstream gap in
ConsumeInventoryActivity’s own saga-visible failure state - Microservices: inventory-service, order-service