Architecture

10 min read

November 22, 2026

Inventory reservations that survive retries

How to stop oversells and duplicate orders when every layer retries: reservation rows with expiry, row locks, idempotency keys and the transactional outbox, with PostgreSQL examples.

By Parth Patel

Two customers buy the last unit of a product at the same moment, and both receive an order confirmation. A payment provider retries a webhook after a timeout, and a customer is charged once but receives two orders. A queue redelivers a message, and stock is decremented twice.

None of these are exotic bugs. They are the normal behavior of distributed systems: networks time out, providers retry, queues deliver at least once, and users double-click. Correctness comes from designing every step so that repeating it is safe and racing it is impossible. This guide shows one pattern that holds up well in commerce backends, with PostgreSQL examples.

Where duplicates come from

Before fixing anything, it helps to name the sources:

  • Client retries. A checkout request times out on a flaky mobile connection; the app or the user retries. The first request may have succeeded.
  • Webhook redelivery. Payment providers retry until they receive a success response, and sometimes even after.
  • At-least-once queues. SQS, Service Bus, Kafka consumers and most job runners can deliver the same message more than once.
  • Unknown outcomes. When a call to a provider times out, you don't know whether it happened. Retrying blindly creates duplicates; not retrying loses work.

The defense has five layers: idempotency keys at the edge, reservations instead of decrements, expiry, idempotent payment handling, and reliable event publishing.

Layer 1: idempotency keys at the edge

Every write request carries a key that identifies the intent, generated by the client once per attempt at an action (not per HTTP request). The server stores the first result for each key and replays it for duplicates.

SQLSQL
CREATE TABLE idempotency_keys (
  tenant_id    uuid        NOT NULL,
  key          text        NOT NULL,
  request_hash text        NOT NULL,
  status       text        NOT NULL DEFAULT 'in_progress', -- in_progress | completed
  response     jsonb,
  created_at   timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, key)
);

The handler claims the key first, then does the work:

TypeScriptTypeScript
export async function withIdempotency<T>(
  db: Db,
  tenantId: string,
  key: string,
  requestHash: string,
  work: (tx: Tx) => Promise<T>,
): Promise<T> {
  return db.transaction(async (tx) => {
    const claimed = await tx.query(
      `INSERT INTO idempotency_keys (tenant_id, key, request_hash)
       VALUES ($1, $2, $3) ON CONFLICT DO NOTHING RETURNING key`,
      [tenantId, key, requestHash],
    );

    if (claimed.rowCount === 0) {
      const existing = await tx.one(
        `SELECT request_hash, status, response FROM idempotency_keys
         WHERE tenant_id = $1 AND key = $2 FOR UPDATE`,
        [tenantId, key],
      );
      if (existing.request_hash !== requestHash) throw new ConflictError("Key reused with a different request");
      if (existing.status === "completed") return existing.response as T; // replay
      throw new RetryLaterError("Original request still in progress");
    }

    const result = await work(tx);
    await tx.query(
      `UPDATE idempotency_keys SET status = 'completed', response = $3 WHERE tenant_id = $1 AND key = $2`,
      [tenantId, key, JSON.stringify(result)],
    );
    return result;
  });
}

Two details matter. The request hash catches clients that reuse a key for a different request, which is a bug worth surfacing. And the in-progress state means a duplicate that arrives while the original is still running gets a "retry later" instead of starting a second copy of the work.

Layer 2: reserve, don't decrement

The classic oversell happens when checkout reads the stock level, decides there is enough, and decrements it later. Between the read and the write, another checkout does the same thing.

Instead of decrementing stock at checkout, create a reservation with an expiry, and define availability as stock on hand minus active reservations:

SQLSQL
CREATE TABLE reservations (
  id         bigserial   PRIMARY KEY,
  tenant_id  uuid        NOT NULL,
  sku_id     uuid        NOT NULL,
  cart_id    uuid        NOT NULL,
  qty        int         NOT NULL CHECK (qty > 0),
  expires_at timestamptz NOT NULL,
  UNIQUE (cart_id, sku_id)
);

The reservation itself must make the check and the write atomic. Locking the SKU row serializes concurrent reservations for the same item, so the availability check can't interleave with another insert:

SQLSQL
-- Inside one transaction:
SELECT on_hand FROM inventory WHERE sku_id = $1 FOR UPDATE;

INSERT INTO reservations (tenant_id, sku_id, cart_id, qty, expires_at)
SELECT $4, $1, $2, $3, now() + interval '15 minutes'
WHERE (
  SELECT i.on_hand - COALESCE(SUM(r.qty), 0)
  FROM inventory i
  LEFT JOIN reservations r
    ON r.sku_id = i.sku_id AND r.expires_at > now()
  WHERE i.sku_id = $1
  GROUP BY i.on_hand
) >= $3
ON CONFLICT (cart_id, sku_id) DO NOTHING
RETURNING id;

No row returned means one of two things: not enough stock, or this cart already holds a reservation for this item. Both are safe outcomes, and the second makes the operation naturally idempotent for a retried request.

Layer 3: let reservations expire

Abandoned carts must not hold stock forever. Because availability already ignores expired rows, expiry is mostly automatic. A periodic job only needs to delete old rows to keep the table small:

SQLSQL
DELETE FROM reservations WHERE expires_at < now() - interval '1 hour';

The expiry window is a product decision, not just a technical one. Fifteen minutes suits most checkouts; limited-edition drops often use five, with a visible countdown so customers know the clock is running.

Layer 4: commit on payment, exactly once

When the payment provider confirms a payment, three things must happen together: the order becomes paid, the reservation becomes a permanent stock movement, and downstream systems are told. The webhook can arrive twice, so record each provider event before acting on it:

SQLSQL
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)
);

In one transaction: insert the event ID (stop if it already exists), mark the order paid, convert the reservation (decrement on-hand stock, delete the reservation), and write an outbox row. If any step fails, nothing is committed, and the provider's retry will try again cleanly.

Always verify the webhook signature before any of this, and treat the provider as the source of truth for money. If your records and the provider's ever disagree, a nightly reconciliation job should find it before your finance team does.

Layer 5: publish events reliably

Fulfillment, email and analytics need to know an order was paid. Publishing a message right after the commit looks fine until the process crashes between the commit and the publish, and the event is lost. Publishing before the commit is worse: the event goes out for a transaction that might roll back.

The transactional outbox solves this. The event is written to an outbox table in the same transaction as the state change, and a separate relay publishes outbox rows to your broker, marking them as sent:

SQLSQL
INSERT INTO outbox (aggregate_id, type, payload)
VALUES ($1, 'OrderPaid', jsonb_build_object('orderId', $1, 'tenantId', $2));

The relay itself delivers at least once, so consumers must also be idempotent: record the event ID they've processed, exactly like the webhook handler above. Idempotency is not a feature of one service. It is a property every step has to provide.

Testing the guarantees

These properties are easy to break with an innocent refactor, so check them deliberately:

  • Fire 50 concurrent checkouts for an item with 3 units in stock. Exactly 3 must succeed.
  • Replay every webhook in your test suite twice. Order counts and stock levels must not change on the second pass.
  • Kill the relay mid-batch and restart it. Every event must arrive at least once, and consumers must end up in the same state.
  • Run reconciliation against a deliberately corrupted record and confirm it is flagged.

Trade-offs to know about

Row locks on a single SKU serialize every checkout for that item. For normal catalogs that's invisible; for a flash sale on one product with thousands of buyers per second it becomes the bottleneck. Options at that scale include splitting stock into several buckets that are locked independently, or holding a short-lived counter in Redis for the sale and reconciling with the database afterward. Both add complexity, so reach for them when measurements show the lock is the constraint, not before.

Checklist

  • Every write endpoint accepts an idempotency key and replays stored results
  • Checkout creates reservations with an expiry; it never decrements stock directly
  • The reservation check and insert happen atomically under a row lock
  • Payment webhooks are signature-verified and recorded by event ID before processing
  • Paid status, stock movement and the outbox row commit in one transaction
  • Consumers record processed event IDs and ignore duplicates
  • Concurrency and replay checks run before every release
  • A reconciliation job compares your records with the payment provider's

Retries and races are not edge cases in distributed systems. They are the normal case. Designing for them from the first version costs a few tables and a little discipline, which is far less than refunding a sold-out drop.

Next step

Working on something like this? Let’s talk it through.

Send a short brief. You’ll get a written reply from me within two business days — either a few clarifying questions, a suggested first step, or an honest “I’m not the right fit” with a pointer elsewhere.

Parth Patel

Senior full-stack engineer