Loading
Code Deb

Concurrent E-Commerce: Discounts, SKUs and Stock Reservations

Design concurrent ecommerce checkout with atomic stock reservations, deterministic discounts, idempotent orders and reliable SKU identity across channels.

Two checkout paths converge on one remaining blue inventory unit.

Two successful checkouts can consume one remaining unit without the stock count ever becoming negative. That failure is harder to detect than a negative inventory balance because the final database value can look perfectly reasonable.

Enumerating every possible two-checkout schedule

We modeled two buyers, each with a read followed by a write, against one unit of stock. Respecting the order within each checkout produces exactly six interleavings. An unsafe implementation reads stock into a local variable, then writes that stale value minus one after accepting the order.

AlgorithmOverselling schedules
Separate read and stale write4 of 6
Atomic conditional decrement0 of 6

Four schedules accept both orders and leave stock at zero. For example, A reads 1, B reads 1, A writes 0 and B writes 0. An assertion that stock must be nonnegative misses this defect entirely. Our enumeration is exhaustive for this two-step model, not a PostgreSQL throughput benchmark.

Put the invariant in the database

-- PostgreSQL reference pattern; run in a transaction.
UPDATE inventory
SET available = available - $4
WHERE tenant_id = $1
  AND warehouse_id = $2 AND sku = $3
  AND available >= $4
RETURNING available;

Exactly one returned row means stock was decremented. Zero rows means the requested stock could not be allocated. The reservation record and idempotency result must be written in the same transaction; rolling back just one of those steps would introduce a different inconsistency. PostgreSQL's transaction isolation reference explains why Serializable transactions may require a whole-transaction retry. The Stock Reservations SDK deliberately requires an atomic adapter, rather than hiding a process-local mutex behind an API.

Expiring a hold races with confirming a payment

Model held, committed, released and expired as mutually exclusive states, with a version counter. A payment callback arriving after the hold was released must not be able to transition the old version to committed. Use compare-and-swap on tenant, reservation ID, status and version; a lost comparison triggers a fresh read and a reconciliation decision. Do not blindly retry a successful payment or invent available stock. See our replay and retry experiment.

A rounding bug can survive correct stock locking

A one-paisa discount split between two identical lines cannot be represented as half a paisa on either invoice line. Allocate the remainder deterministically, using stable line IDs as a tie-breaker. Record rule version and final line amounts. If a return uses the current promotion rather than the stored allocation, it can refund a different amount. Promotion Engine and our rounding comparison address that separate invariant.

Acceptance tests that catch the real failure

Test two requests for one unit, duplicate request keys, two warehouses, multi-line rollback, payment after expiry and repeated returns. Compare accepted order quantities against committed stock movements, not merely the final stock count. A practical concurrency test should run against the target database adapter, with independent connections and a barrier between steps. This article's six-schedule model motivates those tests; it does not certify a deployed POS or any payment provider. Read invoice sequencing before treating order and invoice creation as one operation.

Method and reproducibility: Controlled synthetic model. See Code Deb's recorded experiment results and reproduction script in the repository. Figures are reproducible from declared inputs, not undisclosed client outcomes. The cited external material is independent of Code Deb's experiment.

More from Code Deb

Read about our agency, explore available services, or contact the team for a project discussion.