LLD

Full Designs

Shopping Cart (Amazon, Flipkart)

A weak answer draws a cart with a list of items and a total, and stops. We build one that holds up when the interviewer pushes: promotions that stack only in some ways, the best set chosen for the customer, discounts shared out to the cent, prices that change before Place order, and a guest cart that merges at sign-in.

"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.

A cart at a glance
Asha adds products as a guest on her phone (1). When she signs in, the guest cart merges into her own cart (2). The cart page calls quote(), which reads today's prices from the Catalog and asks PromotionEngine for the best set, and shows $59.00 (3). Staff then raise the mug from $12 to $13. Asha taps Place order with the quote she saw (4). placeOrder prices the cart again, finds $61.00, and sends the new total back in amber. Asha confirms it (5), and ORD-1 is placed for $61.00.Asha adds products as a guest on her phone (1). When she signs in, the guest cart merges into her own cart (2). The cart page calls quote(), which reads today's prices from the Catalog and asks PromotionEngine for the best set, and shows $59.00 (3). Staff then raise the mug from $12 to $13. Asha taps Place order with the quote she saw (4). placeOrder prices the cart again, finds $61.00, and sends the new total back in amber. Asha confirms it (5), and ORD-1 is placed for $61.00.
Prices are read at every quote, and again when the order is placed. Asha adds products as a guest on her phone (1). When she signs in, the guest cart merges into her own cart (2). The cart page calls quote(), which reads today's prices from the Catalog and asks PromotionEngine for the best set, and shows $59.00 (3). Staff then raise the mug from $12 to $13. Asha taps Place order with the quote she saw (4). placeOrder prices the cart again, finds $61.00, and sends the new total back in amber. Asha confirms it (5), and ORD-1 is placed for $61.00.

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Can people shop before they sign in?Yes. A guest has a cart of their ownA CartId that is a guest's or a customer's
What happens to that cart at sign-in?It merges into the customer's cartmergeOnSignIn and a MergeReport
Is there a limit per product?Yes, set per product, from 1 to 20. A cart holds at most 50 productsA 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 totalA Promotion interface and three records
Can promotions stack?Item deals stack if they touch different products, and one order offer goes on topA 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 codesA search in PromotionEngine
Can a price change while a product sits in a cart?Yes, at any timeThe cart holds no prices, and checkout prices again
Can one customer use two devices at once?Yes, a phone and a laptop on one cartA lock per cart, and a version that counts changes
What about payment and stock?Outside this designplaceOrder 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:

  1. 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.
  2. The cart page shows today's prices, the promotions applied, and the total.
  3. 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.
  4. The shop applies the set of promotions that saves the customer the most.
  5. Each discount is shared out across the lines it covers, and the shares add up exactly to the discount.
  6. 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.
  7. 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 a double. Food Delivery and Ride Sharing wrap cents in a Money record. Here amounts sit mostly in maps of shares per product, where a plain long keeps the arithmetic short, and Math.addExact and Math.multiplyExact guard 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.

From nouns to classes
The shop, the cart and the choice of deals become classes. A cart's owner, a product, the cart page's total, an order, a discount and what a sign-in did become records. Whether a promotion is an item deal or an order offer is the Scope enum. A promotion and the product catalog become interfaces. Six nouns are dropped. A price on a cart line is read from the Catalog every time. A customer is an id inside CartId, and a browser session is the guest id. The checkout page is a caller of placeOrder. There are no coupon codes, because the shop picks the deals. Payment and stock come after the order.The shop, the cart and the choice of deals become classes. A cart's owner, a product, the cart page's total, an order, a discount and what a sign-in did become records. Whether a promotion is an item deal or an order offer is the Scope enum. A promotion and the product catalog become interfaces. Six nouns are dropped. A price on a cart line is read from the Catalog every time. A customer is an id inside CartId, and a browser session is the guest id. The checkout page is a caller of placeOrder. There are no coupon codes, because the shop picks the deals. Payment and stock come after the order.
The cart keeps quantities. The price is dropped from it. The shop, the cart and the choice of deals become classes. A cart's owner, a product, the cart page's total, an order, a discount and what a sign-in did become records. Whether a promotion is an item deal or an order offer is the Scope enum. A promotion and the product catalog become interfaces. Six nouns are dropped. A price on a cart line is read from the Catalog every time. A customer is an id inside CartId, and a browser session is the guest id. The checkout page is a caller of placeOrder. There are no coupon codes, because the shop picks the deals. Payment and stock come after the order.

The noun that needs the most thought is the price on a cart line, because most first drafts store one.

Decision

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 and how they connect
ShoppingService owns every Cart and the placed orders, and uses the Catalog interface and PromotionEngine. PromotionEngine uses the Promotion interface, which three records implement. CentSplitter is a static helper that two of them call. Cart's methods are package-private, so only ShoppingService changes a cart. The records and the Scope enum along the bottom are the values the classes pass around. The two exceptions are not drawn.ShoppingService owns every Cart and the placed orders, and uses the Catalog interface and PromotionEngine. PromotionEngine uses the Promotion interface, which three records implement. CentSplitter is a static helper that two of them call. Cart's methods are package-private, so only ShoppingService changes a cart. The records and the Scope enum along the bottom are the values the classes pass around. The two exceptions are not drawn.
ShoppingService coordinates. Prices and promotions come from outside the cart. ShoppingService owns every Cart and the placed orders, and uses the Catalog interface and PromotionEngine. PromotionEngine uses the Promotion interface, which three records implement. CentSplitter is a static helper that two of them call. Cart's methods are package-private, so only ShoppingService changes a cart. The records and the Scope enum along the bottom are the values the classes pass around. The two exceptions are not drawn.

The classes fall into three groups:

  • Data: the records Product, PricedLine, Discount, Quote, QuotedLine, Order, CartId and MergeReport, and the enum Scope.
  • The core: ShoppingService and Cart. The service coordinates and holds each cart's lock.
  • Rules and outside systems: PromotionEngine, CentSplitter, the Promotion interface with its three records, and the Catalog interface.

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:

cart/ShoppingService.javalines 35–51 of 209
    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:

cart/ShoppingService.javalines 53–74 of 209
    /** 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

promotion/Promotion.javalines 7–14 of 14
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:

promotion/BuyXGetYFree.javalines 27–38 of 40
    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:

promotion/Scope.javalines 4–9 of 9
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.

Decision

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).

The biggest deal first, or every set
On the left, the biggest deal, KITCHEN30 at $13.80, goes first. It claims the mugs and the towels, so MUG3 and TOWEL2 are blocked, in red. The $72.20 left is over $60, so SAVE10 adds $10, and Asha saves $23.80. On the right, PromotionEngine leaves KITCHEN30 out. MUG3 and TOWEL2 save $17.00, the $69.00 left is still over $60, and SAVE10 adds $10, for $27.00. Below, SAVE10's $10.00 is shared over what is left on each line. Rounded down, the shares make 998 cents, and the 2 spare cents go to the two largest remainders, in amber.On the left, the biggest deal, KITCHEN30 at $13.80, goes first. It claims the mugs and the towels, so MUG3 and TOWEL2 are blocked, in red. The $72.20 left is over $60, so SAVE10 adds $10, and Asha saves $23.80. On the right, PromotionEngine leaves KITCHEN30 out. MUG3 and TOWEL2 save $17.00, the $69.00 left is still over $60, and SAVE10 adds $10, for $27.00. Below, SAVE10's $10.00 is shared over what is left on each line. Rounded down, the shares make 998 cents, and the 2 spare cents go to the two largest remainders, in amber.
The biggest single deal blocks two smaller ones that save more together. On the left, the biggest deal, KITCHEN30 at $13.80, goes first. It claims the mugs and the towels, so MUG3 and TOWEL2 are blocked, in red. The $72.20 left is over $60, so SAVE10 adds $10, and Asha saves $23.80. On the right, PromotionEngine leaves KITCHEN30 out. MUG3 and TOWEL2 save $17.00, the $69.00 left is still over $60, and SAVE10 adds $10, for $27.00. Below, SAVE10's $10.00 is shared over what is left on each line. Rounded down, the shares make 998 cents, and the 2 spare cents go to the two largest remainders, in amber.

bestFor first asks every item deal for its discount. Then Search tries every set of those discounts that share no product:

promotion/PromotionEngine.javalines 104–140 of 142
        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.

Decision

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:

promotion/CentSplitter.javalines 29–44 of 46
        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.

Decision

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:

cart/ShoppingService.javalines 169–183 of 209
    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:

Place order, after a price went up
Asha's phone gets version 3 at $59.00 (1). Staff raise the mug to $13 (2). placeOrder with that quote (3) locks Asha's cart, finds the version unchanged, and prices it again from the Catalog: $61.00. That is more than $59.00, so it throws PriceChangedException carrying the new quote, in amber, and places nothing. Asha confirms the $61.00 quote (4). $61.00 is not above $61.00, so ORD-1 is placed and the cart is emptied. When the phone sends the same call again (5), ShoppingService finds version 3 already placed and returns ORD-1 again.Asha's phone gets version 3 at $59.00 (1). Staff raise the mug to $13 (2). placeOrder with that quote (3) locks Asha's cart, finds the version unchanged, and prices it again from the Catalog: $61.00. That is more than $59.00, so it throws PriceChangedException carrying the new quote, in amber, and places nothing. Asha confirms the $61.00 quote (4). $61.00 is not above $61.00, so ORD-1 is placed and the cart is emptied. When the phone sends the same call again (5), ShoppingService finds version 3 already placed and returns ORD-1 again.
Checkout prices the cart again and compares totals. Asha's phone gets version 3 at $59.00 (1). Staff raise the mug to $13 (2). placeOrder with that quote (3) locks Asha's cart, finds the version unchanged, and prices it again from the Catalog: $61.00. That is more than $59.00, so it throws PriceChangedException carrying the new quote, in amber, and places nothing. Asha confirms the $61.00 quote (4). $61.00 is not above $61.00, so ORD-1 is placed and the cart is emptied. When the phone sends the same call again (5), ShoppingService finds version 3 already placed and returns ORD-1 again.
cart/ShoppingService.javalines 85–118 of 209
    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;        }    }
  1. 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.
  2. 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.
  3. Price it again (line 100), with today's prices and today's best promotions.
  4. 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.
  5. Ask if the total went up (lines 110 to 112). PriceChangedException carries the new quote. The app shows it, and the customer confirms by sending that quote back.
  6. 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.

Decision

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.

Decision

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.

Two carts become one
Asha's cart and the guest cart g-41 are both locked, Asha's first. Each guest item is checked against the catalog. Mugs: 2 + 2 is 4, over the limit of 3, so they are capped at 3, in amber. Towels: 0 + 2 is 2, merged, in purple. The lamp is no longer sold and is dropped, in red. Asha's cart becomes version 3 with 3 mugs, a kettle and 2 towels, and the guest cart is emptied in the same step. The MergeReport lists each case. A retried sign-in finds the guest cart empty and merges nothing. A towel added on the phone later stays in the guest cart and merges at the next sign-in.Asha's cart and the guest cart g-41 are both locked, Asha's first. Each guest item is checked against the catalog. Mugs: 2 + 2 is 4, over the limit of 3, so they are capped at 3, in amber. Towels: 0 + 2 is 2, merged, in purple. The lamp is no longer sold and is dropped, in red. Asha's cart becomes version 3 with 3 mugs, a kettle and 2 towels, and the guest cart is emptied in the same step. The MergeReport lists each case. A retried sign-in finds the guest cart empty and merges nothing. A towel added on the phone later stays in the guest cart and merges at the next sign-in.
Quantities add up to the limit. What is no longer sold is dropped. Asha's cart and the guest cart g-41 are both locked, Asha's first. Each guest item is checked against the catalog. Mugs: 2 + 2 is 4, over the limit of 3, so they are capped at 3, in amber. Towels: 0 + 2 is 2, merged, in purple. The lamp is no longer sold and is dropped, in red. Asha's cart becomes version 3 with 3 mugs, a kettle and 2 towels, and the guest cart is emptied in the same step. The MergeReport lists each case. A retried sign-in finds the guest cart empty and merges nothing. A towel added on the phone later stays in the guest cart and merges at the next sign-in.
cart/ShoppingService.javalines 121–156 of 209
    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.

Decision

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.

$ java demo.RaceCheck
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.

Decision

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.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Cart carries 1 and 8, Scope 2, PromotionEngine 3, CentSplitter 4, ShoppingService 5, Quote 6 and MergeReport 7. A purple tag marks Promotion as a Strategy.The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Cart carries 1 and 8, Scope 2, PromotionEngine 3, CentSplitter 4, ShoppingService 5, Quote 6 and MergeReport 7. A purple tag marks Promotion as a Strategy.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Cart carries 1 and 8, Scope 2, PromotionEngine 3, CentSplitter 4, ShoppingService 5, Quote 6 and MergeReport 7. A purple tag marks Promotion as a Strategy.
S.No.The questionWhat we choseWhy
1Does the cart keep each product's price?No: the cart keeps quantities, and every quote reads today's pricesThe catalog is the one place that knows a price
2Which promotions stack?One item deal per product, plus one order offer counted after the item dealsNo unit is discounted twice
3How does the shop choose among promotions?Try every set that obeys the stacking rules, with at most 12 promotionsThe best set by construction
4Where does an order-wide discount land?On each line by amount, with the spare cents going to the largest remaindersThe shares add up to the cent
5When does checkout ask the customer again?Only when the total goes upNo order is placed above the agreed total
6What makes a retried Place order safe?The quote's cart and version: ordersByAttempt returns the order already placed for themEvery retry of one quote gets one order
7How do the two carts merge?Add the quantities up to the limit, drop what is no longer sold, and report bothNothing the customer chose disappears silently
8Where do the locks go?A lock per cart, held while that cart is pricedOnly one customer's devices wait

Here is Asha's order from the demo, end to end:

  1. Her phone calls placeOrder with the version 3 quote at $59.00. ShoppingService takes her cart's lock, and ordersByAttempt holds nothing for version 3.
  2. The cart is still version 3, so price reads every product from Catalog.find and finds the mug at $13.
  3. PromotionEngine.bestFor runs Search and again picks MUG3, TOWEL2 and SAVE10. CentSplitter.split shares out the $10.
  4. $61.00 is more than $59.00, so placeOrder throws PriceChangedException and changes nothing.
  5. Her phone sends the $61.00 quote. placeOrder prices again, places ORD-1, stores it in ordersByAttempt and 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.

cartShoppingService.java
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());    }}
Click a class name in the code to open its fileJava · 209 lines · 1127 in the project

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:

$ java demo.Main
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 asksWhat changesWhat 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.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.