Own-store architecture, part 2: Stock reservations and payments in first production
On this page
For first production, use product, order, inventory, payment, and fulfillment modules in one application with PostgreSQL as the primary database. Background workers call the payment provider, expire holds, reconcile payments, and send notifications. The fictional order 9001 contains one TOTE-NVY for 18,000 KRW. The database owns stock and the payment provider confirms approvals.
Expand the schema first
| Addition | Constraint and responsibility |
|---|---|
| Stock holds | inventory.reserved ranges from zero to on_hand. This sales balance excludes units committed on payment capture, even if they are awaiting shipment. stock_hold has one row per order and SKU, with a quantity and expiry. |
| Checkout requests and payment attempts | checkout_request has a unique customer and request-key pair. It stores the request hash and order ID. payment_attempt has an order FK, unique operation key, amount and currency, and a unique provider account and payment ID pair. |
| Webhooks, shipments and refunds | webhook_inbox has a unique provider account and event ID pair. shipment has an order FK and its own status. refund has a payment FK, positive amount, unique refund operation key, and unique provider account and refund ID pair. |
| Outbox and audit | Here outbox permits one row per order and event type. The operator audit log records the actor, target, time, and reason. |
Track pending, reserved, confirmed, and cancelled orders separately from requested, unknown, successful, and failed payment attempts. Shipments have preparing and dispatched states. Refunds have accepted, pending, unknown, completed, and failed states. In production, finalize prices and lines before committing the order and request key together. Return the existing order for the same customer, key, and request hash. Reject a changed hash as a conflict. Treat lines submitted for reservation as immutable.
Hold stock in a short transaction
Run the reservation DDL and example call in the PostgreSQL 17 test database after part 1. The input is order ID 9001. Lock the order first, then lock each SKU in ascending order of immutable numeric ID. Keep that order during expiry, consumption, and cancellation. The diagram shows the first reservation of a pending order.
ALTER TABLE inventory ADD COLUMN reserved integer NOT NULL DEFAULT 0
CHECK (reserved BETWEEN 0 AND on_hand);
CREATE TABLE stock_hold (
order_id bigint NOT NULL REFERENCES shop_order(id),
sku_id bigint NOT NULL REFERENCES inventory(sku_id),
quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 99),
expires_at timestamptz NOT NULL,
status text NOT NULL CHECK (status IN ('active', 'consumed', 'released')),
PRIMARY KEY (order_id, sku_id)
);
CREATE TABLE outbox (
order_id bigint NOT NULL REFERENCES shop_order(id),
event_type text NOT NULL,
dispatched_at timestamptz,
PRIMARY KEY (order_id, event_type)
);
CREATE FUNCTION reserve_order(p_order_id bigint) RETURNS text
LANGUAGE plpgsql AS $$
DECLARE
current_status text;
item record;
deadline timestamptz := statement_timestamp() + interval '15 minutes';
BEGIN
SELECT status INTO current_status FROM shop_order
WHERE id = p_order_id FOR UPDATE;
IF current_status = 'reserved' THEN
RETURN current_status;
END IF;
IF current_status IS DISTINCT FROM 'pending' OR NOT EXISTS (
SELECT 1 FROM order_item WHERE order_id = p_order_id
) THEN
RAISE EXCEPTION 'order_not_reservable';
END IF;
FOR item IN
SELECT sku_id, quantity FROM order_item
WHERE order_id = p_order_id ORDER BY sku_id
LOOP
UPDATE inventory SET reserved = reserved + item.quantity
WHERE sku_id = item.sku_id AND on_hand - reserved >= item.quantity;
IF NOT FOUND THEN
RAISE EXCEPTION 'insufficient_stock for SKU %', item.sku_id;
END IF;
INSERT INTO stock_hold VALUES
(p_order_id, item.sku_id, item.quantity, deadline, 'active');
END LOOP;
UPDATE shop_order SET status = 'reserved' WHERE id = p_order_id;
INSERT INTO outbox (order_id, event_type) VALUES (p_order_id, 'stock_reserved');
RETURN 'reserved';
END $$;
BEGIN;
SELECT reserve_order(9001);
COMMIT;
Expect reserved and one unit held for SKU 101. The hold and its outbox event commit together. A repeated call on a reserved order returns its existing state. A missing or ineligible order raises order_not_reservable. A stock shortage raises insufficient_stock and rolls back even the changes to earlier SKUs. The sample hold lasts 15 minutes. Set short lock and statement timeouts in production, and have the worker recheck the deadline. Local PostgreSQL 17.12 confirmed the successful call, repeated call, two-session race for the last unit, and full rollback when the second SKU ran short.
Connect payment and fulfillment
A worker reads the outbox after commit. It locks the order to check that the hold is valid and inspect payment state. Skip an already successful payment. Resume or reconcile an in-flight or unknown attempt instead of creating another. Make that decision and persist any new attempt in the same transaction that locks the order. Derive the charge amount from the order snapshot. First it records the payment attempt and a stable provider idempotency key in a short transaction. It calls the provider outside the DB transaction and saves the outcome in a separate transaction. A crash after sending can be retried with the same operation ID. Consumers check state and identifiers to avoid repeating a business effect when an event arrives again. Treat a timeout as unknown and reconcile the original operation. Once the provider’s key expires, a blind retry could charge again.
Verify the raw webhook body, signature, and permitted account and environment. Persist the event ID durably before acknowledging. Match the order, payment ID, amount, and currency. Use the saved state or query the provider when delivery is duplicated or out of order. Treat the browser success page as a user interface. Stripe illustrates the provider-specific key and signature contracts.
Expiry and payment confirmation lock the same order to settle a race. A confirmed capture with a valid hold reduces both reserved and on_hand by the held quantity and consumes the hold. Commit these changes with order confirmation, then permit shipment. Expiry releases only the reservation. If payment confirmation arrives after release, block shipment and reconcile. Use a stable operation ID to void an uncaptured authorization or refund a capture. For a partial refund, lock the payment row and require completed, pending, and unknown refund amounts plus the new amount ≤ captured amount before saving the new operation. If the response is lost, look up that refund before creating another.
Deployment sequence
Deploy the new tables and constraints, then connect workers and a signature-verifying receiver in a test environment. Assign price and stock changes, shipping, and refund approvals to separate operator roles, and enforce order access server-side. Keep order and refund audit trails. Restore a backup in isolation and record the recovery point and elapsed time. Rehearse last-unit contention, duplicate and unordered events, late approvals, and refund contention before opening to a small group of production orders. Only the reservation SQL was run here. Payment, webhooks, shipping, and recovery are design and prelaunch verification items.
Related articles
Official documentation
Previous — Own-store architecture, part 1: Prototype with one app and PostgreSQL
Next — Own-store architecture, part 3: Measure bottlenecks and scale with traffic
Discussion