Shopping Cart System Design: Guest Merges, Price Changes and Stock Holds
Saket Bhatnagar, Founder, SevyDevy, Last updated , 23 min read
Summary
- Shopping cart system design means storing each cart on the server and applying clear rules when things change. Guests get a random cart ID; logged-in shoppers use their user ID.
- On login, merge the guest cart into the account cart once. Merge means combining the two lists of items, and the merge must be safe to repeat if the login request is retried.
- A cart is not an order. The price in the cart is only a reminder of what the shopper saw, so you re-check the current price and stock before payment.
- A common design holds no stock at Add to cart. It holds stock for a few minutes at checkout with one atomic update, a single step that fully happens or not at all.
- Beginners can stop after the section on what the service looks like. Engineers get tested results next: a naive stock check that promised 10 units to 50 buyers, a retry-safe merge and a sweeper, a job that frees expired holds.
What goes wrong when a shopping cart is just a list in the browser?
Shopping cart system design fixes four quiet bugs. Carts vanish between phone and laptop, quantities double on login, prices change silently, and the last item sells twice. A list kept only in the browser causes all four.
Picture a common setup. A fashion store runs a festive sale. A shopper adds two kurtas at 899 rupees and the last red saree to the cart on a phone at lunch, without logging in. The setup is made up, but each problem in it happens in real stores.
That night the shopper opens a laptop and logs in. The account already holds one kurta from last week. The sale has ended, so the kurta now costs 949 rupees. Another shopper is looking at the same saree.
The store now has five decisions to make. It must pick the right kurta count, the price to charge and who gets the saree. It must also survive a login that runs twice, and decide whether to send a reminder. This guide settles each one with the same setup.
Which words do you need before designing a shopping cart?
You need seven words. Each comes with a plain meaning and its place in the running example.
- Cart: a saved, changeable list of things a shopper might buy. Example: two kurtas and one saree.
- Line item: one row in the cart, made of a product, a quantity and some notes. Example: kurta, size M, quantity 2.
- SKU (stock keeping unit): the code for one exact sellable thing, such as a kurta in size M. Example: KURTA-M.
- Guest cart: a cart made before login. The server keys it by a long random cart ID stored in a cookie, a small value the browser sends back with each request.
- Merge: combining the guest cart and the account cart into one when the shopper logs in.
- Hold (also called a reservation): a promise that a unit of stock is kept for one shopper for a short time. Example: the saree is kept for 15 minutes during checkout.
- TTL (time to live): how long something lasts before it expires. Holds and old carts both have one.
What is shopping cart system design?
Shopping cart system design is deciding where carts live, who owns them, and what happens when the shopper, the price or the stock changes. The hard part is not storing a list. It is the rules around that list.
A cart is long-lived, changeable state. It can sit for weeks, move between devices and outlive a sale. An order is the opposite: it is fixed the moment payment succeeds. Mixing the two causes many cart bugs.
| Question | Cart | Order |
|---|---|---|
| Can it change? | Yes, all the time | No, only through refunds or cancellations |
| What does its price mean? | What the shopper saw last time | What the shopper agreed to pay |
| Is stock taken? | Usually not, or only for minutes | Yes, the units are sold |
| How long does it live? | Days or weeks, then it is cleaned up | Years, for accounts and tax |
| What if it is lost? | Annoying, the shopper rebuilds it | Serious, money has moved |
Here is one picture to hold on to. A cart is like a supermarket trolley with your name tag on it. The items in it are a plan, the shelf labels are the prices, and the till is checkout.
Where the picture breaks: a real trolley takes the packet off the shelf, so nobody else can grab it. A digital cart does not do that. Another shopper can buy your saree unless you build a hold, which is a later section.
What does a shopping cart service look like?
A shopping cart service is a small backend service that owns the cart tables and calls other services for prices and stock. The browser or app only holds a cart ID, never the source of truth.
Parts of a shopping cart backend
Drag to exploreNotice that the cart service asks the price and inventory services every time. It never trusts a price stored in the cart or sent by the app.
Diagram connections:
- Shopper app or browser to API gateway (add, view, log in)
- API gateway to Login service (log in)
- Login service to Cart service (merge guest cart)
- API gateway to Cart service (cart calls)
- Cart service to Cart database (read and write)
- Cart service to Price service (current price)
- Cart service to Inventory service (hold at checkout)
- Cart service to Cart events queue (cart events)
- Cart events queue to Reminder and cleanup jobs (idle and expired carts)
- Reminder and cleanup jobs to Email and SMS sender (one reminder)
- Shopper app or browser: Holds only a cart ID cookie or login token
- API gateway: Routes cart, login and checkout calls
- Login service: Checks the user, then asks for a merge
- Cart service: Owns carts, line items and merge rules
- Cart database: Cart, line item and hold tables
- Price service: Current price, sale and coupon rules
- Inventory service: On-hand stock and short holds
- Cart events queue: Cart updated, checkout started, order paid
- Reminder and cleanup jobs: Idle-cart reminders, expiry, old-cart deletion
- Email and SMS sender: Sends at most one reminder per cart
Where a guest cart lives
Keep the guest cart on the server, keyed by a long random cart ID. Put only that ID in a cookie. A random ID matters because a guessable one, such as 1001, lets anyone read the next cart.
A cart kept only in the browser cannot follow the shopper to another device. It also cannot be merged on the server, reminded about or cleaned up, because the server never saw it.
How big the cart data gets
Carts are small, so size is rarely the problem. Suppose the store has 20 lakh (2 million) active carts at the sale peak, with 4 line items each. At about 150 bytes a line, that is 1.2 GB (all numbers made up).
Traffic is the bigger worry. If the peak is 5,000 cart writes a second and four reads per write, that is about 20,000 reads a second (made up). Almost every request touches one cart ID, so you can split carts across database servers by cart ID.
Beginners can stop here. You now know what a cart is, how it differs from an order, and which parts a cart backend needs. The next sections show the rules engineers get wrong, with tested code.
How do you merge a guest cart into an account cart on login?
Claim the guest cart in one atomic step, copy its lines into the account cart with a clear quantity rule, then mark the guest cart as merged. If the same login runs twice, the second run must find nothing to do.
The naive merge and why it fails
The first idea most people have is to add the quantities: 2 kurtas from the guest cart plus 1 from the account gives 3. That looks fair, but it has two problems.
First, the shopper probably added the same kurta twice on two devices and wants one or two, not three. Second, logins get retried. A slow network, a double tap or a client retry can run the merge again.
The answer is 5, not 3. We ran it: the first run gave 3 and the retried run gave 5, because the guest cart's 2 kurtas were added again. A merge that is not safe to repeat will sooner or later double someone's cart.
Choosing a quantity rule
There is no single correct rule. Pick one, write it down and test it. The table lists the common choices with the running example: guest cart has 2 kurtas, account cart has 1.
| Rule | Kurtas after merge | Good for | Risk |
|---|---|---|---|
| Add quantities | 3 | Stores where repeat buying is normal, like groceries | Doubles on retry unless the merge runs only once |
| Keep the higher quantity | 2 | Fashion and electronics, where duplicates are mistakes | A real wish for 3 is lost |
| Keep the account cart only | 1 | Simple stores | Throws away the guest's work |
| Keep the guest cart only | 2 | Stores where the latest session matters most | Throws away saved items |
| Ask the shopper | Shopper decides | Expensive items | Extra step at login |
Real platforms make this choice explicit. As of 31 October 2026, commercetools, a commerce platform, documents two sign-in modes. One merges the guest cart into the customer's active cart. The other makes the guest cart the new active cart.
In the merge mode, its docs say two identical line items are merged with the higher quantity retained. That matches the keep-the-higher-quantity row above.
A retry-safe merge, step by step
Guest-to-account merge on login
Drag to exploreNotice the decision box comes first. Claiming the guest cart with one conditional update is what makes a retried login harmless.
Diagram connections:
- Shopper logs in to Guest cart still active? (start merge)
- Guest cart still active? to Do nothing (No)
- Guest cart still active? to Copy lines across (Yes, claimed)
- Copy lines across to Apply limits
- Apply limits to Re-price and check stock
- Re-price and check stock to Show what changed
- Shopper logs in: Request carries the guest cart ID cookie
- Guest cart still active?: One UPDATE sets status to merged if still active
- Do nothing: A retry or second tab already merged it
- Copy lines across: Same item in both carts: keep the higher qty
- Apply limits: Cap at the per-item limit, here 5
- Re-price and check stock: Read current price and free stock
- Show what changed: Price moved, item sold out, quantity capped
The key move is the claim. One UPDATE changes the guest cart's status from active to merged, but only if it is still active. The database tells you how many rows changed, and zero means another request got there first.
Run the claim and the copy in one transaction, which means the database applies all of the steps or none of them. A crash halfway then leaves the guest cart active, and the next login simply tries again.
Why carts can be merged at all
Carts are a classic case where merging beats rejecting. The 2007 Dynamo paper describes a shopping cart that must never lose an Add to cart. When copies of a cart disagree, the application merges them into one cart.
The same paper names the cost: deleted items can resurface after such a merge. It also reports that 99.94 percent of shopping cart requests saw exactly one version over 24 hours. Conflicts are rare, but your rule must handle them.
What should happen when a price changes while items sit in the cart?
The shopper pays the current price, checked by the server at checkout, and the cart shows the change clearly before payment. The price stored in the cart is only a note of what the shopper saw.
In the running example, the kurta was 899 rupees when added and 949 rupees after the sale. The cart line keeps 899 as price_seen. On every cart view, the service reads the current price and compares.
- If the price went up, show both prices on the line, such as "was 899, now 949", before the shopper reaches the pay button.
- If the price went down, show the lower price and charge it.
- If a coupon or sale ended, say which one ended and when, instead of a silent new total.
- Never accept a price sent by the app at checkout. The app can be changed by the user, so only the server's price counts.
Some stores freeze a price for a short time once checkout starts, so the total does not move while the shopper types an address. This is a business choice, so write down the freeze length and show it.
One open-source platform shows the idea in a nearby place. As of 31 October 2026, Saleor's docs say a draft order line keeps its base price for 24 hours by default, set by draftOrderLinePriceFreezePeriod. That applies to draft orders, not to carts.
Should adding an item to the cart reserve stock?
Often no. A common design checks stock when you add an item but holds it only when checkout starts, for a few minutes. Holding at add-to-cart lets idle carts lock up stock that real buyers want.
| Approach | What the shopper sees | Main risk | Fits |
|---|---|---|---|
| No hold, check at payment | May learn at the last step that the item sold out | Disappointment at payment | Plenty of stock, cheap items |
| Hold on Add to cart | Item is safe while it sits in the cart | Idle carts block stock; bots can hoard | Rare items, short timers, strict limits |
| Hold when checkout starts | Item is safe for a few minutes while paying | Must expire holds reliably | Most stores, and the running example |
Platforms offer these as settings. As of 31 October 2026, Saleor's reservations are optional, with separate durations in minutes for guests and logged-in users. Without them, Saleor allocates stock only when the order is placed.
commercetools offers a ReserveOnCart mode that reserves line items as they are added. Its docs say you must set a project expiry between 1 and 44,640 minutes (31 days). They also say stock changes may take up to 10 seconds to appear.
The hold must be one atomic update
The naive hold reads the free stock, checks it in code and then writes the new number. Between the read and the write, other buyers do the same. Each sees free stock and each succeeds.
We ran this on PostgreSQL 16.15 with 10 sarees and 50 buyers at once. A 50 millisecond pause between the read and the write made the race easy to see. In our run, the naive version told all 50 buyers they had a hold. The stored count said only 6 were held, because writes overwrote each other. A rerun gave different numbers, but it still promised more than 10.
The fix is to let the database do the check. Keep two numbers in the product row: on_hand, the units in the warehouse, and held, the units promised to checkouts. Add a CHECK constraint, a rule the database tests on every write, saying held must stay between 0 and on_hand. Then run held = held + 1 as one statement.
With that change, the same 50-buyer test gave exactly 10 holds and 40 clean failures. The database refuses any update that would push held past on_hand, however many requests arrive together.
Life of a stock hold at checkout
Drag to exploreNotice that there are only two exits for a hold: it becomes a sale, or the sweeper gives the unit back. Nothing waits forever.
Diagram connections:
- Shopper starts checkout to Free stock enough? (try to hold 1)
- Free stock enough? to Show sold out (No)
- Free stock enough? to Hold row with expiry (Yes)
- Hold row with expiry to Paid before expiry? (shopper pays or leaves)
- Paid before expiry? to Turn hold into sale (Yes)
- Paid before expiry? to Sweeper releases hold (No, time ran out)
- Shopper starts checkout: Cart has the last red saree
- Free stock enough?: One UPDATE adds to held; CHECK blocks overselling
- Show sold out: Offer to save the item for later
- Hold row with expiry: Cart ID, SKU, quantity, expires in 15 minutes
- Paid before expiry?: Checkout re-checks expires_at itself
- Turn hold into sale: Reduce on_hand and held together
- Sweeper releases hold: Gives the unit back to other shoppers
How holds expire on time
A sweeper is a background job that runs every minute or so, finds holds whose expiry time has passed, and gives the units back. With several sweepers running, two must never release the same hold twice.
In PostgreSQL, SELECT with FOR UPDATE SKIP LOCKED solves this. Each sweeper locks a batch of expired holds, and rows another sweeper has locked are skipped instead of waited on. The PostgreSQL docs suggest this for queue-like tables.
We tested four sweepers against 1,000 expired holds on PostgreSQL 16.15. They released 200, 250, 250 and 300 holds, exactly 1,000 in total. The held count went back to 0, with no hold released twice.
Sweepers can lag, so checkout must also test expires_at itself and refuse an expired hold. The sweeper keeps stock tidy, while the check at payment keeps it correct.
Try it: a runnable cart in about 70 lines of Python
This script builds the running example in an in-memory SQLite database and runs the merge, a hold, an expiry and a price check. It needs only Python 3 and its built-in sqlite3 module. We ran it on Python 3.13.18 with SQLite 3.53.1.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE product (sku TEXT PRIMARY KEY, price INTEGER, on_hand INTEGER NOT NULL,
held INTEGER NOT NULL DEFAULT 0 CHECK (held BETWEEN 0 AND on_hand));
CREATE TABLE cart (cart_id TEXT PRIMARY KEY, owner TEXT, status TEXT);
CREATE TABLE cart_line (cart_id TEXT, sku TEXT, qty INTEGER, price_seen INTEGER,
PRIMARY KEY (cart_id, sku));
CREATE TABLE hold (cart_id TEXT, sku TEXT, qty INTEGER, expires_at INTEGER,
PRIMARY KEY (cart_id, sku));
INSERT INTO product VALUES ('KURTA-M', 899, 3, 0), ('SAREE-RED', 2499, 1, 0);
INSERT INTO cart VALUES ('guest-7f3a', NULL, 'active'), ('acct-42', 'user-42', 'active');
INSERT INTO cart_line VALUES ('guest-7f3a', 'KURTA-M', 2, 899),
('guest-7f3a', 'SAREE-RED', 1, 2499), ('acct-42', 'KURTA-M', 1, 899);
""")
MAX_PER_ITEM = 5
def merge(guest_id, account_id):
with db: # one transaction: all of it happens, or none of it
claimed = db.execute("UPDATE cart SET status = 'merged' "
"WHERE cart_id = ? AND status = 'active'", (guest_id,))
if claimed.rowcount == 0:
return "already merged, nothing to do"
db.execute("""
INSERT INTO cart_line (cart_id, sku, qty, price_seen)
SELECT ?, sku, min(qty, ?), price_seen FROM cart_line WHERE cart_id = ?
ON CONFLICT (cart_id, sku) DO UPDATE
SET qty = max(qty, excluded.qty)""",
(account_id, MAX_PER_ITEM, guest_id))
return "merged"
def hold_stock(cart_id, sku, qty, now, minutes=15):
try:
with db:
db.execute("UPDATE product SET held = held + ? WHERE sku = ?", (qty, sku))
db.execute("INSERT INTO hold VALUES (?, ?, ?, ?) "
"ON CONFLICT (cart_id, sku) DO UPDATE "
"SET qty = qty + excluded.qty, expires_at = excluded.expires_at",
(cart_id, sku, qty, now + minutes * 60))
return "held"
except sqlite3.IntegrityError:
return "not enough stock"
def release_expired(now):
with db:
expired = db.execute("SELECT cart_id, sku, qty FROM hold "
"WHERE expires_at BETWEEN 0 AND ?", (now,)).fetchall()
for cart_id, sku, qty in expired:
db.execute("UPDATE product SET held = held - ? WHERE sku = ?", (qty, sku))
db.execute("DELETE FROM hold WHERE cart_id = ? AND sku = ?", (cart_id, sku))
return len(expired)
def price_changes(cart_id):
return db.execute("""
SELECT l.sku, l.price_seen, p.price FROM cart_line l JOIN product p USING (sku)
WHERE l.cart_id = ? AND l.price_seen != p.price""", (cart_id,)).fetchall()
print(merge("guest-7f3a", "acct-42"))
print(merge("guest-7f3a", "acct-42"))
print(db.execute("SELECT sku, qty FROM cart_line WHERE cart_id = 'acct-42' "
"ORDER BY sku").fetchall())
print(hold_stock("acct-42", "SAREE-RED", 1, now=1000))
print(hold_stock("acct-99", "SAREE-RED", 1, now=1100))
print("released:", release_expired(now=1000 + 15 * 60))
print(hold_stock("acct-99", "SAREE-RED", 1, now=1950))
db.execute("UPDATE product SET price = 949 WHERE sku = 'KURTA-M'")
print(price_changes("acct-42"))Save it as cart_demo.py and run python3 cart_demo.py. You should see exactly these eight lines:
merged
already merged, nothing to do
[('KURTA-M', 2), ('SAREE-RED', 1)]
held
not enough stock
released: 1
held
[('KURTA-M', 899, 949)]What just happened? Each output line matches one step of the running example.
- Line 1: the merge claimed the guest cart and copied its lines.
- Line 2: the same merge ran again, like a retried login, and did nothing.
- Line 3: the account cart has 2 kurtas, not 3, because the rule keeps the higher quantity, plus the saree.
- Lines 4 and 5: the first shopper holds the only saree, and the second shopper is refused by the CHECK constraint.
- Lines 6 and 7: at 15 minutes the sweeper releases the hold, and the second shopper can now hold the saree.
- Line 8: the kurta's price moved from 899 to 949, so the cart flags that line for the shopper.
Two details are easy to miss. The SQL compares times with BETWEEN 0 AND now, which reads as expired at or before now. The SELECT inside the merge has a WHERE clause, which SQLite's docs say an INSERT from a SELECT needs before ON CONFLICT.
To check that the cap works, change the guest cart's kurta quantity to 9 and run it again. Line 3 should show 5 kurtas, because MAX_PER_ITEM is 5.
How do abandoned-cart reminder jobs work without spamming people?
An abandoned-cart job is a scheduled task that finds carts idle for a set time, checks that a reminder is allowed, and sends at most one message per cart. It must stop the moment the shopper buys.
Find idle carts
Every 15 minutes, select carts with items, an owner who can be contacted, and no update for, say, 4 hours. An index on last updated time, a lookup structure that finds matching rows fast, keeps this query cheap.
Check permission
Skip shoppers who have not agreed to marketing messages or who unsubscribed. Guest carts with no email address are skipped too.
Record before sending
Insert a row saying reminder 1 for this cart, with a unique key on cart ID and reminder number. If the row already exists, another run sent it, so stop.
Re-check, then send
Just before sending, check the cart is still active and unpaid. Re-price it, so the message does not show an old sale price.
Stop on purchase
When an order-paid event arrives, mark the cart converted. Every later job run then skips it.
The record-before-sending step is the same idea as an idempotency key, a unique value that lets a repeated request be detected and ignored. The SevyDevy guide on idempotency keys covers that pattern in depth.
Cleaning up old carts
Carts that nobody touches should be deleted on a schedule, or the table grows forever. Platforms publish their defaults, which are a useful starting point for your own numbers.
As of 31 October 2026, Saleor's docs say unfinished checkouts are deleted after 6 hours if empty. Anonymous ones with items go after 30 days, and ones tied to a user or email after 90 days. commercetools deletes carts 90 days after their last change by default in projects created after 8 January 2020.
Which failures should a shopping cart design plan for?
Plan for retries, two tabs, lagging jobs and slow neighbours. Each one has a cheap fix if you design for it early.
| Failure | What the shopper sees | Fix |
|---|---|---|
| Login request retried | Quantities doubled | Claim the guest cart with one conditional update before copying |
| Two tabs edit one cart | One change silently lost | Keep a version number on the cart; reject a write with an old version and reload |
| Add to cart tapped twice | Quantity jumps by 2 | Send a request ID with each add and ignore repeats |
| Price service slow | Cart page hangs | Show the cart with a short timeout and mark prices as being checked |
| Sweeper stopped | Items stuck as held | Checkout checks expires_at itself; alert when expired holds pile up |
| Many buyers want the last item | Item sold twice | Atomic update guarded by a CHECK constraint on held |
How do you explain shopping cart system design in a system design interview?
Start from the rules, not the boxes. A strong answer shows that a cart is changeable state with merge, price and stock rules, then adds the parts that enforce them.
Scope it
Ask about guest checkout, devices, item limits and whether stock is scarce. Say you will design the cart and checkout handoff, not payments.
Size it
Estimate active carts, lines per cart and peak writes. Show that data is small and traffic is the challenge, so carts split well by cart ID.
Draw the parts
Cart service and database, price and inventory services, an events queue and background jobs. The app holds only a cart ID.
Explain the merge
Name your quantity rule and why. Show the atomic claim that makes a retried login harmless.
Explain price and stock
The cart price is a note; the server re-prices at checkout. Hold stock at checkout with an atomic update and an expiry.
Cover the jobs
A sweeper using SKIP LOCKED, a reminder job that records before sending, and cleanup of stale carts.
Close with failures
Walk through retries, two tabs and a stopped sweeper, and how each fix handles them.
Questions people ask
Should a shopping cart be stored in the browser or on the server?
Store the cart on the server and keep only a random cart ID in the browser. A server cart can follow the shopper to another device, be merged at login, trigger reminders and be cleaned up. A browser-only cart can do none of these, and its prices can be edited by the user.
What happens to a guest cart when the user logs in?
The guest cart is merged into the account cart, or replaces it, by a rule the store chooses. A safe merge first claims the guest cart with one conditional update, so a retried login does nothing. For the same item in both carts, commercetools, for example, keeps the higher quantity rather than adding them.
Does adding an item to the cart reserve it?
Often not. In a common design, adding an item checks that stock exists, but the unit is held only when checkout starts, for a few minutes. Some platforms can reserve at add-to-cart, with an expiry, for scarce items. Holding stock for every idle cart would block real buyers.
How do you stop two people buying the last item?
Let the database enforce the limit in one statement. Keep held and on_hand in the same row, add a CHECK constraint that held stays between 0 and on_hand, and increase held with a single update. In our 50-buyer test on PostgreSQL 16.15, this gave exactly 10 holds for 10 units.
Which price does the customer pay if it changed after adding to cart?
The customer pays the current price that the server calculates at checkout, unless the store has a written price-lock rule. The cart keeps the old price only as a note, so it can show the change clearly before payment. Never accept a price sent by the app.
How long should a cart be kept?
Long enough to be useful, then deleted on a schedule. As of 31 October 2026, Saleor deletes empty checkouts after 6 hours and anonymous ones with items after 30 days. commercetools deletes carts 90 days after their last change by default in projects created after 8 January 2020.
How do abandoned-cart emails avoid being sent twice?
Record the reminder in the database before sending, with a unique key on cart ID and reminder number. If a second job run tries the same reminder, the insert fails and it stops. Re-check that the cart is unpaid just before sending, and stop once an order is paid.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (11)
- Dynamo: Amazon's Highly Available Key-value Store (SOSP 2007), sections 2.3, 4.4 and 6.3
- commercetools docs: Cart merge strategies
- commercetools docs: Reserve stock on Cart
- commercetools release note, 8 January 2020: default project values for deletion
- Saleor docs: Stock reservation
- Saleor docs: Checkout lifecycle
- Saleor docs: Price freeze period
- PostgreSQL docs: SELECT, the locking clause (SKIP LOCKED)
- PostgreSQL docs: Constraints (check constraints)
- SQLite docs: UPSERT
- Redis docs: Keyspace notifications, timing of expired events