Video in progress
How do you design temporary stock reservation in a warehouse, and how are unpaid reservations released?
A reservation is a separate record: which order, how much, until when. Sellable stock = total − active reservations. A scheduler releases expired reservations, and if the payment goes through the reservation is confirmed. Every operation is idempotent by order ID.
📖 Answer
The simple solution is to decrease stock.quantity right away. It works, but when the payment fails or the customer abandons the cart, the logic to put it back gets scattered everywhere. A separate reservation table is clearer:
CREATE TABLE reservation (
order_id uuid,
sku text,
qty int NOT NULL,
status text NOT NULL, -- HELD, CONFIRMED, RELEASED
expires_at timestamptz NOT NULL,
PRIMARY KEY (order_id, sku)
);
To avoid overselling, the check and the write are atomic:
UPDATE stock SET reserved = reserved + :qty
WHERE sku = :sku AND on_hand - reserved >= :qty;
-- 0 rows => not enough stock
This UPDATE and inserting the reservation row are in one transaction. The PRIMARY KEY (order_id, sku) catches a repeated ReserveStock command (a retry, a duplicate message): the second one does nothing.
Releasing:
-- every minute; with SKIP LOCKED several pods can run it safely
SELECT order_id, sku, qty FROM reservation
WHERE status = 'HELD' AND expires_at < now()
LIMIT 500 FOR UPDATE SKIP LOCKED;
For each row, reserved is decreased, the status becomes RELEASED, and a ReservationExpired event goes out through the outbox, so the order service cancels the order.
The race: the payment goes through in the same second the reservation expires. Confirm works only if status = 'HELD'. If the reservation was already released, there are two ways out: reserve again if the stock is still there, or refund the money if it isn't. That is a business decision, so agree on it in advance.
The TTL value is the business's call too: 15 minutes for a card payment, 3 days for a bank transfer.
Sign up to mark studied questions and save your progress.