"Design a shopping cart" sounds like a list with a total. A weak answer draws a Cart holding CartItems, each with a product, a quantity and a price, and a getTotal() that adds them up. Then it stops, and the hard parts are not in it.
The interviewer is checking three of them. The shop runs several promotions at once, and the design must say which ones can stack and which set the customer gets. A price can change between the moment a product goes in the cart and the moment the customer taps Place order. And a customer who shopped as a guest signs in, and two carts become one.
Food Delivery already designs a cart from one restaurant, stock taken at checkout, and a bill with one coupon, tax and a delivery fee. This page does not repeat those. It follows a 45 minute interview: we ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| Can people shop before they sign in? | Yes. A guest has a cart of their own | A CartId that is a guest's or a customer's |
| What happens to that cart at sign-in? | It merges into the customer's cart | mergeOnSignIn and a MergeReport |
| Is there a limit per product? | Yes, set per product, from 1 to 20. A cart holds at most 50 products | A check in add, setQuantity and the merge |
| Which promotions run? | Buy X get Y free, a percentage off a category, and an amount off orders from a total | A Promotion interface and three records |
| Can promotions stack? | Item deals stack if they touch different products, and one order offer goes on top | A Scope on each promotion, and the engine's rule |
| Does the customer pick the promotions? | No. The shop applies the set that saves the most, with no codes | A search in PromotionEngine |
| Can a price change while a product sits in a cart? | Yes, at any time | The cart holds no prices, and checkout prices again |
| Can one customer use two devices at once? | Yes, a phone and a laptop on one cart | A lock per cart, and a version that counts changes |
| What about payment and stock? | Outside this design | placeOrder ends at an Order |
The question that matters most is "can promotions stack?" If no two promotions ever combine, the shop applies the largest one and the job is a loop. Once some combine and some do not, the shop has to compare whole sets, and the biggest single deal is not always part of the best set.
Requirements
Functional:
- A guest or a signed-in customer adds products to a cart. Each product has a limit per customer, and a cart holds at most 50 products. A product the shop no longer sells cannot be added.
- The cart page shows today's prices, the promotions applied, and the total.
- The shop runs three kinds of promotion: buy X get Y free on a product, a percentage off a category, and an amount off orders from a total. A product takes at most one item deal. One order offer can go on top, and its threshold counts the order after the item deals.
- The shop applies the set of promotions that saves the customer the most.
- Each discount is shared out across the lines it covers, and the shares add up exactly to the discount.
- Placing an order prices the cart again. If the total went up since the customer saw it, nothing is placed, and the customer sees the new total to confirm. A retried Place order never places a second order.
- When a guest signs in, the guest cart merges into the customer's cart. Quantities add up to the product's limit, products no longer sold are dropped, products that do not fit a full cart are left out, and the customer is told about each. A repeated sign-in merges nothing twice.
Out of scope: payment, holding stock, several sellers and split shipments, saved for later, wishlists, shipping charges and tax. We come back to these at the end, because each is a likely follow-up.
Everything lives in memory, as is normal for a low-level design interview. The product catalog is an interface, and the project has an in-memory one.
What the code itself must handle:
- Two devices on one cart. A phone and a laptop can add, quote and place an order at the same moment.
- Rules that change. Marketing adds kinds of promotion, and the cart must not change when they do.
- Money that adds up. Every amount is a whole number of cents in a
long, never adouble. Food Delivery and Ride Sharing wrap cents in aMoneyrecord. Here amounts sit mostly in maps of shares per product, where a plainlongkeeps the arithmetic short, andMath.addExactandMath.multiplyExactguard the sums and products.
Finding the classes
Picking the nouns out of the requirements gives a first list. Most become classes, records, enums or interfaces. A few are dropped, and dropping them is part of the design.
The noun that needs the most thought is the price on a cart line, because most first drafts store one.
Does the cart keep each product's price?
Yes: the price when it was added, charged at checkout
The customer pays exactly what they saw. But a cart left for a month buys at last month's price, and a price typed wrong cannot be fixed for carts that already hold it.
Yes, and checkout compares each line's price
Checkout can name the product whose price moved. But each line carries a second price to keep in step, and a line comparison misses a change that moves no price, such as an offer that ended.
No: the cart keeps quantities, and every quote reads today's pricesOur pick
The catalog is the one place that knows a price. The cart page and checkout both price the cart the same way, and checkout compares totals, which catches every change that raises the total. The cost is that the cart page cannot say "this was $12 when you added it" without extra state.
Data or behaviour?
Some classes only carry values that never change: a product, a priced line, a discount, a quote, an order. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString without writing them. Cart and ShoppingService are ordinary classes, because their state changes.
Three kinds of error leave the design. A refusal the customer should read, such as a limit reached, is a CartException, and PriceChangedException is one of these. A mistake in the calling code, such as adding a quantity of 0 or adding a product id the catalog never listed, throws IllegalArgumentException. A promotion that answers with an impossible discount is a bug in our own rules, and the engine throws IllegalStateException.
The class diagram
The classes fall into three groups:
- Data: the records
Product,PricedLine,Discount,Quote,QuotedLine,Order,CartIdandMergeReport, and the enumScope. - The core:
ShoppingServiceandCart. The service coordinates and holds each cart's lock. - Rules and outside systems:
PromotionEngine,CentSplitter, thePromotioninterface with its three records, and theCataloginterface.
Building it
The cart and its version
A Cart holds a quantity for each product id and a version that goes up on every change. Adding checks the limits under the cart's lock:
public void add(CartId cartId, String productId, int quantity) { if (quantity < 1) { throw new IllegalArgumentException("Quantity must be positive: " + quantity); } Cart cart = cartOf(cartId); synchronized (cart) { Product product = onSale(productId); int have = cart.quantityOf(productId); if (have == 0 && cart.lineCount() >= Cart.MAX_LINES) { throw cartFull(); } if (quantity > product.maxPerCustomer() - have) { throw new CartException(atMost(product)); } cart.set(productId, have + quantity); } }The lock is taken on line 40, so the checks and the change are one step. Line 43 refuses a 51st product. Line 46 compares against what is left under the limit, maxPerCustomer() - have, so no sum is made that could overflow. A product the shop no longer sells is refused by onSale on line 41, with the product's name in the message. Every refusal leaves the cart and its version as they were.
The cart page also needs to lower a quantity. If the shop cuts the mug's limit from 5 to 3, a cart holding 5 must be able to go down to 3:
/** Sets one product's quantity, and 0 removes it. Lowering is always allowed; raising checks the limits. */ public void setQuantity(CartId cartId, String productId, int quantity) { if (quantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative: " + quantity); } Cart cart = cartOf(cartId); synchronized (cart) { int have = cart.quantityOf(productId); if (quantity > have) { Product product = onSale(productId); if (have == 0 && cart.lineCount() >= Cart.MAX_LINES) { throw cartFull(); } if (quantity > product.maxPerCustomer()) { throw new CartException(atMost(product)); } } if (quantity != have) { cart.set(productId, quantity); } } }setQuantity sets the quantity directly, and 0 removes the product. Lowering skips every check (line 61), because it is how the customer fixes a cart, even one above a lowered limit or holding a product no longer sold. Raising runs the same checks as add (lines 62 to 68). Setting the quantity the cart already has changes nothing, not even the version (lines 70 to 72).
The version is how checkout later knows the cart is the one the customer saw. A quote records it, and an edit from another device moves it on.
Promotions behind one interface
public interface Promotion { String id(); Scope scope(); /** What this promotion takes off these lines, or empty if it does not apply to them. */ Optional<Discount> discountFor(List<PricedLine> lines);}discountFor gets the cart's priced lines and answers with a Discount, which says how many cents come off each product, or with nothing. Here is buy X get Y free:
public Optional<Discount> discountFor(List<PricedLine> lines) { for (PricedLine line : lines) { if (line.productId().equals(productId)) { long freeUnits = (long) (line.quantity() / (buy + free)) * free; long cents = Math.multiplyExact(freeUnits, line.unitPriceCents()); if (cents == 0) { return Optional.empty(); } return Optional.of(new Discount(id, Map.of(productId, cents))); } } return Optional.empty();Only full sets count. Buy 2 get 1 free gives one free mug for 3 mugs, one for 5 and two for 6, and nothing for 2. PercentOffCategory adds up the category's lines and takes its share in basis points, rounded down, so a 30% offer never gives more than 30%. AmountOffOver takes its amount once the lines reach its threshold, and never more than the lines are worth. All three are records, because an offer does not change once it starts.
Which promotions stack
Each promotion says where it applies:
public enum Scope { /** Takes money off particular lines. A line takes at most one item deal. */ ITEM, /** Takes money off the whole order, after the item deals. An order takes at most one. */ ORDER}An item deal takes money off particular products. An order offer takes money off the whole order, and it sees the order as the item deals left it.
Which promotions stack?
All of them, one after another
It needs no rules. But a mug already free under buy 2 get 1 then gets 30% off as well, and the answer changes with the order the promotions are listed in.
None: one promotion per order
It is easy to explain and to check. But the shop cannot run a mug deal and a "$10 off from $60" offer for the same customer, which is a common pairing.
One item deal per product, plus one order offer counted after the item dealsOur pick
No unit is discounted by two item deals, and the order offer sees only what the item deals left, so a line's discounts never add up past its amount. The order offer stacks on top, and its threshold counts what the customer pays for the items, so free mugs do not lift an order over $60. The cost is that the shop must now compare sets of promotions, which the next section does.
Choosing the best set
The demo cart holds 3 mugs at $12, a kettle at $40 and 2 tea towels at $5. Four promotions run: buy 2 mugs get 1 free (MUG3), buy 1 towel get 1 free (TOWEL2), 30% off Kitchen (KITCHEN30), and $10 off from $60 (SAVE10).
bestFor first asks every item deal for its discount. Then Search tries every set of those discounts that share no product:
void from(int next) { if (next == deals.size()) { consider(); return; } Discount deal = deals.get(next); if (Collections.disjoint(claimed, deal.byProduct().keySet())) { chosen.add(deal); claimed.addAll(deal.byProduct().keySet()); from(next + 1); claimed.removeAll(deal.byProduct().keySet()); chosen.remove(chosen.size() - 1); } from(next + 1); } private void consider() { long cents = 0; Map<String, Long> taken = new HashMap<>(); for (Discount deal : chosen) { cents = Math.addExact(cents, deal.totalCents()); taken.putAll(deal.byProduct()); } List<PricedLine> left = new ArrayList<>(); for (PricedLine line : lines) { left.add(line.withAmount(line.amountCents() - taken.getOrDefault(line.productId(), 0L))); } Optional<Discount> offer = bestOffer(left); long total = offer.isPresent() ? Math.addExact(cents, offer.get().totalCents()) : cents; // Strictly more, so a tie keeps the set found first and the same cart always gets the same answer. if (total > bestCents) { List<Discount> picked = new ArrayList<>(chosen); offer.ifPresent(picked::add); best = List.copyOf(picked); bestCents = total; } }For each deal, from tries the sets with it (line 113), if it touches no product already claimed (line 110), and then the sets without it (line 117). At the end of each path, consider takes the chosen deals off their lines and asks every order offer about what is left (lines 127 to 131). It keeps the set only if it saves strictly more (line 134). So a tie keeps the set found first, and the same cart always gets the same answer.
The engine does not trust a promotion's numbers. checked refuses a discount on a product that is not in the cart, or larger than what is left on its line, with an IllegalStateException. A promotion is code someone will change, and a bug there must fail the quote, not price a line below zero.
How does the shop choose among promotions?
A priority order that marketing sets
The answer is predictable, and marketing controls it. But the customer can lose money to a list that nobody reordered after a new offer started.
The biggest deal first, then whatever still fits
It is one pass and sounds right. The figure shows it picking KITCHEN30 and saving $3.20 less than the best set.
Try every set that obeys the stacking rules, with at most 12 promotionsOur pick
The answer is the best set by construction, and it is easy to test against single promotions. The cost is time, which can double with each item deal. PromotionEngine refuses more than 12 promotions, so a quote tries at most 4,096 sets. bestFor already searches only the deals that apply to this cart. With hundreds of offers, the cap would move from registered promotions to the deals that touch this cart.
Sharing a discount out to the cent
An order offer takes $10 off the order, but each line needs its own share. A customer who returns the kettle gets back what the kettle cost after discounts, and tax in many places is worked out per line. Splitwise splits a bill among people in the same way, and its Decision explains why the leftover cents go to the largest remainders. CentSplitter does the same for lines:
Map<String, Long> remainders = new HashMap<>(); long given = 0; for (Map.Entry<String, Long> line : weights.entrySet()) { long exact = Math.multiplyExact(cents, line.getValue()); shares.put(line.getKey(), exact / total); remainders.put(line.getKey(), exact % total); given += exact / total; } // The cents lost by rounding down go one each to the largest remainders; a tie goes to the earlier line. List<String> byRemainder = new ArrayList<>(weights.keySet()); byRemainder.sort((first, second) -> Long.compare(remainders.get(second), remainders.get(first))); for (int i = 0; i < cents - given; i++) { shares.merge(byRemainder.get(i), 1L, Long::sum); } shares.values().removeIf(share -> share == 0); return shares;Each line gets its exact share rounded down (lines 32 to 35), and the cents left over go one each to the largest remainders (lines 38 to 41). In the figure, $10.00 over $24, $40 and $5 gives 347.83, 579.71 and 72.46 cents. Rounded down that is 998, and the 2 spare cents go to the mugs and the kettle.
Ties are broken differently. Splitwise sorts people by id, so a bill splits the same way whatever order the names were typed in. Here a tie goes to the earlier line in the cart. The cart's order is the receipt's order, and an order keeps its quote, so the split is worked out once and never again. Someone reading the receipt from the top can see which line took the cent.
No share is ever larger than its line, because a line that gets a spare cent was below its exact share. The product on line 32 fits in a long. A cart holds at most 50 products of 20 units at $10,000, or 1,000,000,000 cents, so the product is at most that number squared, about 9 times below the largest long. multiplyExact would throw rather than wrap if the limits ever grew.
Where does an order-wide discount land?
Only on the order total
The receipt is simple. But a return of one item cannot be refunded exactly, and anything worked out per line has nothing to work from.
On each line by amount, with the spare cents going to the largest remaindersOur pick
Each line carries its share, so a return or a tax per line has an exact amount to work from, and the shares add up to the discount. PercentOffCategory uses the same splitter for its share of a category. The cost is a sort over at most 50 lines and one more number on each line of the receipt.
When a price changes before Place order
The cart page calls quote, which prices the cart under its lock:
private Quote price(CartId cartId, Cart cart) { List<PricedLine> lines = new ArrayList<>(); List<String> problems = new ArrayList<>(); for (Map.Entry<String, Integer> item : cart.items().entrySet()) { Optional<Product> product = catalog.find(item.getKey()); if (product.isEmpty() || !product.get().onSale()) { problems.add(notSold(product.map(Product::name).orElse(item.getKey()))); } else if (item.getValue() > product.get().maxPerCustomer()) { problems.add(atMost(product.get())); } else { lines.add(PricedLine.of(product.get(), item.getValue())); } } return Quote.of(cartId, cart.version(), lines, promotions.bestFor(lines), problems); }Each product is read from the catalog now (line 173). A product the shop stopped selling stays in the catalog with onSale false, so it becomes a problem on the quote that names it, not a line (lines 174 and 175). The quote records the cart's version (line 182). Asha's cart page shows version 3 at $59.00. Then staff raise the mug to $13, and Asha taps Place order with the quote she saw:
public Order placeOrder(Quote seen) { CartId cartId = Objects.requireNonNull(seen, "seen").cartId(); if (cartId.kind() != CartId.Kind.CUSTOMER) { throw new CartException("Please sign in to place your order"); } Cart cart = cartOf(cartId); synchronized (cart) { Attempt attempt = new Attempt(cartId, seen.cartVersion()); Order placed = ordersByAttempt.get(attempt); if (placed != null) { return placed; } if (seen.cartVersion() != cart.version()) { throw new CartException("Your cart changed on another device. Please check it again."); } Quote now = price(cartId, cart); if (!now.problems().isEmpty()) { throw new CartException(String.join("; ", now.problems())); } if (!seen.problems().isEmpty()) { throw new CartException("Your cart changed since you checked it. Please check it again."); } if (now.lines().isEmpty()) { throw new CartException("Your cart is empty"); } if (now.totalCents() > seen.totalCents()) { throw new PriceChangedException(seen, now); } Order order = new Order(orderNumbers.incrementAndGet(), cartId.id(), now); ordersByAttempt.put(attempt, order); cart.clear(); return order; } }- A retry finds its order (lines 92 to 96). The quote's cart and version name the attempt. If an order was already placed for them, it is returned, before anything else is checked.
- The cart must be the one the customer saw (lines 97 to 99). An edit from another device moved the version on, and the customer must look again.
- Price it again (line 100), with today's prices and today's best promotions.
- Refuse any quote with a problem (lines 101 to 106), today's or the one the customer saw. If the seen quote left out a peg that was not on sale, and the peg is back, today's lines differ from what was shown. The peg's $5 could lift the order over $60 and lower the total, so the total check alone would place it unasked.
- Ask if the total went up (lines 110 to 112).
PriceChangedExceptioncarries the new quote. The app shows it, and the customer confirms by sending that quote back. - Place it (lines 113 to 115). The order holds the new quote, its number is taken only now, and the cart is emptied.
Every check runs before anything changes. A promotion that throws in the middle leaves the cart, its version and the orders exactly as they were.
When does checkout ask the customer again?
Never: charge today's price
There is no second step. But Asha agreed to $59.00 and is charged $61.00 without being asked.
Honour the total the customer saw
The customer is never surprised. But an old tab buys at an old price, and a price typed wrong as $1.20 instead of $12 stays $1.20 for anyone who saw it.
Only when the total goes upOur pick
No order is placed for more than the customer agreed to. With step 4 in place, the lines are the ones the customer saw, so a lower or equal total goes through at today's prices, with no second step. Totals are compared, not prices, because a total can rise with no price rising. A $64 kettle with SAVE10 costs $54. At $58 it loses the $10 and costs $58. The cost is one more round trip when the total rises.
What makes a retried Place order safe?
A request id that the app makes and sends
It works for one device that retries. But the app must keep the id across a crash, and a second device sends its own id for the same cart.
The quote's cart and version: ordersByAttempt returns the order already placed for themOur pick
The quote already names one exact state of one cart, so it is the key. A retry, a double tap and a second tab holding the same quote all get the same order. The check runs before the version check, because placing the order moved the version on. In production this is a unique key on the orders table, and a cart's version must never start again from zero, or a recreated cart would match an old order. A second tab holding the $59.00 quote gets back ORD-1 at $61.00, placed from the other device, so the app shows the returned order's total, not the quote's. The cost is one map entry per order.
Merging the guest cart at sign-in
Asha's account cart has 2 mugs and a kettle from last week. Her phone, as guest g-41, has 2 mugs, 2 towels and a desk lamp, and the shop has since stopped selling the lamp.
public MergeReport mergeOnSignIn(String guestId, String customerId) { Cart guest = carts.get(CartId.guest(guestId)); if (guest == null) { return MergeReport.NOTHING; } Cart target = cartOf(CartId.customer(customerId)); // Always the customer's cart first, then the guest's, so two merges can never deadlock. synchronized (target) { synchronized (guest) { Map<String, Integer> next = new LinkedHashMap<>(target.items()); List<String> merged = new ArrayList<>(); List<String> capped = new ArrayList<>(); List<String> dropped = new ArrayList<>(); List<String> noRoom = new ArrayList<>(); for (Map.Entry<String, Integer> item : guest.items().entrySet()) { String productId = item.getKey(); Optional<Product> product = catalog.find(productId); int have = next.getOrDefault(productId, 0); if (product.isEmpty() || !product.get().onSale()) { dropped.add(productId); } else if (have == 0 && next.size() >= Cart.MAX_LINES) { noRoom.add(productId); } else if (have + item.getValue() > product.get().maxPerCustomer()) { capped.add(productId); next.put(productId, Math.max(have, product.get().maxPerCustomer())); } else { merged.add(productId); next.put(productId, have + item.getValue()); } } target.replaceAll(next); guest.clear(); return new MergeReport(merged, capped, dropped, noRoom); } } }The merge takes both locks, the customer's cart first (lines 128 and 129). It builds the new quantities in a copy, next (line 130), reading each product from the catalog (line 137). A product no longer sold goes to dropped, and a new product that would be a 51st line goes to noRoom (lines 139 to 142), so the app can tell the customer which one happened. A capped product keeps the larger of what the customer already had and the limit (line 145), so a merge never lowers a quantity, even above a lowered limit. Only then are both carts changed (lines 151 and 152). If the catalog throws halfway, neither cart has changed.
Emptying the guest cart in the same locked step makes a retried sign-in safe. The second call finds the guest cart empty and returns a report with nothing in it. The lock order matters too. Every merge takes a customer's cart and then a guest's, and nothing ever locks a guest cart first and then a customer's. So two merges cannot each hold the lock the other needs.
How do the two carts merge?
The guest cart replaces the customer's cart
It is one assignment. But last week's kettle disappears without a word.
Keep the larger quantity of each product
A product added on both devices is not doubled by accident. But a customer who meant to add 2 more mugs gets 2 in all, and nothing tells them.
Add the quantities up to the limit, drop what is no longer sold, and report bothOur pick
Every item the customer chose is either in the cart or named in the MergeReport, as merged, capped, dropped or without room, and the app turns it into a short notice. The cost is that a customer who added the same mug on two devices by mistake now has two, and the notice is how they find out.
Two devices, one cart
Every method of ShoppingService that reads or changes a cart takes that cart's lock first, and Cart itself has no public methods. The project includes a check, demo/RaceCheck.java. It runs three races 1,000 times each, with a barrier that starts both devices together. Two devices add the last mug the limit allows. The phone places its order while the laptop adds a towel. Two tabs finish signing in with one guest cart.
Last allowed mug, two devices: both told "added" 0 times Place order while adding: order first 499, add first 501, towel lost or bought unseen 0 Two sign-ins, one guest cart: towels not exactly 2 0 times
No device was told "added" for a mug over the limit, no towel was lost or bought without being quoted, and no guest towels were counted twice. The split between "order first" and "add first" changes from run to run. With every lock removed, the mug race let both devices add the last mug a few times in 1,000 in most runs. The order race crashed with a ConcurrentModificationException in most runs we tried, before the sign-in race started, and lost or bought unseen towels in the rest. With only the merge's two locks removed, the sign-in race counted guest towels twice a few times in 1,000, or crashed.
Where do the locks go?
One lock on the whole ShoppingService
It is correct and easy to explain. But every customer's quote waits behind every other customer's, and a quote calls the catalog.
A lock per cart, held while that cart is pricedOur pick
Only one customer's own devices ever wait for each other. The quote and the order are priced from the cart as it is under the lock, so no item slips in between. The cost is that a slow catalog makes Asha's laptop wait for her phone, and the merge has to take two locks in a fixed order.
The final design
ShoppingService is the core. It owns every cart and the placed orders, and holds each cart's lock while it works. It reaches prices only through the Catalog interface, and promotions only through PromotionEngine, which asks each Promotion and splits discounts with CentSplitter.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Does the cart keep each product's price? | No: the cart keeps quantities, and every quote reads today's prices | The catalog is the one place that knows a price |
| 2 | Which promotions stack? | One item deal per product, plus one order offer counted after the item deals | No unit is discounted twice |
| 3 | How does the shop choose among promotions? | Try every set that obeys the stacking rules, with at most 12 promotions | The best set by construction |
| 4 | Where does an order-wide discount land? | On each line by amount, with the spare cents going to the largest remainders | The shares add up to the cent |
| 5 | When does checkout ask the customer again? | Only when the total goes up | No order is placed above the agreed total |
| 6 | What makes a retried Place order safe? | The quote's cart and version: ordersByAttempt returns the order already placed for them | Every retry of one quote gets one order |
| 7 | How do the two carts merge? | Add the quantities up to the limit, drop what is no longer sold, and report both | Nothing the customer chose disappears silently |
| 8 | Where do the locks go? | A lock per cart, held while that cart is priced | Only one customer's devices wait |
Here is Asha's order from the demo, end to end:
- Her phone calls
placeOrderwith the version 3 quote at $59.00.ShoppingServicetakes her cart's lock, andordersByAttemptholds nothing for version 3. - The cart is still version 3, so
pricereads every product fromCatalog.findand finds the mug at $13. PromotionEngine.bestForrunsSearchand again picksMUG3,TOWEL2andSAVE10.CentSplitter.splitshares out the $10.- $61.00 is more than $59.00, so
placeOrderthrowsPriceChangedExceptionand changes nothing. - Her phone sends the $61.00 quote.
placeOrderprices again, placesORD-1, stores it inordersByAttemptand empties the cart, all under the same lock.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package cart; import java.util.ArrayList;import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import catalog.Catalog;import catalog.Product;import promotion.PricedLine;import promotion.PromotionEngine; public class ShoppingService { private final Catalog catalog; private final PromotionEngine promotions; private final Map<CartId, Cart> carts = new ConcurrentHashMap<>(); /** Placed orders by cart and cart version, so a retried Place order finds its order. */ private final Map<Attempt, Order> ordersByAttempt = new ConcurrentHashMap<>(); private final AtomicLong orderNumbers = new AtomicLong(); private record Attempt(CartId cartId, long cartVersion) { } public ShoppingService(Catalog catalog, PromotionEngine promotions) { this.catalog = Objects.requireNonNull(catalog, "catalog"); this.promotions = Objects.requireNonNull(promotions, "promotions"); } public void add(CartId cartId, String productId, int quantity) { if (quantity < 1) { throw new IllegalArgumentException("Quantity must be positive: " + quantity); } Cart cart = cartOf(cartId); synchronized (cart) { Product product = onSale(productId); int have = cart.quantityOf(productId); if (have == 0 && cart.lineCount() >= Cart.MAX_LINES) { throw cartFull(); } if (quantity > product.maxPerCustomer() - have) { throw new CartException(atMost(product)); } cart.set(productId, have + quantity); } } /** Sets one product's quantity, and 0 removes it. Lowering is always allowed; raising checks the limits. */ public void setQuantity(CartId cartId, String productId, int quantity) { if (quantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative: " + quantity); } Cart cart = cartOf(cartId); synchronized (cart) { int have = cart.quantityOf(productId); if (quantity > have) { Product product = onSale(productId); if (have == 0 && cart.lineCount() >= Cart.MAX_LINES) { throw cartFull(); } if (quantity > product.maxPerCustomer()) { throw new CartException(atMost(product)); } } if (quantity != have) { cart.set(productId, quantity); } } } /** The cart page: today's prices and the best promotions. Nothing changes. */ public Quote quote(CartId cartId) { Cart cart = cartOf(cartId); synchronized (cart) { return price(cartId, cart); } } /** Places the order for the quote the customer saw. A retry with the same quote returns the same order. */ public Order placeOrder(Quote seen) { CartId cartId = Objects.requireNonNull(seen, "seen").cartId(); if (cartId.kind() != CartId.Kind.CUSTOMER) { throw new CartException("Please sign in to place your order"); } Cart cart = cartOf(cartId); synchronized (cart) { Attempt attempt = new Attempt(cartId, seen.cartVersion()); Order placed = ordersByAttempt.get(attempt); if (placed != null) { return placed; } if (seen.cartVersion() != cart.version()) { throw new CartException("Your cart changed on another device. Please check it again."); } Quote now = price(cartId, cart); if (!now.problems().isEmpty()) { throw new CartException(String.join("; ", now.problems())); } if (!seen.problems().isEmpty()) { throw new CartException("Your cart changed since you checked it. Please check it again."); } if (now.lines().isEmpty()) { throw new CartException("Your cart is empty"); } if (now.totalCents() > seen.totalCents()) { throw new PriceChangedException(seen, now); } Order order = new Order(orderNumbers.incrementAndGet(), cartId.id(), now); ordersByAttempt.put(attempt, order); cart.clear(); return order; } } /** On sign-in, moves the guest's items into the customer's cart. A second call finds nothing to move. */ public MergeReport mergeOnSignIn(String guestId, String customerId) { Cart guest = carts.get(CartId.guest(guestId)); if (guest == null) { return MergeReport.NOTHING; } Cart target = cartOf(CartId.customer(customerId)); // Always the customer's cart first, then the guest's, so two merges can never deadlock. synchronized (target) { synchronized (guest) { Map<String, Integer> next = new LinkedHashMap<>(target.items()); List<String> merged = new ArrayList<>(); List<String> capped = new ArrayList<>(); List<String> dropped = new ArrayList<>(); List<String> noRoom = new ArrayList<>(); for (Map.Entry<String, Integer> item : guest.items().entrySet()) { String productId = item.getKey(); Optional<Product> product = catalog.find(productId); int have = next.getOrDefault(productId, 0); if (product.isEmpty() || !product.get().onSale()) { dropped.add(productId); } else if (have == 0 && next.size() >= Cart.MAX_LINES) { noRoom.add(productId); } else if (have + item.getValue() > product.get().maxPerCustomer()) { capped.add(productId); next.put(productId, Math.max(have, product.get().maxPerCustomer())); } else { merged.add(productId); next.put(productId, have + item.getValue()); } } target.replaceAll(next); guest.clear(); return new MergeReport(merged, capped, dropped, noRoom); } } } public List<Order> ordersOf(String customerId) { List<Order> orders = new ArrayList<>(); for (Order order : ordersByAttempt.values()) { if (order.customerId().equals(customerId)) { orders.add(order); } } orders.sort(Comparator.comparingLong(Order::number)); return orders; } private Quote price(CartId cartId, Cart cart) { List<PricedLine> lines = new ArrayList<>(); List<String> problems = new ArrayList<>(); for (Map.Entry<String, Integer> item : cart.items().entrySet()) { Optional<Product> product = catalog.find(item.getKey()); if (product.isEmpty() || !product.get().onSale()) { problems.add(notSold(product.map(Product::name).orElse(item.getKey()))); } else if (item.getValue() > product.get().maxPerCustomer()) { problems.add(atMost(product.get())); } else { lines.add(PricedLine.of(product.get(), item.getValue())); } } return Quote.of(cartId, cart.version(), lines, promotions.bestFor(lines), problems); } private Product onSale(String productId) { Product product = catalog.find(productId) .orElseThrow(() -> new IllegalArgumentException("No product " + productId)); if (!product.onSale()) { throw new CartException(notSold(product.name())); } return product; } private static String notSold(String name) { return name + " is no longer sold"; } private static String atMost(Product product) { return "You can buy at most " + product.maxPerCustomer() + " of " + product.name(); } private static CartException cartFull() { return new CartException("Your cart is full: it holds at most " + Cart.MAX_LINES + " products"); } private Cart cartOf(CartId cartId) { return carts.computeIfAbsent(Objects.requireNonNull(cartId, "cartId"), id -> new Cart()); }}demo/Main.java runs Asha's morning. Her account cart is from last week, and she shops as a guest on her phone, then signs in. The shop stops selling the lamp before she signs in and raises the mug's price before she places her order:
Last week, signed in: 2 mugs and a kettle Today, as a guest on her phone: 2 mugs, 2 tea towels and a desk lamp The shop stops selling the desk lamp Asha signs in: merged [TOWEL], capped [MUG], dropped [LAMP], no room [] The sign-in is retried: merged [], capped [], dropped [], no room [] Another mug? You can buy at most 3 of Stoneware mug Cart page, cart version 3: 3 x Stoneware mug $36.00 less $15.48 pays $20.52 1 x Electric kettle $40.00 less $5.80 pays $34.20 2 x Tea towel $10.00 less $5.72 pays $4.28 MUG3 -$12.00 TOWEL2 -$5.00 SAVE10 -$10.00 subtotal $86.00, discount $27.00, total $59.00 The shop raises the mug to $13.00 Place order: Your total went up since you checked your cart. Please check the new total. was $59.00, now $61.00 Asha confirms: ORD-1 placed for $61.00 ORD-1, cart version 3: 3 x Stoneware mug $39.00 less $16.66 pays $22.34 1 x Electric kettle $40.00 less $5.63 pays $34.37 2 x Tea towel $10.00 less $5.71 pays $4.29 MUG3 -$13.00 TOWEL2 -$5.00 SAVE10 -$10.00 subtotal $89.00, discount $28.00, total $61.00 The phone retries Place order: ORD-1, orders for asha: 1
Notice three things in the output. The sign-in capped the mugs at 3 and dropped the lamp, and the retried sign-in merged nothing. The cart page took $27.00 off without KITCHEN30, the biggest single deal. And after the price rise, the order's lines pay $22.34, $34.37 and $4.29, which add up to exactly $61.00, and the retried Place order returned ORD-1 with still one order for Asha.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Show 'this was $12 when you added it'." | Cart keeps the price seen at each add, only for display, and QuotedLine carries it. | placeOrder still compares totals. |
| "Let customers type a coupon code." | A promotion that applies only when its code is on the cart. Cart keeps the codes, and discountFor needs them, so Promotion's signature changes. | Scope, the search and the splitter. |
| "Hold stock while the customer pays." | placeOrder reserves every product or none before the order, as reserve does in Food Delivery. | Quotes, promotions and the merge. |
| "Take payment." | After placeOrder, the order is charged with a key that never repeats, as in BookMyShow. | The cart and the price check. |
| "Several sellers, split shipments." | Quote groups lines by seller, and one checkout creates an order per seller. Shipping charges arrive per seller. | Promotions per line and the version check. |
| "Save for later." | A second list per customer. Moving a product removes it from the cart under the same lock. | Quotes and promotions, which see only the cart. |
| "Wishlists." | A separate list with no quantities and no limits, shared by a link. | Cart and ShoppingService's checkout. |
| "Hundreds of promotions." | The cap moves from registered promotions to the deals that touch this cart, which bestFor already searches alone. Above a dozen of those, it needs a smarter search or a priority order. | Promotion, Scope and the splitter. |
| "Promotions that start and end." | The engine takes a Clock and reads the running promotions at each quote. | placeOrder already asks again when an ending offer raises the total. |
| "Clear old guest carts." | A timer removes guest carts unused for 30 days. | The merge, which already treats a missing guest cart as empty. |
In most rows the change lands in a promotion, a record field, or a class beside the core. Two rows are bigger: a coupon code changes the Promotion interface, and several sellers split one checkout into several orders.
What the interviewer looks for
Mid-level
A mid-level candidate shows clear classes for the cart, the product and the order, money in integer cents, and a limit per product. They apply promotions and know that two devices on one cart need a lock, even if the promotions are applied one after another.
Senior
A senior candidate shows everything above and gives the reasons. They state which promotions stack and why, and show that the biggest deal first can lose to a pair of smaller ones. They share an order discount over the lines so it adds up to the cent. They price the cart again at checkout and ask when the total rises.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They raise these cases: a retried Place order, an edit from another device after the quote, and a price drop that raises the total. They make the merge safe to repeat, and they say what the search costs and where it stops scaling.
Common mistakes
- A price stored in the cart and charged at checkout. A cart left for a month buys at last month's price.
- Promotions applied one after another. A free mug also gets 30% off, and the total depends on the order of a list.
- The biggest deal first. It can block two smaller deals that save more together.
- Each line's share rounded on its own. The shares drift from the discount by a cent or more.
- Charging today's price without asking, or never charging it. One surprises the customer, and the other sells at old prices.
- A merge that replaces or repeats. Replacing loses last week's items, and a retried sign-in that adds again doubles them.
- Checking a limit and adding in two steps without a lock. Two devices can both pass the check.
Summary
- Ask first whether promotions stack, whether prices change, and whether guests shop. Each answer changes the code.
- The cart keeps quantities and a version. Every quote reads today's prices from the catalog.
- One item deal per product, one order offer on top, counted after the item deals. The engine tries every allowed set and keeps the one that saves the most.
- Share each discount over its lines by amount, and give the spare cents to the largest remainders.
- Checkout prices again and asks only when the total rises. The quote's cart and version make a retry return the same order.
- At sign-in, add quantities up to the limit, drop what is no longer sold, report both, and empty the guest cart in the same locked step.
- Lock per cart, and take two carts' locks in one fixed order.