Designing a Shopping Cart: Price Snapshots, Merge, and No Inventory Hold
Adding a shirt to a cart is not booking a seat. The cart is a small document keyed by a person, written often, read by that person, and thrown away at checkout. Treating it like inventory is how you hold stock for someone who will never come back. The hold belongs later, and it has a deadline.
The document, not the warehouse
A line is a SKU, a quantity, a currency, and the unit price at add time. That price is a snapshot, not a promise. Inventory is not on the line. Availability next to the button is a stale-ok read of the inventory service.
The cart is one partition: user id, or an anonymous cart id, as the key. Two tabs adding the same SKU should land on one line. The write is "set this SKU's quantity," or "add delta," applied in the cart service so a double-click does not depend on the client counting.
CREATE TABLE carts (
cart_id UUID PRIMARY KEY,
user_id UUID NULL,
currency CHAR(3) NOT NULL,
merged_from UUID NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE cart_lines (
cart_id UUID NOT NULL REFERENCES carts(cart_id),
sku TEXT NOT NULL,
qty INT NOT NULL CHECK (qty > 0),
unit_price BIGINT NOT NULL, -- minor units at add time
currency CHAR(3) NOT NULL,
PRIMARY KEY (cart_id, sku)
);
Store money in minor units. A float on the line is how $19.99 becomes $19.989999 on the receipt. Currency on both cart and line lets you reject a SKU priced in a different currency instead of silently converting.
The interesting write is a merge of two lines for the same SKU, not a new row per click:
INSERT INTO cart_lines (cart_id, sku, qty, unit_price, currency)
VALUES (:cart, :sku, :qty, :price, :ccy)
ON CONFLICT (cart_id, sku) DO UPDATE
SET qty = LEAST(cart_lines.qty + EXCLUDED.qty, :max_qty),
unit_price = EXCLUDED.unit_price, -- latest add wins the snapshot
currency = EXCLUDED.currency;
Cap quantity in the same statement. Pair the HTTP call with an idempotency key when the client might retry the whole request.
Login merge is the bug that doubles the basket
Before login the cart id is a random value in a cookie, not a sequence. A sequence is guessable, and a guessable cart id is someone else's basket.
On login, merge once. Same SKU: add the quantities, cap at whatever maximum you sell. Then reprice. The merge itself has to be idempotent. A login callback that runs twice, or a user with two devices, must not double the quantities a second time. Record that this anonymous cart id has already been merged into this user, and make the second attempt a no-op that returns the current cart.
async function mergeOnLogin(userId: string, anonymousCartId: string) {
return db.transaction(async (tx) => {
const already = await tx.oneOrNone(
`SELECT cart_id FROM carts
WHERE user_id = $1 AND merged_from = $2`,
[userId, anonymousCartId],
);
if (already) {
return loadCart(tx, already.cart_id);
}
const userCart = await getOrCreateUserCart(tx, userId);
const guest = await loadCart(tx, anonymousCartId);
if (!guest) return userCart;
for (const line of guest.lines) {
await tx.none(
`INSERT INTO cart_lines (cart_id, sku, qty, unit_price, currency)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (cart_id, sku) DO UPDATE
SET qty = LEAST(cart_lines.qty + EXCLUDED.qty, $6)`,
[userCart.id, line.sku, line.qty, line.unit_price, line.currency, MAX_QTY],
);
}
await tx.none(
`UPDATE carts SET merged_from = $1, user_id = $2 WHERE cart_id = $3`,
[anonymousCartId, userId, userCart.id],
);
await tx.none(`DELETE FROM cart_lines WHERE cart_id = $1`, [anonymousCartId]);
return loadCart(tx, userCart.id);
});
}
The merged_from check is the lock. Unique on (user_id, merged_from) if you expect two login callbacks in flight. Without it, both transactions load an unmerged guest cart and you get 2x qty.
Conflicting currencies on merge should fail the guest lines, not convert them.
Anonymous carts expire. A week is plenty. A logged-in cart can live until checkout or until the snapshot is too old to show without a reprice.
Reprice in front of the user, not in the charge
Charging the snapshot from three weeks ago is wrong when the price went up, and charging a new price with no notice is wrong when it went up too. At checkout, read the current price, compare it to the snapshot, and if the policy says the difference matters, stop and show it. The user confirms. Then you create the order.
function priceDelta(snapshot: number, current: number) {
return { snapshot, current, changed: snapshot !== current };
}
async function beginCheckout(cartId: string) {
const cart = await loadCart(cartId);
const catalog = await prices.current(cart.lines.map((l) => l.sku));
const diffs = cart.lines
.map((l) => ({ sku: l.sku, ...priceDelta(l.unit_price, catalog[l.sku]) }))
.filter((d) => d.changed);
if (diffs.length) {
return { status: "needs-confirm", diffs };
}
return createOrderFromCart(cart);
}
How large a delta matters is a product call. Do not hide a jump inside a 200 from the charge API. The user confirmed the snapshot.
That confirm is the moment a hold might start, if the product needs one. The hold has a TTL measured in minutes, and it returns stock if payment does not finish. How that hold survives contention is the problem in booking inventory. The cart does not start the hold on add-to-cart. Abandoned carts would pin the warehouse.
The order created from the cart is a write the client will retry. Give that POST an idempotency key so a timed-out checkout does not create two orders. The money side of that order is a ledger, covered in double-entry payments. The cart row can be deleted, or marked checked out, in the same step that accepts the key. A retry returns the original order.
When this is the wrong cart
Flash drops, concert seats, and limited drops are not this document. If selling the item twice is the unforgivable outcome, you need a hold at selection time, with a TTL, the way a ticketing system does. A grocery cart of cereal boxes is the opposite: overselling a box is a substitution, not a lawsuit, and holding every abandoned basket overnight is how you show "out of stock" on a full warehouse.
Do not put tax or shipping into the line snapshot unless those numbers are what you will charge without a later quote. Both depend on the address typed at checkout. A snapshot of subtotal at add detects catalog drift. A snapshot of order total is a lie the moment they change the postcode.
Things that break in production
- Two devices, same user, both holding an anonymous cookie. Merge both, in order, each recorded in
merged_from. The second merge of an already-used id is a no-op. - SKU replaced by a successor. Keep the original SKU on the line and fail checkout with "no longer sold" rather than silently swapping.
- Partial checkout: payment authorized, order write failed, cart still full. The idempotency key on create-order is what makes the retry safe. Clearing the cart before the order commits is how you lose the basket and still charge.
- Promo codes applied on the cart and again on the order. Apply them once, on the quote that the user confirms.
Checkout is the expensive moment. Until then the cart is a sticky note. Keep it that cheap.
Keep reading
FOR UPDATE: No Row, No Lock
SELECT … FOR UPDATE locks tuples that exist. An empty scan is not a lock on the key. Two sessions both insert; a unique violation is the lucky case.
SKIP LOCKED: Due Jobs, Empty Batch
SKIP LOCKED does not mean the next free job. It skips rows that currently have a conflicting lock. A forgotten transaction can make a full queue claim nothing until that session ends.
OFFSET Pagination: Page Two Skipped a Row
OFFSET counts rows from a moving table. An insert or delete between pages skips or duplicates. Keyset on a unique sort key is the stable window.
Transactional Inbox: The Handler That Ran Twice
Outbox makes the event exist. It does not make the consumer run once. Record the message id in the same transaction as the side effect, or a retry will do the work again.
Two-Phase Commit: Why Distributed Transactions Stall
Two-phase commit makes two resources atomic until the coordinator dies. Here is why it blocks, why 3PC did not save it, and what you run instead.
Write Skew: The Anomaly Snapshot Isolation Does Not Catch
Two transactions each read what the other writes, both commit, and an invariant dies. Snapshot isolation allows write skew — here is how to close the hole.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.