TL;DR
- PostgreSQL inventory reservation can keep one row per sellable unit, letting concurrent checkouts lock different rows. Use
FOR UPDATE SKIP LOCKEDin a short transaction and roll back the whole hold if it cannot claim the requested quantity. - A short claim can mean stock is temporarily locked by another transaction. Treat it as a failed attempt under contention and use a bounded retry policy. Use separate logic for any definitive sold-out decision.
- Keep hold state and expiration in PostgreSQL. Checkout completion and the expiry worker must lock the same hold row before changing it. Redis can help display a countdown or wake a worker. A reconciliation query must still release expired holds after missed events.
Why flash sales stress a single stock row
At launch, many buyers request one of the same limited product. A checkout that separately reads a remaining quantity and later writes a decrement can race another checkout. PostgreSQL can safely decrement an inventory counter using an atomic UPDATE with a stock predicate. For a moderately contended SKU, this is often the simplest design. The throughput tradeoff is that concurrent checkouts wishing to update that SKU all need the same row lock.
Once the transaction includes cart updates, promotion validation, or a remote payment call, time spent holding that row can rise sharply. A row-per-unit model creates independently claimable items so concurrent workers can proceed on different rows. It also gives the platform a native object to reserve, expire, or mark sold. It creates more rows and index churn, which is a poor bargain for very large fungible inventories or a checkout that can safely reserve from one fast counter.
PostgreSQL documents SKIP LOCKED as a way to avoid waiting on row locks in queue-like tables. Skipped rows mean the selection is not a consistent global stock view. Table-level locks and other dependencies can still block the transaction. Treat the pattern as a bounded queue claim rather than a mechanism for counting current inventory. PostgreSQL locking clause.
Represent inventory, the hold, and the purchase separately
Inventory units can be available, held, or sold. The hold record supplies a buyer, request key, SKU, quantity, and expiration time. It also gives confirmation and expiration workers one row they can both lock, so the hold has one state transition at a time. Keep a payment or order reference on the hold or in a separate table with a uniqueness rule. Separate physical fulfillment, refunds, and restocking from this initial claim model. A refund may require an inventory inspection before a unit becomes sellable again.
Store a server-generated hold ID and one durable idempotency key per buyer operation. When a client retries after a timeout, use that key to return the existing record. Compare the original operation details to distinguish a legitimate replay from key reuse for different units. Authorization also matters here. The application must authenticate the buyer and scope operations to their hold before executing a claim or confirmation. A hold identifier can appear in logs and should not independently grant access.
Commerce systems often distinguish sellable, committed, and reserved quantities in their public APIs. Shopify’s documentation describes these inventory states and their API meanings. The following design is an independent PostgreSQL example. Public commerce APIs describe platform behavior without exposing private storage implementation. Shopify inventory states reference.
Implement atomic multi-unit claims in PostgreSQL
Define state constraints and targeted indexes
This example uses PostgreSQL 17 and a single SKU per hold. Limit where the function can be called and grant the actual checkout role only what its write path requires. The composite foreign key prevents a unit from belonging to a hold for a different SKU. The database checks field consistency inside each row. The transaction still needs to assert that the count of claimed or transitioned units equals the hold quantity.
CREATE TABLE inventory_hold (
hold_id uuid PRIMARY KEY,
customer_id uuid NOT NULL,
request_key text NOT NULL CHECK (length(request_key) BETWEEN 1 AND 128),
sku text NOT NULL,
quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 20),
status text NOT NULL CHECK (status IN ('held', 'sold', 'expired')),
expires_at timestamptz NOT NULL,
payment_ref text UNIQUE,
UNIQUE (customer_id, request_key),
UNIQUE (hold_id, sku),
CHECK ((status = 'sold') = (payment_ref IS NOT NULL))
);
CREATE TABLE inventory_unit (
unit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL,
status text NOT NULL DEFAULT 'available'
CHECK (status IN ('available', 'held', 'sold')),
hold_id uuid,
FOREIGN KEY (hold_id, sku) REFERENCES inventory_hold (hold_id, sku),
CHECK ((status = 'available') = (hold_id IS NULL))
);
CREATE INDEX inventory_available
ON inventory_unit (sku, unit_id) WHERE status = 'available';
CREATE INDEX inventory_hold_units
ON inventory_unit (hold_id) WHERE hold_id IS NOT NULL;
CREATE INDEX inventory_due
ON inventory_hold (expires_at, hold_id) WHERE status = 'held';
For an initial stock load, insert one unit per sellable item. Use an independently idempotent import from the inventory source in a real application. Make the quantity limit match the store’s checkout policy. Keep an equally explicit policy for holding multiple SKUs. A multi-SKU cart typically needs an all-or-none transaction and a consistent SKU order across writers to reduce deadlocks.
Claim units, or roll back the attempted hold
The function below assumes Read Committed isolation. The unique key lets concurrent retries of the same operation converge on one hold. A retry that waits for an existing request key to commit can see that hold in the following statement. The unit claim skips locks held by competing carts and locks whichever eligible rows remain. If fewer than requested are found, the exception rolls back the attempted hold and its partial assignments. The application should also roll back the surrounding transaction, classify the result, and retry only within its request budget. PostgreSQL Read Committed behavior.
CREATE FUNCTION reserve_inventory(
p_hold uuid, p_customer uuid, p_request text, p_sku text, p_quantity integer
) RETURNS uuid
LANGUAGE plpgsql
AS $$
DECLARE
new_hold_id uuid;
prior inventory_hold%ROWTYPE;
claimed_count integer;
BEGIN
INSERT INTO inventory_hold
(hold_id, customer_id, request_key, sku, quantity, status, expires_at)
VALUES (p_hold, p_customer, p_request, p_sku, p_quantity, 'held',
clock_timestamp() + interval '10 minutes')
ON CONFLICT (customer_id, request_key) DO NOTHING
RETURNING inventory_hold.hold_id INTO new_hold_id;
IF new_hold_id IS NULL THEN
SELECT h.* INTO STRICT prior
FROM inventory_hold AS h
WHERE h.customer_id = p_customer AND h.request_key = p_request;
IF prior.sku IS DISTINCT FROM p_sku
OR prior.quantity IS DISTINCT FROM p_quantity THEN
RAISE EXCEPTION 'request key belongs to different inventory details'
USING ERRCODE = '22023';
END IF;
RETURN prior.hold_id;
END IF;
WITH picked AS MATERIALIZED (
SELECT unit_id
FROM inventory_unit
WHERE sku = p_sku AND status = 'available'
ORDER BY unit_id
LIMIT p_quantity
FOR UPDATE SKIP LOCKED
)
UPDATE inventory_unit AS unit
SET status = 'held', hold_id = new_hold_id
FROM picked
WHERE unit.unit_id = picked.unit_id;
GET DIAGNOSTICS claimed_count = ROW_COUNT;
IF claimed_count <> p_quantity THEN
RAISE EXCEPTION 'inventory temporarily unavailable for requested quantity'
USING ERRCODE = 'P0001';
END IF;
RETURN new_hold_id;
END;
$$;
Call the function using bound parameters inside a short transaction, and return success only after commit. Read the existing hold’s stored status and expiration when replaying a request. A past hold should never silently create a fresh hold under the same key. If the client wants to make a new reservation after expiry, use a new operation and key. Choose an application-level machine code for claim shortfalls, since SQLSTATE P0001 is also the default for unrelated PL/pgSQL exceptions.
-- Set illustrative bounds for the reservation transaction.
BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL lock_timeout = '150ms';
SET LOCAL statement_timeout = '500ms';
-- Execute SELECT reserve_inventory($1, $2, $3, $4, $5) using the DB driver.
COMMIT;
Expire and finalize holds without reopening sold inventory
Run a periodic worker from PostgreSQL’s expiration timestamp. Select due holds ordered by expiration and lock them in short batches. Mark each hold expired and release its held units in the same transaction. Each completion path should acquire the hold row lock before updating units. The expiry statement below assumes the only unit writers implement these transitions. For environments with additional writers, validate per-hold release counts before committing and alert on inconsistencies.
WITH due AS MATERIALIZED (
SELECT hold_id
FROM inventory_hold
WHERE status = 'held' AND expires_at <= statement_timestamp()
ORDER BY expires_at, hold_id
LIMIT 200
FOR UPDATE SKIP LOCKED
), expired AS (
UPDATE inventory_hold AS hold
SET status = 'expired'
FROM due
WHERE hold.hold_id = due.hold_id
RETURNING hold.hold_id
)
UPDATE inventory_unit AS unit
SET status = 'available', hold_id = NULL
FROM expired
WHERE unit.hold_id = expired.hold_id AND unit.status = 'held';
For confirmation, get the hold row with SELECT ... FOR UPDATE using its ID and the expected buyer or order scope. After obtaining the lock, verify it is still held and the database clock is before expiration. Update the unit rows to sold, validate the affected count, and store the unique payment reference and sold state in the same transaction. A duplicate payment notification can return the existing successful outcome when its reference matches. If the hold already expired, preserve that state and reconcile the payment separately. Any provider-side authorization, void, capture, or refund must happen outside the database lock, using durable events and idempotent retries for the external workflow.
Redis TTL keys can cache the checkout countdown or hint that an expiry worker should run. Redis expiration notifications use Pub/Sub and can arrive later than the configured TTL. An offline subscriber misses events. A countdown key disappearing tells you nothing about whether the database has released those units. Periodic database reconciliation remains responsible for convergence. Redis keyspace notification delivery and timing.
Failure modes to exercise under concurrent load
Temporary lock contention looks like sold-out stock
Open a transaction that claims several units and leave it uncommitted while another checkout attempts a larger request. The second checkout may get a partial selection and must roll back. Release the first transaction and retry within the budget. A stock read separate from the claim can report a useful approximation for display, but it cannot guarantee availability for the next transaction.
Payment completes while expiry runs
Run both workers against one hold with a short expiry. Confirm that a sale records one payment reference and no sold units return to the available pool. If expiry wins and the external authorization already succeeded, the reconciliation worker must resolve that outcome using a durable event and provider idempotency. Test duplicated and out-of-order notifications as well as a worker crash between external calls and persistence.
Cleanup throughput cannot keep up
Measure active holds past expiration, the age of the oldest due hold, and records released per batch. A reported worker success only tells you the last run exited cleanly. Scale expiry workers, shorten transactions, and examine query plans while testing warmed and cold indexes. Track autovacuum and index churn because a flash sale repeatedly moves rows in and out of the available and expiry indexes. PostgreSQL index testing for production workloads.
Choose row-per-unit reservations when the workload fits
Atomic counters suit lower contention or many fungible items per SKU. Keep the predicate and decrement in one write, and pair a reservation ledger with it when holds and refunds need durable history. Row-per-unit locks suit limited batches and inventory that benefits from identifying each unit. Admission control or preallocated stock partitions can reduce pressure before checkout. Admission control trades immediate access for predictable capacity. Partitions introduce balancing and reconciliation work when purchase demand is uneven.
Benchmark with the actual quantity distribution, client retries, payment callback delays, and expiry batch sizes. Compare p95 claim latency, successful reservations, partial-claim rollbacks, and the age of the expiry backlog. Check invariants under the same load: no unit with two owners, every active hold connected to exactly its quantity, and the total unit count reconciled with available, held, and sold. A fast path that silently loses reservations is a correctness failure. Enforcing a different reservation invariant with PostgreSQL exclusion constraints · Keeping financial transitions balanced in PostgreSQL.
Frequently asked questions
Does SKIP LOCKED return every available inventory unit?
No. PostgreSQL skips candidate rows locked by another transaction. A result smaller than the requested quantity can indicate contention rather than a definitive stock count. Roll back partial claims, then follow a bounded retry or availability policy. Use a separate stock projection for presentation and revalidate on reservation.
Can a Redis TTL alone coordinate checkout reservation expiry?
A TTL can display a countdown or reduce the delay before cleanup. Use a PostgreSQL expiration timestamp as the authority when PostgreSQL owns the inventory. Run a reconciliation worker and use the hold row lock to coordinate release with confirmation. Redis notification delays or subscriber disconnects should not leave inventory stranded.
When should I keep an atomic inventory counter instead of one row per unit?
Keep a counter when contention is acceptable and units have no independent allocation, lifecycle, or traceability needs. The atomic update should include a stock predicate and run in a short transaction. If wait time becomes a bottleneck, compare row-per-unit locking or admission control against that simpler baseline.
Review your checkout reservation design
If you are planning a flash sale, talk to our engineering team about PostgreSQL inventory reservation, expiry recovery, or a concurrency test that fits your checkout volume.
