Two hands reaching from opposite sides for the last cardboard box on a warehouse shelf

Prevent Inventory Overselling: Reservations, Locks and Idempotency

•11 min read

When a store runs a promotion, checkout stops being just a form and turns into a concurrency problem. Two customers try to buy the last unit in the same second. A payment provider sends the same webhook twice. A browser submits the order again. Now you have sold stock you do not have. This guide shows how to prevent inventory overselling at the system level. It covers the data model, the SQL that makes reservations atomic, how holds expire, how to make payment confirmation idempotent, and the trade-offs between database locks, in-memory counters and queues.

For the business side of getting a store ready for a busy shopping day (getting found, taking orders online, getting paid), read our Small Business Saturday tech fixes for small stores. This article covers the engineering underneath.

Why overselling happens

The classic bug is read, then check, then write:

stock = SELECT available FROM inventory WHERE sku = 'MUG-01'
if stock >= qty:
    UPDATE inventory SET available = stock - qty WHERE sku = 'MUG-01'
    create_order()

Two requests both read 1, both pass the check and both write 0, so you get two orders for one mug. Nothing in this code stops that, and adding more servers makes it more likely. Overselling has other causes too:

  • Duplicate submissions: a double click, a mobile network retry, or a user who refreshes the payment page.
  • Repeated or out-of-order events: treat payment webhooks as at-least-once. Design as if any event can arrive twice, or after a later one.
  • Several channels, several copies of stock: the web store, a marketplace, a point of sale and a distributor portal each lower their own counter.
  • Stale caches: a product page cached as "in stock" accepts orders the database can no longer honor.

A data model that prevents inventory overselling

Store what is physically on hand separately from what is promised to carts in progress. Availability is on_hand - reserved. Then let the database enforce the invariant, so a bug fails loudly instead of quietly overselling.

CREATE TABLE inventory (
  sku       text PRIMARY KEY,
  on_hand   integer NOT NULL CHECK (on_hand >= 0),
  reserved  integer NOT NULL DEFAULT 0 CHECK (reserved >= 0),
  CHECK (reserved <= on_hand)
);

CREATE TABLE reservations (
  id          uuid PRIMARY KEY,
  checkout_id uuid NOT NULL,
  sku         text NOT NULL REFERENCES inventory(sku),
  qty         integer NOT NULL CHECK (qty > 0),
  status      text NOT NULL CHECK (status IN ('held','committed','released')),
  expires_at  timestamptz NOT NULL,
  UNIQUE (checkout_id, sku)
);
CREATE INDEX reservations_expiry ON reservations (status, expires_at);

CREATE TABLE processed_events (
  provider     text NOT NULL,
  event_id     text NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_id)
);

The CHECK (reserved <= on_hand) constraint is your last line of defense. Even a code path you forgot about cannot commit more promises than stock. The transaction fails instead. The UNIQUE (checkout_id, sku) constraint makes reservation retries safe, and processed_events deduplicates webhooks.

A common variant adds an append-only inventory_movements ledger (receipts, sales, returns, adjustments) for auditing, and keeps the counter row for the hot path. The ledger tells you why stock changed. The counter answers "can I sell this?" quickly. If you keep both, update them in the same transaction.

Option 1: an atomic conditional update

For a single item, the simplest correct approach is one statement that checks and writes at the same time:

UPDATE inventory
SET reserved = reserved + $2
WHERE sku = $1
  AND on_hand - reserved >= $2
RETURNING on_hand - reserved AS available_after;

If it returns zero rows, there was not enough stock. No separate read can go stale. In PostgreSQL, row-level locks block other writers to the same row, so a concurrent request for the same SKU waits for the first one, and its guard is then checked against the updated row.

  • Pros: one round trip, no extra infrastructure, and correctness lives in one place.
  • Cons: every buyer of a popular SKU queues on the same row, and a cart with many lines needs more care (next section).

Option 2: lock the rows for multi-line carts

A cart with five products should reserve all of them or none. Do it in one transaction. Lock rows in a consistent order (for example, sorted by SKU), so two carts with the same products cannot deadlock each other. Insert the reservation first, so a retried request does not add stock to reserved twice:

function reserveCart(checkoutId, lines, ttl):
  lines = sortBy(lines, "sku")            // consistent lock order
  begin transaction
    for line in lines:
      inserted = INSERT INTO reservations
                   (id, checkout_id, sku, qty, status, expires_at)
                 VALUES (uuid(), checkoutId, line.sku, line.qty,
                         'held', now() + ttl)
                 ON CONFLICT (checkout_id, sku) DO NOTHING
                 RETURNING id
      if inserted is empty:
        continue                          // retry: already reserved
      rows = UPDATE inventory SET reserved = reserved + line.qty
             WHERE sku = line.sku AND on_hand - reserved >= line.qty
      if rows == 0:
        rollback
        return OutOfStock(line.sku)
  commit
  return Reserved(checkoutId)

If you need to read several rows before deciding, for example to apply bundle rules, use SELECT ... FROM inventory WHERE sku = ANY($1) ORDER BY sku FOR UPDATE and run your logic before you write. Never call a payment API, a shipping quote or any other network service while you hold these locks. Keep transactions in the millisecond range and do slow work outside them.

Option 3: in-memory counters or a queue per SKU

Teams that expect heavy contention on a few items often move the hot counter out of the relational database:

  • Atomic counter in an in-memory store (for example, a Redis Lua script that checks and decrements in one step). It is very fast, but now you have two sources of truth. You need a plan for restarts and persistence, a reconciliation job against the database, and a rule for which one wins when they disagree.
  • A queue partitioned by SKU, where one consumer per partition applies reservations in order. Correctness becomes easy to reason about because there is a single writer, but checkout becomes asynchronous and you take on queue infrastructure and its monitoring.

A practical rule: start with Options 1 and 2 in the database you already run. Move to Option 3 only when measurements show row contention on specific SKUs, and keep the database constraint even then.

Reservation lifecycle: hold, commit, release

A reservation is a promise with a deadline. Create it when the customer enters payment, not when they add to cart, or abandoned carts will lock up your stock. Commit it when payment is confirmed. Release it when it expires or the checkout is canceled. Choose a TTL longer than your real payment flow, including bank authentication steps and redirects, and measure that flow in your own logs instead of guessing.

A background job releases expired holds. FOR UPDATE SKIP LOCKED lets several workers run without blocking each other or touching rows a checkout is committing right now:

WITH expired AS (
  SELECT id FROM reservations
  WHERE status = 'held' AND expires_at < now()
  ORDER BY expires_at
  LIMIT 500
  FOR UPDATE SKIP LOCKED
), released AS (
  UPDATE reservations r SET status = 'released'
  FROM expired e WHERE r.id = e.id
  RETURNING r.sku, r.qty
)
UPDATE inventory i
SET reserved = i.reserved - s.qty
FROM (SELECT sku, sum(qty) AS qty FROM released GROUP BY sku) s
WHERE i.sku = s.sku;

Idempotent payment confirmation

Payments touch inventory in two directions, and each one needs its own protection.

Outgoing: idempotency keys to the provider

When your server creates a charge or payment intent, send an idempotency key derived from the checkout attempt, not from the customer. According to Stripe's idempotent requests reference, Stripe saves the status code and body of the first request for a key, whether it succeeds or fails, and later requests with the same key return the same result, including 500 errors. Keys can be up to 255 characters. If parameters fail validation or the request conflicts with one that is running at the same time, no result is saved and you can retry. If a key is reused after Stripe has pruned it, Stripe treats it as a new request. In practice: retry network failures with the same key, and generate a new key only for a genuinely new attempt, such as the customer switching cards.

Incoming: deduplicate webhooks in the same transaction

function onPaymentSucceeded(event):
  begin transaction
    first = INSERT INTO processed_events (provider, event_id)
            VALUES ('stripe', event.id)
            ON CONFLICT DO NOTHING RETURNING event_id
    if first is empty:
      commit; return 200                  // already handled
    lines = UPDATE reservations SET status = 'committed'
            WHERE checkout_id = event.checkoutId AND status = 'held'
            RETURNING sku, qty
    if lines is empty:
      handleLatePayment(event)            // hold expired or released
    else:
      for l in lines:
        UPDATE inventory SET on_hand = on_hand - l.qty,
                             reserved = reserved - l.qty
        WHERE sku = l.sku
      insert order row
      insert outbox row (email, ERP, shipping)
  commit
  return 200

The outbox row is sent by a separate worker after the commit, so a slow email or ERP call never holds inventory locks and never runs for a transaction that rolled back. The late-payment branch matters. If the hold expired before the money arrived, try to reserve again. If stock is gone, flag the order for a refund or a backorder decision. Never commit stock you do not have just because the payment succeeded.

Performance on hot SKUs

  • Keep the locked section tiny: validation, pricing and fraud checks happen before the transaction. Only the reservation writes happen inside it.
  • Split very hot stock into buckets: store (sku, bucket) rows and pick a random bucket that has stock. Contention drops, but the last units become harder to find, so fall back to scanning all buckets when the first try fails.
  • Index the expiry query so the release job stays cheap as reservations pile up.
  • Load test the invariant, not just throughput: fire many concurrent buyers at one SKU with a small stock and assert that committed quantity never exceeds on_hand.

Direct-selling companies hit exactly this pattern when a product launch is announced to the whole distributor network at once, often with stock split by warehouse or country. An e-commerce and order platform for network marketing companies needs these reservation rules built into its order engine, not bolted on later. If your current stack cannot express them, a custom order and inventory service next to your store is often less risky than a full rewrite.

Checklist

  1. Availability is on_hand - reserved, with a database CHECK that rejects overselling.
  2. Reservation is a single conditional update, or locked rows in sorted order for carts.
  3. Reservations are unique per checkout and SKU, so retries are harmless.
  4. Holds start at payment, carry a measured TTL and are released by a SKIP LOCKED job.
  5. Outgoing payment calls use idempotency keys tied to the checkout attempt.
  6. Webhooks are deduplicated by event ID in the same transaction that commits stock.
  7. Side effects go through an outbox, never inside the lock.
  8. Late payments have an explicit policy: re-reserve, refund or backorder.
  9. One source of truth for stock across all channels, or a documented reconciliation job.
  10. A concurrency test proves the invariant under load.

Common mistakes

  • Checking stock in application code and writing it in a separate statement.
  • Reserving at add-to-cart, which lets abandoned carts block real buyers.
  • Calling the payment provider inside a database transaction that holds row locks.
  • Generating a new idempotency key on every retry, which defeats the purpose.
  • Marking a webhook as processed in one transaction and committing stock in another.
  • Trusting a cached "in stock" flag at the moment of purchase.

Frequently asked questions

Should I use optimistic or pessimistic locking to prevent overselling?

For a single SKU, an atomic conditional update is simpler than either one and is enough. For multi-line carts or logic that must read before it writes, pessimistic row locks in a consistent order are easier to get right than optimistic version checks with retry loops.

Is Redis enough on its own for inventory?

It can enforce an atomic counter, but it becomes a second source of truth next to your orders database. If you use it, keep the database constraint and run a reconciliation job that defines which system wins.

What happens if payment succeeds after the reservation expired?

Try to reserve the stock again inside the webhook transaction. If it is no longer available, record the order in a state that triggers a refund or a backorder decision, and never commit stock that is not there.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

It is never published.