Design a Distributed Inventory Reservation System: Prevent Overselling at Scale

Tags:

Imagine a fictional online retailer selling the last 100 headphones during a festival sale. Thousands of shoppers click Buy Now, but payment takes several minutes. If the checkout service merely reads the available stock before accepting an order, two customers can buy the same last unit. A reservation service solves this by temporarily allocating stock before payment and releasing it when checkout expires. The challenge is to maintain correctness even when requests are retried, workers crash or payment callbacks arrive late.

Conceptual overview; hold duration is configurable and Redis is optional, not authoritative.

Difficulty: Intermediate to advanced. Prerequisites: SQL transactions, HTTP APIs and message queues.

1. Requirements and invariants

Define the inventory unit as a SKU at a fulfillment location. A reservation holds a quantity for one checkout. The service must support reserve, confirm, release and status lookup. Exclude replenishment forecasting and warehouse routing from the initial scope. A successful reservation must never allocate more units than are available, even under concurrent requests.

RequirementDesign implicationPrevent oversellingAtomic conditional updateRetry safelyUnique tenant-scoped request keyExpire unpaid holdsDurable expiry timestamp and recovery workerConfirm paid ordersConditional state transitionLow latencyShort transactions; no payment calls inside locks

Maintain available, reserved and sold quantities as nonnegative values. Within a fixed stock allocation their sum stays constant. Restocking and adjustments must be recorded as explicit inventory movements. Do not confuse a cached product availability estimate with the authoritative decision to reserve.

2. Capacity and architecture evolution

Assume 2 million checkout attempts per day, each reserving an average of two SKUs. This gives about 46 SKU reservation attempts per second on average. A twentyfold burst produces about 926 attempts per second. With a ten-minute hold and a sustained peak of 463 checkouts per second, the theoretical upper bound is 277,800 simultaneous holds if none completes early. These are illustrative assumptions; actual hold duration and traffic skew determine sizing.

Start with a single relational database and one service. An indexed stock row and a transaction are sufficient for moderate load. Next add stateless API replicas, a durable expiry worker and an outbox relay. Finally partition inventory by SKU and location when measurements justify it. A popular SKU remains a hot key even after sharding, so admission control and bounded queues may be more useful than simply adding database nodes.

3. High-level design

The checkout API calls the reservation service with a stable checkout identifier. The service validates quantities and writes the stock update and reservation record atomically. Payment is initiated only after the reservation commits. A payment callback requests confirmation; an expiry worker releases abandoned reservations. Both compete through conditional transitions on the same authoritative record. An outbox relay sends committed changes to order and reporting services.

ComponentResponsibilityCheckout APIAuthentication, request validation and orchestrationReservation serviceAtomic allocation and state transitionsInventory databaseAuthoritative stock and reservation stateExpiry workerRelease overdue active holdsOutbox relayPublish committed state changesConsumersIdempotent order and reporting updates

Keep Redis or a CDN cache for product browsing if useful, but never authorize reservations solely from a stale cache. If the database is unavailable, reject new reservations temporarily rather than accept orders that cannot be backed by stock. A waiting room can protect hot products during a sale; it does not replace the inventory invariant.

4. Low-level design and API

EndpointSemanticsPOST /v1/reservationsCreate hold; 201 or 409 insufficient stockGET /v1/reservations/{id}Read current state and expiryPOST /v1/reservations/{id}/confirmConfirm active unexpired holdPOST /v1/reservations/{id}/releaseRelease active hold idempotently
POST /v1/reservations
Idempotency-Key: checkout-482
{“sku”:”HEADPHONE-01″,”location”:”WH-1″,”quantity”:2}

201 Created
{“id”:”res_482″,”state”:”HELD”,”expires_at”:”2026-12-04T10:10:00Z”}

Store a request hash with the idempotency key. A retry with the same payload returns the original reservation; a different payload under the same key returns a conflict. Authorize all management operations by tenant and checkout ownership. Confirmation should be callable only by trusted order or payment orchestration services.

CREATE TABLE inventory (
sku text, location text,
available bigint NOT NULL CHECK (available >= 0),
reserved bigint NOT NULL CHECK (reserved >= 0),
sold bigint NOT NULL CHECK (sold >= 0),
PRIMARY KEY (sku, location)
);
CREATE TABLE reservations (
id uuid PRIMARY KEY,
tenant_id text NOT NULL,
request_key text NOT NULL,
request_hash text NOT NULL,
sku text NOT NULL, location text NOT NULL,
quantity bigint NOT NULL CHECK (quantity > 0),
state text NOT NULL CHECK (state IN (‘HELD’,’CONFIRMED’,’RELEASED’,’EXPIRED’)),
expires_at timestamptz NOT NULL,
UNIQUE (tenant_id, request_key),
FOREIGN KEY (sku,location) REFERENCES inventory(sku,location)
);
CREATE INDEX due_holds ON reservations(expires_at)
WHERE state = ‘HELD’;

5. Prevent overselling with atomic SQL

BEGIN;
UPDATE inventory
SET available = available – :qty,
reserved = reserved + :qty
WHERE sku = :sku AND location = :location
AND available >= :qty
RETURNING available;
— If no row returned, roll back and reject.
— Insert reservation and outbox event in this transaction.
COMMIT;

The placeholders represent bound parameters, not literal PostgreSQL syntax. PostgreSQL serializes conflicting updates to the same row and rechecks the condition under READ COMMITTED. If two customers request the last unit, one update succeeds and the other finds insufficient stock. Insert the reservation and outbox record before committing; a unique-key conflict must roll back the stock update and retrieve the original reservation in a new transaction. For a multi-item basket, lock stock rows in deterministic order and roll back the entire basket if any item is unavailable. Across shards, a saga can release partial holds, but it does not provide atomic all-or-nothing visibility.

6. Confirmation versus expiry

The state machine permits HELD to become CONFIRMED, RELEASED or EXPIRED. Terminal states cannot transition back to HELD. In a short transaction lock the reservation row, evaluate the current database clock after acquiring the lock, and verify that the hold is still active and unexpired before confirming. Confirmation moves quantity from reserved to sold; release or expiry moves it from reserved to available. Update the reservation and inventory in the same transaction. A duplicate callback sees the terminal state and must not move stock again.

Payment and inventory live in different systems. If payment succeeds after the hold expires, do not resurrect the reservation blindly. Attempt a fresh reservation only if business policy permits; otherwise void or refund the payment and notify the customer. Prefer authorization before capture where supported, and reconcile payment and inventory records periodically. No distributed lock alone can make a payment provider and a database commit atomically.

7. Recovery, scaling and tradeoffs

FailureResponseAPI timeout after commitRetry with same key and return original holdExpiry worker crashesScan overdue HELD rows after restartPayment callback duplicatedConditional terminal transitionBroker unavailableRetain transactional outbox and retry relayHot SKU contentionBound admission and monitor lock waitDatabase failoverFence old primary; reconcile acknowledged writes

Workers can claim bounded batches using FOR UPDATE SKIP LOCKED, but should keep transactions short and avoid network calls while holding locks. Use database time consistently and monitor the age of the oldest overdue hold. An expired timestamp alone does not return stock until the release transaction commits. This can temporarily reduce availability but does not oversell. For higher throughput, allocate disjoint stock budgets to regional partitions; each region may sell only its assigned budget. Rebalancing requires durable ownership transfer and fencing. This trades global utilization for local latency.

A relational transaction is usually simpler than distributed locks or an eventually consistent counter. A strongly consistent key-value store with conditional writes can also work, but multi-item transactions and secondary queries require careful evaluation. Queue-based serialization reduces contention for a hot SKU at the cost of waiting latency and queue recovery complexity. Choose based on measured lock waits, burst duration and business tolerance for rejected checkouts.

8. Security, observability and testing

Enforce tenant ownership, positive bounded quantities, authenticated service callbacks and per-customer hold limits to prevent stock hoarding. Record audit events without payment secrets. Measure reservation latency, insufficient-stock responses, lock wait, expired-hold age, outbox lag and reconciliation discrepancies. Alert on negative quantities or a mismatch between reserved stock and active holds. Use a consistent snapshot for reconciliation so concurrent transactions do not produce false alarms.

Test 100 concurrent buyers against stock of 10 and assert exactly 10 successful one-unit holds. Replay the same idempotency key concurrently and assert one stock movement. Race confirmation against expiry at the deadline and assert exactly one terminal transition. Kill a worker before and after commit; verify recovery does not release twice. Pause the broker and confirm reservations remain durable. Load-test a single popular SKU separately from uniform traffic. Contract tests should cover conflict responses, ownership checks and repeated terminal operations.

9. Interview questions and answers

Why not read stock and then decrement it?

Concurrent readers can observe the same stock. A conditional update or row lock makes the decision atomic.

Can Redis be the source of truth?

Only if its durability, failover and consistency guarantees meet the inventory invariant. A cache alone is insufficient; a transactional database is a simpler starting point.

How do you handle a late payment?

Check the authoritative reservation state. If expired, compensate through refund or void, or create a new hold under explicit policy.

How do you reserve multiple SKUs?

Use one transaction with deterministic lock order on a single database. Across shards use coordinated transactions or a saga with explicit partial-hold semantics.

How do you scale a single viral SKU?

Limit admission, shorten transactions and consider disjoint inventory budgets. Hash sharding alone cannot distribute one authoritative stock row.

Conclusion

Start with correctness: atomic stock movements, durable holds, idempotency and explicit terminal states. Add queues, caches and regional partitions only when their benefits justify their consistency costs. In an interview, explain the last-unit race first, then show how payment and expiry compete and how recovery preserves the invariant. Further reading: PostgreSQL transaction isolation and explicit locking. Related: distributed job scheduler.

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *