Architecture — Inventory Stock Reservation, Consumption, and Concurrency Control
| Metadata | Details |
|---|---|
| System | inventory-service — StockBalanceService Reservation & Consumption |
| Document ID | ARCH-2026-INV-001 |
| Author | Engineering Team |
| Status | Approved |
Implements SR-019, per the decisions in ADR-00035. This is the “inside the black box” companion to Architecture — Checkout Completion: Payment Capture and Fulfillment Handoff, which already covers ReserveInventoryActivity/ConsumeInventoryActivity at the saga-sequencing level without describing what happens inside inventory-service itself when those activities are called — this doc does not re-describe the saga’s own step ordering, compensation, or timers.
Diagram

Components
| Component | Language / Runtime | Role in this flow |
|---|---|---|
order-service |
Go, Temporal workflow/activities | Calls StockBalanceService.ReserveInventory/ReleaseInventory/ConsumeInventory over gRPC from ReserveInventoryActivity/ConsumeInventoryActivity (and the saga’s own compensation path for release) — sequencing already covered by Architecture-00012; this doc starts where that gRPC call lands. |
inventory-service — StockBalanceService (gRPC) |
Go, gRPC server (grpc/stockbalance.proto) |
Entry point for all three methods; extracts tenant_id/user_id/role from inbound gRPC metadata, never the request payload — SR-019 NFR-03. |
stock_balance_reservation_impl_svc.go |
Go, service layer | Owns ReserveInventory/ReleaseInventory — the conditional-update guard and the append-only guard-row writes for both reservation and release — SR-019 FR-01–FR-03, FR-07–FR-09. |
stock_balance_write_impl_svc.go |
Go, service layer | Owns ProcessWarehouseStockBalance — the single shared balance-mutation routine used by both the admin Stock Entry flow and checkout-driven consumption; the ModeSale branch is what ConsumeInventory calls into — SR-019 FR-04–FR-06. |
inventory_balances (PostgreSQL) |
PostgreSQL table | Holds quantity_physical/quantity_reserved/quantity_available per (warehouse_id, sku_id) — the row both the reservation guard’s conditional UPDATE and consumption’s INSERT ... ON CONFLICT DO UPDATE act on. |
order_inventory_reservations (PostgreSQL) |
PostgreSQL table | The append-only guard-row table — one row per (tenant_id, order_id, sku_id, warehouse_id, status), three per-status partial unique indexes — that makes a retried ReserveInventory/ReleaseInventory/ConsumeInventory call a safe no-op — SR-019 FR-07–FR-09. |
stock_ledger_entries (PostgreSQL) |
PostgreSQL table | Immutable ledger row appended in the same transaction as every balance mutation — SR-019 FR-10. |
End-to-end flow (A) — Reservation: non-blocking conditional-update guard
order-service’sReserveInventoryActivitycallsReserveInventorywith the order’s line items. The service layer opens a single database transaction covering every line in the call — SR-019 FR-03.- Before touching
inventory_balances, the service checksorder_inventory_reservationsfor an existingRESERVEDrow for each(tenant_id, order_id, sku_id, warehouse_id)line. If every requested line already has one (a saga-activity retry after an already-successful attempt), the call returns success immediately with no further writes — SR-019 FR-09. - For each genuinely new line, the service issues one conditional
UPDATE:
This single statement is both the check and the move — there is no separate read-then-write, no version column, and no application-level lock. PostgreSQL’s own row-level write serialization is the only concurrency guarantee: if two concurrent orders race for the last unit, exactly oneUPDATE inventory_balances 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;UPDATEmatches a row and moves the quantity; the other matches zero rows — SR-019 FR-01, NFR-01. - If the
UPDATEmatches zero rows (insufficientquantity_available), reservation for that line fails immediately as a validation error — no retry, no backoff, no re-check of a stale read. The transaction rolls back, so no other line in the same call is left partially reserved — SR-019 FR-02. - If the
UPDATEsucceeds, the service inserts aRESERVEDguard row intoorder_inventory_reservationsand astock_ledger_entriesrow (quantity_changed,balance_before,balance_after) in the same transaction, then commits — SR-019 FR-07, FR-10.
End-to-end flow (B) — Release: the saga’s compensation path
- If a later saga step fails (payment, shipment — see Architecture-00012’s compensation actions),
order-servicecallsReleaseInventoryfor the same order. - The service checks for an existing
RELEASEDrow, or the absence of anyRESERVEDrow, for each line — either case (already released, or never reserved) is a no-op — SR-019 FR-09. - Otherwise, the service reverses the reservation’s own
UPDATE(quantity_reserveddown,quantity_availableup by the same amount), inserts aRELEASEDguard row, and appends a ledger entry — all in one transaction. The originalRESERVEDrow is never mutated or deleted; it remains as history alongside the newRELEASEDrow — SR-019 FR-07. - The three guard-row statuses (
RESERVED,RELEASED,CONSUMED) are each enforced unique per line via their own partial unique index, rather than one table-wide constraint — this is what lets all three rows for one line’s full lifecycle legitimately coexist while still preventing two activeRESERVEDrows for the same line — SR-019 FR-08.
End-to-end flow (C) — Consumption: upsert-acquired row lock, deterministic ordering
- Once payment and shipment have both succeeded,
order-service’sConsumeInventoryActivitycallsConsumeInventory. The service again checksorder_inventory_reservationsfirst — a redelivered consume call for lines that already have aCONSUMEDrow is a no-op, consistent with FR-09’s idempotency rule. - For genuinely new lines, the service collects every distinct SKU ID touched by the call and sorts them lexicographically (Go’s
sort.Strings) before acquiring any row lock — SR-019 FR-05. This fixed ordering is what guarantees two concurrent multi-SKU consumption calls can never deadlock against each other by locking the same two rows in opposite order — SR-019 NFR-02. - For each SKU in that sorted order,
ConsumeInventorycalls intoProcessWarehouseStockBalance— the same balance-mutation routine the admin Stock Entry flow already uses for aModeSaletransaction, not a second, independently-written mutation path — SR-019 FR-06, NFR-05. The routine acquires its row lock via:
The upsert itself is the pessimistic lock — there is no separateINSERT INTO inventory_balances (warehouse_id, sku_id, quantity_physical, quantity_reserved, quantity_available, ...) VALUES (:warehouse_id, :sku_id, 0, 0, 0, ...) ON CONFLICT (warehouse_id, sku_id) DO UPDATE SET quantity_physical = inventory_balances.quantity_physical + :qty_changed, quantity_reserved = inventory_balances.quantity_reserved + :qty_changed, updated_at = CURRENT_TIMESTAMP, updated_user_id = :user_id RETURNING quantity_physical, quantity_reserved, quantity_available;SELECT ... FOR UPDATEstatement.qty_changedis negative for a sale, soquantity_physicalandquantity_reservedboth decrease by the consumed amount;quantity_availableis deliberately left untouched, because it was already decremented at reservation time (flow A, step 3) and must not be double-counted — SR-019 FR-04. - Each successful line writes a
CONSUMEDguard row and astock_ledger_entriesrow, then the same shared routine computesafterAvailable(equal to the unchangedquantity_available, specifically for thisModeSalecase) to decide whether to fire astock-balance-status-changedevent forsearch-service— reused as-is from the admin flow, not re-derived for checkout.
Why this is reliable under concurrent demand
- Reservation never pays the cost of a lock it doesn’t need. A single conditional
UPDATEboth checks and moves the quantity atomically — no application-level mutex, no version-column compare-and-swap, no retry loop on failure — so a losing request fails fast rather than queuing behind a lock it was always going to lose — BRD-018 BR-01, BR-02, see ADR-00035 Part 1 for why this beats an explicit lock-then-check for reservation specifically. - Consumption gets its concurrency safety by construction, not by a second implementation. Routing
ConsumeInventorythrough the exact sameProcessWarehouseStockBalanceroutine the admin Stock Entry flow already relies on means the checkout path inherits that routine’s row-locking and deadlock-avoidance guarantees automatically — see ADR-00035 Part 2 for why consumption’s locking mechanism is deliberately different from reservation’s. - Two concurrent multi-SKU consumptions can never deadlock each other. Sorting SKU IDs before locking (flow C, step 2) fixes the acquisition order regardless of which order the two calls’ own line items arrived in — SR-019 NFR-02.
- A saga-activity retry is always a safe no-op, never a duplicate mutation. The append-only guard-row table, keyed per line and per status via three separate partial unique indexes, is what lets
ReserveInventory/ReleaseInventory/ConsumeInventoryall be re-called after a timeout or a worker crash without double-reserving, double-releasing, or double-consuming anything — SR-019 FR-07–FR-09. - Today’s mechanisms resolve contention correctly, but only at the database row itself. There is no layer upstream of PostgreSQL that pre-filters or fairly sequences a much larger, scheduled burst of simultaneous demand before it reaches the database — named as a deliberately deferred gap, not an oversight, in Technical Debt — TD-00013.
History & audit trail: why reservation state is append-only, not mutated in place
order_inventory_reservations did not start out as the append-only table described in flows (A)–(C) above — it evolved into that shape in two steps, and the evolution itself is why a line’s full lifecycle (not just its current status) is always on the record, satisfying BRD-018 BR-06.
- Original shape — one mutable row per line. The table was first created with a single plain unique index on
(tenant_id, order_id, sku_id, warehouse_id)and astatuscolumn meant to hold the line’s current state (RESERVEDorRELEASED) — i.e., a design where a release wouldUPDATEthe existing row’s status in place rather than insert a new one. - Converted to append-only before that mutate-in-place design shipped in practice. The plain unique index was replaced with two partial unique indexes — one scoped
WHERE status = 'RESERVED', one scopedWHERE status = 'RELEASED'— so a single line can hold one row of each status at once (each still capped at exactly one by its own partial index).ReserveOrderInventory/ReleaseOrderInventorywere changed in the same step to read the latest row per(sku_id, warehouse_id)(DISTINCT ON (sku_id, warehouse_id) ... ORDER BY created_at DESC) and to alwaysINSERTa new row rather thanUPDATEthe existing one — this is what flow (B), step 3 above means by “the originalRESERVEDrow is never mutated or deleted.” - Extended with a third status. A
CONSUMEDpartial unique index was added the same way once flow (C) — permanent consumption — was implemented, so a line’s full lifecycle can legitimately hold up to three rows: oneRESERVED, and one of eitherRELEASEDorCONSUMED.
The result is that nothing about an earlier step is ever lost: querying every row for a given (tenant_id, order_id, sku_id, warehouse_id) always reconstructs the complete sequence of what happened to that line’s reservation, in order, exactly as BRD-018 BR-06 requires.
This history is currently write-path-only. The “latest row” lookups described in flows (A)–(C) exist solely inside ReserveInventory/ReleaseInventory/ConsumeInventory themselves, to decide idempotent no-op behavior on a retried call — none of them, nor any other method, repository function, or endpoint, returns a line’s full recorded history to a caller. There is today no way for customer support or Finance & Operations to ask “show me everything that happened to this order’s reservation for this SKU” without querying the database directly. (Gap — tracked as technical debt, see TD-00015, SR-019 FR-12.)
Related Documents
- BRD-018 — Concurrent Demand: Stock Integrity Under Simultaneous Orders and the Scaling Decision
- SR-019 — Concurrent Demand: Stock Integrity Under Simultaneous Orders System Requirements
- ADR-00035 — Conditional-Update Reservation vs. Row-Locked Consumption, and the Redis/Token-Bucket Scaling Decision
- Technical Debt — High-Concurrency Stock Contention Scaling Gap
- Technical Debt — Order Inventory Reservation History Has No Query Surface
- Architecture — Checkout Completion: Payment Capture and Fulfillment Handoff — the saga-level sequencing that calls into this document’s
ReserveInventory/ReleaseInventory/ConsumeInventoryflows - SR-014 — Checkout Completion: Payment Capture & Fulfillment Handoff System Requirements — the 15-minute payment-wait timer bounding how long a reservation can sit unconsumed
- SR-020 — Warehouse Stock Entry: Ledger & Approval Control System Requirements — the admin Stock Entry flow that
stock_balance_write_impl_svc.go’s sharedProcessWarehouseStockBalanceroutine (flow C, step 3) is reused from - Admin UI Walkthrough — Warehouse Stock Entry Console — the page-by-page walkthrough of that admin Stock Entry flow
- Microservices: inventory-service, order-service