Agent Wranglers

ECM-8Recommended

Reserve stock at checkout and release it on timeout

Reserve the items when checkout starts payment, with an expiry such as 15 minutes. Turn the reservation into an allocation when payment succeeds, and release it when it expires or payment fails.

How to do it

Reserving at "add to cart" locks stock for people who never buy. Reserving only after payment sells the last item to two people. Reserve when the buyer moves to pay, with the conditional update from Decrement stock in one conditional update. Store each reservation with its order and expiry time. A job runs every minute and releases expired reservations as movements. Make the expiry longer than the payment page's own timeout, so a slow 3-D Secure step does not lose the item. A payment that succeeds after its reservation was released takes stock again. If none is left, refund it at once and tell the buyer.

Examples

TypeScript example

const RESERVATION_MINUTES = 15;

export async function reserve(db: Db, orderId: string, variantId: string, quantity: number) {
  if (!(await takeStock(db, variantId, quantity))) throw new OutOfStock(variantId);
  await db.query(
    `INSERT INTO reservation (order_id, variant_id, quantity, expires_at)
     VALUES ($1, $2, $3, now() + make_interval(mins => $4))`,
    [orderId, variantId, quantity, RESERVATION_MINUTES],
  );
}

Python example

RESERVATION_MINUTES = 15

def release_expired(conn) -> int:
    rows = conn.execute(
        "DELETE FROM reservation WHERE expires_at < now() AND allocated_at IS NULL RETURNING variant_id, quantity"
    ).fetchall()
    for variant_id, quantity in rows:
        conn.execute("UPDATE stock SET available = available + %s WHERE variant_id = %s", (quantity, variant_id))
    return len(rows)

How to check

A test reserves the last item, waits past the expiry and runs the release job. The item is available again. A second test confirms payment after release with no stock left, and the order is refunded and cancelled automatically.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/ecommerce/stock-and-reservations/checkout-reservations">Agent Wranglers e-commerce and fulfilment playbook</a>. In code you write, add a comment next to it with the same link.