Architecture — Inventory Stock Reservation, Consumption, and Concurrency Control

By Engineering Team•October 8, 2026•6 min read
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

Inventory stock reservation and consumption — the conditional-update reservation guard, the upsert-acquired row lock for consumption, and the append-only reservation-guard table that ties both together


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

  1. order-service’s ReserveInventoryActivity calls ReserveInventory with the order’s line items. The service layer opens a single database transaction covering every line in the call — SR-019 FR-03.
  2. Before touching inventory_balances, the service checks order_inventory_reservations for an existing RESERVED row 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.
  3. For each genuinely new line, the service issues one conditional UPDATE:
    UPDATE 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;
    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 one UPDATE matches a row and moves the quantity; the other matches zero rows — SR-019 FR-01, NFR-01.
  4. If the UPDATE matches zero rows (insufficient quantity_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.
  5. If the UPDATE succeeds, the service inserts a RESERVED guard row into order_inventory_reservations and a stock_ledger_entries row (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

  1. If a later saga step fails (payment, shipment — see Architecture-00012’s compensation actions), order-service calls ReleaseInventory for the same order.
  2. The service checks for an existing RELEASED row, or the absence of any RESERVED row, for each line — either case (already released, or never reserved) is a no-op — SR-019 FR-09.
  3. Otherwise, the service reverses the reservation’s own UPDATE (quantity_reserved down, quantity_available up by the same amount), inserts a RELEASED guard row, and appends a ledger entry — all in one transaction. The original RESERVED row is never mutated or deleted; it remains as history alongside the new RELEASED row — SR-019 FR-07.
  4. 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 active RESERVED rows for the same line — SR-019 FR-08.

End-to-end flow (C) — Consumption: upsert-acquired row lock, deterministic ordering

  1. Once payment and shipment have both succeeded, order-service’s ConsumeInventoryActivity calls ConsumeInventory. The service again checks order_inventory_reservations first — a redelivered consume call for lines that already have a CONSUMED row is a no-op, consistent with FR-09’s idempotency rule.
  2. 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.
  3. For each SKU in that sorted order, ConsumeInventory calls into ProcessWarehouseStockBalance — the same balance-mutation routine the admin Stock Entry flow already uses for a ModeSale transaction, not a second, independently-written mutation path — SR-019 FR-06, NFR-05. The routine acquires its row lock via:
    INSERT 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;
    The upsert itself is the pessimistic lock — there is no separate SELECT ... FOR UPDATE statement. qty_changed is negative for a sale, so quantity_physical and quantity_reserved both decrease by the consumed amount; quantity_available is 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.
  4. Each successful line writes a CONSUMED guard row and a stock_ledger_entries row, then the same shared routine computes afterAvailable (equal to the unchanged quantity_available, specifically for this ModeSale case) to decide whether to fire a stock-balance-status-changed event for search-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 UPDATE both 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 ConsumeInventory through the exact same ProcessWarehouseStockBalance routine 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/ConsumeInventory all 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.

  1. 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 a status column meant to hold the line’s current state (RESERVED or RELEASED) — i.e., a design where a release would UPDATE the existing row’s status in place rather than insert a new one.
  2. 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 scoped WHERE 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/ReleaseOrderInventory were 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 always INSERT a new row rather than UPDATE the existing one — this is what flow (B), step 3 above means by “the original RESERVED row is never mutated or deleted.”
  3. Extended with a third status. A CONSUMED partial 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: one RESERVED, and one of either RELEASED or CONSUMED.

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.)