"Design Swiggy" in a low-level design round is not about maps or delivery times. A weak answer draws a Customer, a Restaurant, a DeliveryPartner and an Order with a status string, and stops. The names are right, but nothing about the order has been designed.
The interviewer is checking the order itself. A cart holds dishes from one restaurant, and a dish can sell out between the cart and the checkout. The bill adds items, a coupon, tax and a delivery fee, and it must come out exact to the cent. The order moves through fixed steps, and the customer and the restaurant may each cancel only at some of them, with different refunds. And a restaurant can tap Accept at the same moment the customer taps Cancel.
This article 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 one order mix restaurants? | No. A cart holds dishes from one restaurant | Cart remembers its restaurant and refuses a second one |
| Do dishes run out? | Yes. Each dish has a number of portions left for the day | Restaurant keeps a count per dish, and checkout takes portions |
| Can prices change during the day? | Yes | The cart holds no prices. The bill reads the menu at checkout |
| What goes on the bill? | Items, at most one coupon, 5% tax on the food, and a $2.99 delivery fee that is free from $25 of food | A BillCalculator, a Coupon interface, and money in exact cents |
| When is the customer charged? | At checkout, by card, through an outside card processor | A PaymentGateway interface, and refunds when an order is cancelled |
| Can the restaurant say no? | Yes. It can reject before accepting, and cancel any time before pickup | Who cancels is part of the order's record |
| Can the customer cancel? | Yes, for a full refund before the restaurant accepts. After that, until cooking starts, the restaurant keeps 20% of the food price | The order's states, and a CancellationFee rule |
| How is the courier chosen? | By a dispatch system outside this code | A CourierDispatcher interface. A courier is just an id |
| How many people act at once? | Many customers, and a restaurant and a customer can act on one order at the same moment | Each order and each restaurant guards its own state with a lock |
The question that matters most is "can the customer cancel?" The answer decides the order's states, what each cancel refunds, and the race at the heart of the design. If a cancel before acceptance is free and a cancel after it costs a fee, then the moment of acceptance decides how much money goes back. When the restaurant and the customer tap at the same instant, exactly one of them must be first.
Requirements
Functional:
- A customer adds dishes from one restaurant to a cart. A dish from a second restaurant is refused until the cart is cleared.
- Placing an order takes every portion in the cart, or none if any dish is short, and then charges the card. A failed checkout takes nothing and leaves the cart as it was.
- The bill is the item total, less one coupon, plus 5% tax on the food after the coupon, plus a $2.99 delivery fee that is free from $25 of food after the coupon. Every amount is exact to the cent.
- An order moves from placed to accepted, preparing, picked up and delivered. An outside dispatcher assigns the courier, and only that courier can pick up and deliver.
- The customer can cancel before acceptance for a full refund, and after it, until preparing starts, for everything except 20% of the food. The restaurant can cancel any time before pickup, with a full refund.
- Portions of a cancelled order go back on sale if cooking has not started.
- A refund that does not go through is kept and tried again, and no order is ever refunded twice.
Out of scope: live tracking and delivery times, choosing a courier, ratings, tips, scheduled orders, more than one coupon, and paying restaurants and couriers. 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.
What the code itself must handle:
- Two people on one order. The restaurant's tablet and the customer's phone call into the same order from different threads.
- Many customers on the last portions. Checkouts at one restaurant run at the same time.
- Outside systems that fail. The card processor can decline, or not answer, on a charge or a refund.
- Rules that change. Coupons and the cancellation fee each sit behind an interface.
Finding the classes
Picking the nouns out of the requirements gives a first list. Three of them, the order, the cart and the restaurant, hold state that changes and that several threads touch, so they become classes. The rules and the outside systems become interfaces.
Should a courier be a class?
A Courier class with a location, a status and a current order
It matches the courier app. But it pulls in the whole matching problem: who is free, who is nearest, and how two orders never get the same courier. Ride Sharing designs exactly that for drivers, and nothing about the order needs it.
No: a courier is an id, and choosing one is CourierDispatcher's jobOur pick
The order needs one fact: which courier may pick it up. Order keeps the courier's id, and the dispatch system, behind CourierDispatcher, decides who that is. If the interviewer wants matching inside this design, the driver claim from Ride Sharing moves in behind the same interface.
Data or behaviour?
Some classes only carry values and never change: an amount of money, a dish on the menu, a line on an order, a bill. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. Order, Cart and Restaurant are ordinary classes, because their state changes and their methods guard those changes.
The class diagram
The classes fall into three groups:
- Data: the records
Money,Bill,OrderLine,MenuItem,CartContentsand the privatePendingRefund, and the enumsOrderStatus,PartyandRefundStatus. - The core:
FoodDeliveryService,Order,CartandRestaurant. The service coordinates. The other three each guard their own state with their own lock. - Rules and outside systems:
BillCalculatorand the interfacesCoupon,CancellationFee,PaymentGatewayandCourierDispatcher.
Building it
Money and the bill
A bill is a sum of parts, a percentage off, and a percentage of tax. The receipt and the card charge must agree to the cent, so Money is a record holding a whole number of cents in a long, as in Ride Sharing. It refuses negative amounts, and plus and times use Math.addExact and Math.multiplyExact, so an overflow throws instead of wrapping. One method divides:
/** This amount times numerator / denominator, rounded half up to the nearest cent. */ public Money times(long numerator, long denominator) { if (numerator < 0 || denominator <= 0) { throw new IllegalArgumentException("Cannot scale money by " + numerator + "/" + denominator); } long product = Math.multiplyExact(cents, numerator); return new Money(Math.addExact(product, denominator / 2) / denominator); }times multiplies first and divides once, rounding half up. Tax at 5% is times(500, 10_000), in basis points, so a rate like 2.75% needs no fractions either.
BillCalculator turns the order's lines and a coupon into a Bill:
public Bill billFor(List<OrderLine> lines, Coupon coupon) { Objects.requireNonNull(coupon, "coupon"); if (lines.isEmpty()) { throw new IllegalArgumentException("A bill needs at least one line"); } Money itemTotal = Money.ZERO; for (OrderLine line : lines) { itemTotal = itemTotal.plus(line.total()); } if (itemTotal.isLessThan(coupon.minimumOrder())) { throw new ActionNotAllowedException(coupon.code() + " needs at least " + coupon.minimumOrder() + " of food"); } Money discount = coupon.discountFor(itemTotal).min(itemTotal); Money food = itemTotal.minus(discount); // Tax is on what the customer pays for the food, rounded once for the whole order. Money tax = food.times(taxBasisPoints, 10_000); Money delivery = food.isLessThan(freeDeliveryFrom) ? deliveryFee : Money.ZERO; return new Bill(itemTotal, discount, tax, delivery); }The steps run in a fixed order. The item total is the sum of the lines. A coupon below its minimum is refused with a message for the customer, so a coupon they picked is never dropped without a word. The discount comes off the item total, and never more than it. Tax is 5% of what is left, rounded once for the whole order. Delivery is free once that same amount reaches $25.
Asha's order from the demo is two paneer tikka at $8.49 and three garlic naan at $1.99:
| Line | How | Amount |
|---|---|---|
| Items | 2 × $8.49 + 3 × $1.99 | $22.95 |
| Coupon SAVE20 | 20% of $22.95 is $4.59, capped at $4.00 | -$4.00 |
| Tax | 5% of $18.95 is 94.75 cents, rounded half up | $0.95 |
| Delivery | $18.95 is below $25 | $2.99 |
| Total | $22.89 |
Is tax calculated before or after the coupon?
On the item total, before the coupon
It is simple, and the tax does not move when a coupon is added. But the customer pays tax on $22.95 of food they are buying for $18.95. A $10 coupon on a $10 order would leave tax on food that cost nothing.
Per line, after the coupon is shared across the lines
Each dish gets its own tax, which some invoices need. But sharing $4.00 across lines needs its own rounding, and three lines of 2.5 cents round to 9 cents where the whole order rounds to 8.
On the food after the coupon, rounded once for the orderOur pick
Tax follows what the customer pays for the food. There is one rounding step for tax, so the bill is easy to check by hand. The cost is that a coupon also lowers the tax, which the business accepts.
Coupons
/** One discount on the item total. An order uses one coupon, or NONE. */public interface Coupon { /** No coupon: nothing off and no minimum, so the bill needs no special case. */ Coupon NONE = new FlatOffCoupon("NONE", Money.ZERO, Money.ZERO); String code(); /** The smallest item total this coupon may be used on. */ Money minimumOrder(); Money discountFor(Money itemTotal);}PercentOffCoupon takes 20% up to a cap, and FlatOffCoupon takes $3 off. Both are records, because a coupon is a fixed offer. Line 6 holds the answer to "what if there is no coupon?"
The cart
A cart holds the restaurant, a quantity for each dish id, and a flag that is set while an order is placed from it:
class Cart { private Restaurant restaurant; private final Map<String, Integer> quantities = new LinkedHashMap<>(); private boolean checkingOut; synchronized void add(Restaurant from, String itemId, int quantity) { requireEditable(); if (restaurant != null && restaurant != from) { throw new DifferentRestaurantException(restaurant.name(), from.name()); } quantities.merge(itemId, quantity, Math::addExact); restaurant = from; }add refuses a dish from a second restaurant with a DifferentRestaurantException. The app shows its message and offers to clear the cart. Removing the last dish, or clearing the cart, frees it for any restaurant. FoodDeliveryService.addToCart checks that the dish is on that restaurant's menu before it reaches the cart.
Can one cart hold dishes from two restaurants?
Yes, and the order splits into one order per restaurant
The customer gets everything in one go. But one checkout now holds stock at two restaurants and charges once for two orders. If the second restaurant rejects, half the order is cancelled, and two couriers arrive at different times.
Yes, and silently replace the cart
It needs no prompt. But a customer who taps one dish from another restaurant loses a full cart without warning.
No: refuse, and let the app offer to clear the cartOur pick
One order means one restaurant, one kitchen, one courier and one refund. The refusal is a message to the person, and the app turns it into a "start a new cart?" prompt. Mixed orders are a follow-up.
Stock
Each Restaurant keeps its menu and a count of portions left for each dish, and its own lock guards both. Checkout reserves a whole cart in one call:
/** Takes every portion asked for, or none, and prices each line at today's menu price. */ public synchronized List<OrderLine> reserve(Map<String, Integer> quantities) { if (quantities.isEmpty()) { throw new IllegalArgumentException("Nothing to reserve"); } List<String> soldOut = new ArrayList<>(); for (Map.Entry<String, Integer> wanted : quantities.entrySet()) { MenuItem item = known(wanted.getKey()); if (wanted.getValue() <= 0) { throw new IllegalArgumentException("Quantity must be positive: " + wanted); } if (portionsLeft.get(item.id()) < wanted.getValue()) { soldOut.add(item.name()); } } if (!soldOut.isEmpty()) { throw new OutOfStockException(name, soldOut); } List<OrderLine> lines = new ArrayList<>(); for (Map.Entry<String, Integer> wanted : quantities.entrySet()) { MenuItem item = menu.get(wanted.getKey()); portionsLeft.merge(item.id(), -wanted.getValue(), Integer::sum); lines.add(new OrderLine(item.id(), item.name(), item.price(), wanted.getValue())); } return List.copyOf(lines); }reserve is synchronized, so the check and the take happen as one step. The first loop finds every dish that is short and changes nothing. If any dish is short, it throws an OutOfStockException that names them all, so the customer can fix the cart in one go. Only when every dish fits does the second loop take the portions and build each OrderLine at today's price. The price is read under the same lock as the stock, so a price change cannot land halfway through a reservation.
Does adding to the cart hold stock?
Yes: adding a dish reserves a portion until checkout or a timeout
The customer never meets "sold out" at checkout. But carts are cheap to fill and often left behind, so the last biryani sits in a forgotten cart while paying customers are turned away. It also needs a timer to give the portions back.
No: the portions are taken at checkout, all or noneOur pick
The cart costs nothing to fill, and stock changes in one place, reserve, under one lock. The cost is that a dish can sell out between the cart and the checkout. When it does, the customer sees which dish and edits the cart, which is the "out of stock" screen these apps already have.
Placing an order
placeOrder freezes the cart, and checkout does the work:
public Order placeOrder(String customerId, Coupon coupon) { Objects.requireNonNull(coupon, "coupon"); Cart cart = cartOf(customerId); CartContents contents = cart.beginCheckout(); Order order = null; try { order = checkout(customerId, contents, coupon); return order; } finally { cart.endCheckout(order != null); } } private Order checkout(String customerId, CartContents contents, Coupon coupon) { Restaurant restaurant = restaurant(contents.restaurantId()); List<OrderLine> lines = restaurant.reserve(contents.quantities()); boolean paid = false; try { Bill bill = bills.billFor(lines, coupon); String orderId = "O-" + orderCounter.incrementAndGet(); Order order = new Order(orderId, UUID.randomUUID().toString(), customerId, restaurant.id(), lines, bill); charge(order); paid = true; orders.put(order.id(), order); return order; } finally { if (!paid) { restaurant.release(lines); } } }- Freeze the cart with
beginCheckout(line 87). A second tap on Place order, or an edit from another phone, is refused until this one finishes. Without the freeze, a double tap would take the portions twice and charge twice. - Take the portions with
reserve(line 99). If anything is short, it throws, and nothing was taken. - Bill and charge (lines 102 to 106).
chargethrows aPaymentFailedExceptionif the card is declined or the card processor does not answer. - Give back the portions if the order was not paid (lines 110 to 112). The
finallyblock runs whether the coupon was refused, the card declined, or something threw. - Empty or unfreeze the cart (line 93). A placed order empties it. Any failure leaves it as it was, ready to fix.
Each order gets two ids. O-1 is the number people read, and it starts again after a restart. The payment key is a random UUID, so it never repeats, and the card processor never mixes up two orders. BookMyShow gives a hold the same two ids for the same reason. The order number is taken before the charge, so a declined attempt uses one up. That is why the demo never places an O-3. Messages for the customer, such as sold out, a coupon under its minimum or a declined card, are ActionNotAllowedException and its subclasses. A programmer's mistake, such as a quantity of zero or an unknown dish, throws IllegalArgumentException.
Is stock taken before or after the charge?
Charge first, then take the stock
The card is checked before any stock moves. But if the last portion went to someone else during the charge, the customer is charged and then refunded, and a refund can take days to show on a card.
Take the stock first, release it if the charge failsOur pick
A customer is only charged for food that is set aside for them. A declined card costs a moment of held stock, and the finally block gives it back. The cost is that another customer can be told "sold out" for a portion that is about to come back.
The order's lifecycle
Once paid, an order moves forward through five states, or ends in a sixth, CANCELLED. Each forward move is allowed in exactly one state. Cancels are the hard part, because they are allowed in three states, and who may cancel and what comes back depend on the state.
| State | accept | startPreparing | pickUp | deliver | customer cancels | restaurant cancels |
|---|---|---|---|---|---|---|
PLACED | to ACCEPTED | refused | refused | refused | full refund | full refund (a reject) |
ACCEPTED | refused | to PREPARING | refused | refused | all but 20% of the food | full refund |
PREPARING | refused | refused | to PICKED_UP | refused | refused | full refund |
PICKED_UP | refused | refused | refused | to DELIVERED | refused | refused |
DELIVERED | refused | refused | refused | refused | refused | refused |
CANCELLED | refused | refused | refused | refused | refused | refused |
Every allowed cancel moves the order to CANCELLED. Each move is a synchronized method on Order that checks the state first, and cancel is the longest:
/** Cancels the order and fixes the refund. Returns the status the order was cancelled from. */ synchronized OrderStatus cancel(Party by, CancellationFee fee) { Objects.requireNonNull(by, "by"); OrderStatus from = status; if (!mayCancel(by, from)) { throw new ActionNotAllowedException("The " + by.name().toLowerCase() + " cannot cancel " + id + ": it is " + from); } Money total = bill.total(); Money kept = Money.ZERO; if (by == Party.CUSTOMER && from == OrderStatus.ACCEPTED) { kept = fee.feeFor(bill).min(total); } refund = total.minus(kept); refundStatus = refund.isZero() ? RefundStatus.NONE : RefundStatus.PENDING; cancelledBy = by; status = OrderStatus.CANCELLED; return from; } synchronized void markRefunded() { if (refundStatus == RefundStatus.PENDING) { refundStatus = RefundStatus.REFUNDED; } } private static boolean mayCancel(Party by, OrderStatus from) { return switch (from) { case PLACED, ACCEPTED -> true; case PREPARING -> by == Party.RESTAURANT; case PICKED_UP, DELIVERED, CANCELLED -> false; }; }cancel reads the state once, into from, and mayCancel decides from the table. Only a customer cancelling from ACCEPTED pays a fee, and the fee is never more than the total. The refund is fixed and the state set to CANCELLED under the order's lock. A refused move throws ActionNotAllowedException, whose message the app shows.
Then FoodDeliveryService.cancel does the work that touches other objects, after the order's lock is released:
public Order cancel(String orderId, Party by) { Order order = order(orderId); OrderStatus from = order.cancel(by, cancellationFee); if (from == OrderStatus.PLACED || from == OrderStatus.ACCEPTED) { // Nothing has been cooked yet, so the portions go back on sale. restaurant(order.restaurantId()).release(order.lines()); } if (order.courierId().isPresent()) { releaseCourier(orderId); } if (!order.refund().isZero()) { // Written down before the call, so a refund that fails is retried, never forgotten. PendingRefund refund = new PendingRefund(order, order.refund()); pendingRefunds.put(order.paymentKey(), refund); sendRefund(order.paymentKey(), refund); } return order; }The portions go back if the order was cancelled from PLACED or ACCEPTED. A courier is released only if one was assigned. Then the refund is written down and sent, which the section on money below covers.
Can the customer cancel once the restaurant accepts?
No: once accepted, the order stands
The restaurant never loses an accepted order. But a customer who taps Cancel one second after acceptance has no way out, even though nothing has been cooked.
Yes, any time before pickup, for a full refund
The customer is always safe. But the restaurant cooks food it is never paid for, and the food is wasted.
Yes, until preparing starts, and the restaurant keeps 20% of the foodOur pick
Before cooking, the portions can still be sold, so they go back on sale and most of the money goes back. Once cooking starts, only the restaurant can cancel. The cost is that the refund now depends on which state the cancel finds, which is the race in the next section.
The courier fits around these states. accept asks CourierDispatcher for a courier, outside the order's lock, and the dispatch system answers through courierAssigned. Order.assignCourier takes the first courier while the order is ACCEPTED or PREPARING. It answers true again if the same courier is sent twice while the order is still live, and false in every other case, after which the dispatcher frees that courier. So a courier sent to an order that was cancelled or delivered a moment earlier is turned down, not lost. pickUp and deliver check that the caller is the assigned courier.
The dispatch system can fail like the card processor. A request or a release that throws is logged and put in courierRequestsToRetry or courierReleasesToRetry, and the order carries on. retryDispatch, called by a timer like retryRefunds, sends each one again. It drops a request whose order no longer needs a courier, such as one cancelled in the meantime. A call that threw may still have landed, so a retried request can bring a second courier, and courierAssigned turns that one down.
Accept and cancel at the same moment
Spice Route's tablet taps Accept on O-1 at the same moment Asha taps Cancel. Both calls arrive on different threads.
synchronized void accept() { require(OrderStatus.PLACED, "accept"); status = OrderStatus.ACCEPTED; }accept and cancel are both synchronized on the same Order, so they run one after the other. Each checks the state when it runs, so either the cancel wins and the accept is refused, or the accept wins and the cancel finds ACCEPTED. Either way, the refund matches the order of events.
The project includes a check, demo/RaceCheck.java. It places 1,000 orders and sends each an accept and a cancel at the same moment, with a barrier that starts the two together. Then it has 200 customers order the last 50 thalis at once:
1000 orders, each accepted and cancelled at the same moment by 16 threads Cancel first, accept refused, full refund: 545 Accept first, then cancel with the fee kept: 455 Accepted and still fully refunded: 0 200 customers order the last 50 thalis at once: 50 placed, 150 refused, 0 left, 50 cards charged
The split between "cancel first" and "accept first" changes from run to run, but no order was both accepted and fully refunded. Exactly 50 thalis were sold and 50 cards charged. We also ran it in a scratch copy with synchronized removed from accept and cancel. Every run we tried left a few orders accepted and fully refunded. With synchronized removed from reserve instead, every run we tried sold more than 50 thalis. The exact numbers change from machine to machine.
Where do the locks go?
One lock on the whole FoodDeliveryService
It is correct and easy to explain. But every customer in the city waits while one checkout talks to the card processor, which can take seconds.
A lock per order and a lock per restaurant, never held during an outside callOur pick
The order's lock covers its state, and the restaurant's lock covers its stock and prices. A move on one order never waits for another order, and checkouts at different restaurants never wait for each other. The card processor and the dispatcher are always called with no lock held, so a slow bank never blocks a tablet. No method holds two of these locks at once, so they cannot deadlock. The cost is that cancel gives the portions back a moment after the state changes, not in the same step.
When money has to go back
BookMyShow covers the two rules underneath this: a timeout is not a decline, and a refund is retried with the same key. Here money goes back in two cases, a cancel and a charge that got no answer, and both end in one map, pendingRefunds:
private void charge(Order order) { Money total = order.bill().total(); if (total.isZero()) { return; } boolean approved; try { approved = payments.charge(order.customerId(), total, order.paymentKey()); } catch (RuntimeException e) { // No answer: the card may have been charged, so the key waits for a refund. LOG.log(System.Logger.Level.WARNING, "Charge for " + order.id() + " got no answer", e); pendingRefunds.put(order.paymentKey(), new PendingRefund(order, total)); throw PaymentFailedException.unconfirmed(order.id(), total); } if (!approved) { throw PaymentFailedException.declined(order.id(), total); } } private void sendRefund(String key, PendingRefund refund) { boolean done; try { done = payments.refund(key, refund.amount()); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Refund for " + refund.order().id() + " got no answer", e); done = false; } if (done && pendingRefunds.remove(key, refund)) { refund.order().markRefunded(); } }A cancel writes its refund into pendingRefunds and then sends it, as shown above. If the card processor returns false or throws, the entry stays, and the order's RefundStatus stays PENDING. retryRefunds, which a timer or a support tool calls, sends every entry again with the same key. Only a refund that goes through removes the entry and marks the order REFUNDED.
A charge with no answer only queues its refund (lines 203 to 207). The customer is not kept waiting for a second bank call, and is told "we could not confirm the payment; anything taken will be refunded", not that the card was declined. The next retryRefunds sends it. This relies on the PaymentGateway contract:
/** The card processor, outside our code. The key is the order's payment key, a random UUID. */public interface PaymentGateway { /** * Charges the customer's card. Returns false if the card is declined, and throws if * there is no answer. A key that was charged is never charged again. */ boolean charge(String customerId, Money amount, String key); /** * Gives back what was charged with this key, at most once. A refunded key can never be * charged, and a key that was never charged needs nothing back, so the answer is true. * Returns false or throws if the refund did not go through. */ boolean refund(String key, Money amount);}A key is charged at most once and refunded at most once. Once refunded it can never be charged, and refunding a key that was never charged moves no money. If the charge is still on its way when the refund arrives, the card processor refuses it when it lands, because its key is already refunded. So a timeout ends with Asha either never charged or charged and refunded, and never charged twice. Here refund also does the job of BookMyShow's reverse: for a key that was never charged, it blocks the key.
Charge at checkout, or only authorise until the restaurant accepts?
Hold the amount on the card at checkout, and take it when the restaurant accepts
A reject then costs nothing, because the hold just ends. But the gateway needs two steps, holds expire, and accepting an order now waits on a bank call.
Charge at checkout, and refund on a cancelOur pick
The order is paid before the restaurant sees it, so a restaurant never cooks an unpaid order and accepting is one local step. The cost is that a reject is a real refund, which can fail and takes days to reach the card, so refunds need the retry path above.
A refund call fails. What happens?
Undo the cancel
The order and the money agree. But a restaurant that rejected the order would find it back on its tablet, and a customer who cancelled would be told no because of a bank outage.
Log the failure and move on
Nothing blocks. But the customer paid, has no food, and nobody remembers the refund.
The cancel stands, and the refund waits in pendingRefunds to be retried with the same keyOur pick
The cancel is about the food, and the refund is about the money, so a bank outage changes only the money. The refund is written down before the call, so a timeout or an exception cannot lose it. pendingRefunds lives in memory here. In production, the refund row is written in the same transaction as the cancel, so a crash cannot lose it either. For the same reason, production writes the payment attempt before the charge, or a crash between the charge and pendingRefunds.put would lose it. The same key means a retry after a lost answer never refunds twice.
The final design
FoodDeliveryService is the core. It owns every cart, order and restaurant, and the refunds and courier calls still to retry. It reaches coupons, the cancellation fee, the card processor and the courier system only through interfaces, and BillCalculator does the arithmetic of the bill. Order and Restaurant each guard their own state with their own lock, and no lock is held while an outside system is called.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should a courier be a class? | No: a courier is an id, and choosing one is CourierDispatcher's job | The order only needs to know which courier may pick it up |
| 2 | Is tax calculated before or after the coupon? | On the food after the coupon, rounded once for the order | Tax follows what the customer pays |
| 3 | Can one cart hold dishes from two restaurants? | No: refuse, and let the app offer to clear the cart | One order is one kitchen, one courier and one refund |
| 4 | Does adding to the cart hold stock? | No: the portions are taken at checkout, all or none | Abandoned carts never hold food |
| 5 | Is stock taken before or after the charge? | Take the stock first, release it if the charge fails | Nobody pays for food that was not set aside |
| 6 | Can the customer cancel once the restaurant accepts? | Yes, until preparing starts, and the restaurant keeps 20% of the food | Uncooked food can still be sold |
| 7 | Where do the locks go? | A lock per order and a lock per restaurant, never held during an outside call | A slow bank never blocks a tablet |
| 8 | Charge at checkout, or only authorise until the restaurant accepts? | Charge at checkout, and refund on a cancel | Accepting stays one local step |
| 9 | A refund call fails. What happens? | The cancel stands, and the refund waits in pendingRefunds to be retried with the same key | A failed refund is kept and retried, and never paid twice |
Here is Asha's order from the demo, end to end:
- Asha's phone calls
placeOrderwithSAVE20.Cart.beginCheckoutfreezes her cart under the cart's lock. Restaurant.reservetakes two paneer tikka and three naan under Spice Route's lock, and prices the lines.BillCalculator.billForasksSAVE20for its discount and fixes the total at $22.89, exact to the cent.PaymentGateway.chargecharges $22.89 withO-1's payment key. This is the outside call, and no lock is held during it.O-1is stored andCart.endCheckoutempties the cart.- The tablet calls
accept.Order.acceptmovesO-1toACCEPTEDunder the order's lock, andCourierDispatcher.requestCourieris called after it is released.
A cancel takes the other path. cancel calls Order.cancel, which reads the state under the order's lock, checks it against the table, and fixes the refund with CancellationFee.feeFor. With that lock released, Restaurant.release puts uncooked portions back on sale and CourierDispatcher.release frees an assigned courier. Last, cancel writes the refund into pendingRefunds and only then calls PaymentGateway.refund with the order's payment key.
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 order; import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import billing.Bill;import billing.BillCalculator;import billing.CancellationFee;import billing.Coupon;import billing.Money;import delivery.CourierDispatcher;import exception.PaymentFailedException;import payment.PaymentGateway;import restaurant.OrderLine;import restaurant.Restaurant; public class FoodDeliveryService { private static final System.Logger LOG = System.getLogger(FoodDeliveryService.class.getName()); private final BillCalculator bills; private final CancellationFee cancellationFee; private final PaymentGateway payments; private final CourierDispatcher dispatcher; private final Map<String, Restaurant> restaurants = new ConcurrentHashMap<>(); private final Map<String, Cart> carts = new ConcurrentHashMap<>(); private final Map<String, Order> orders = new ConcurrentHashMap<>(); private final Map<String, PendingRefund> pendingRefunds = new ConcurrentHashMap<>(); private final Set<String> courierRequestsToRetry = ConcurrentHashMap.newKeySet(); private final Set<String> courierReleasesToRetry = ConcurrentHashMap.newKeySet(); private final AtomicLong orderCounter = new AtomicLong(); /** A refund still to send. The order may never have been placed, if its charge got no answer. */ private record PendingRefund(Order order, Money amount) { } public FoodDeliveryService(BillCalculator bills, CancellationFee cancellationFee, PaymentGateway payments, CourierDispatcher dispatcher) { this.bills = Objects.requireNonNull(bills, "bills"); this.cancellationFee = Objects.requireNonNull(cancellationFee, "cancellationFee"); this.payments = Objects.requireNonNull(payments, "payments"); this.dispatcher = Objects.requireNonNull(dispatcher, "dispatcher"); } public void addRestaurant(Restaurant restaurant) { if (restaurants.putIfAbsent(restaurant.id(), restaurant) != null) { throw new IllegalArgumentException("Restaurant " + restaurant.id() + " is already added"); } } public void addToCart(String customerId, String restaurantId, String itemId, int quantity) { if (quantity <= 0) { throw new IllegalArgumentException("Quantity must be positive: " + quantity); } Restaurant restaurant = restaurant(restaurantId); if (restaurant.item(itemId).isEmpty()) { throw new IllegalArgumentException("No dish " + itemId + " at " + restaurant.name()); } cartOf(customerId).add(restaurant, itemId, quantity); } public void removeFromCart(String customerId, String itemId) { cartOf(customerId).remove(itemId); } public void clearCart(String customerId) { cartOf(customerId).clear(); } public Optional<CartContents> cart(String customerId) { return cartOf(customerId).contents(); } public Order placeOrder(String customerId) { return placeOrder(customerId, Coupon.NONE); } public Order placeOrder(String customerId, Coupon coupon) { Objects.requireNonNull(coupon, "coupon"); Cart cart = cartOf(customerId); CartContents contents = cart.beginCheckout(); Order order = null; try { order = checkout(customerId, contents, coupon); return order; } finally { cart.endCheckout(order != null); } } private Order checkout(String customerId, CartContents contents, Coupon coupon) { Restaurant restaurant = restaurant(contents.restaurantId()); List<OrderLine> lines = restaurant.reserve(contents.quantities()); boolean paid = false; try { Bill bill = bills.billFor(lines, coupon); String orderId = "O-" + orderCounter.incrementAndGet(); Order order = new Order(orderId, UUID.randomUUID().toString(), customerId, restaurant.id(), lines, bill); charge(order); paid = true; orders.put(order.id(), order); return order; } finally { if (!paid) { restaurant.release(lines); } } } public Order accept(String orderId) { Order order = order(orderId); order.accept(); // Outside the order's lock: the dispatcher is another system and may be slow. requestCourier(order); return order; } public Order startPreparing(String orderId) { Order order = order(orderId); order.startPreparing(); return order; } /** The dispatcher's answer. False means the order does not want this courier. */ public boolean courierAssigned(String orderId, String courierId) { return order(orderId).assignCourier(courierId); } public Order pickUp(String orderId, String courierId) { Order order = order(orderId); order.pickUp(courierId); return order; } public Order deliver(String orderId, String courierId) { Order order = order(orderId); order.deliver(courierId); releaseCourier(orderId); return order; } public Order cancel(String orderId, Party by) { Order order = order(orderId); OrderStatus from = order.cancel(by, cancellationFee); if (from == OrderStatus.PLACED || from == OrderStatus.ACCEPTED) { // Nothing has been cooked yet, so the portions go back on sale. restaurant(order.restaurantId()).release(order.lines()); } if (order.courierId().isPresent()) { releaseCourier(orderId); } if (!order.refund().isZero()) { // Written down before the call, so a refund that fails is retried, never forgotten. PendingRefund refund = new PendingRefund(order, order.refund()); pendingRefunds.put(order.paymentKey(), refund); sendRefund(order.paymentKey(), refund); } return order; } /** Tries every refund that has not gone through yet. Returns how many are still pending. */ public int retryRefunds() { for (Map.Entry<String, PendingRefund> pending : pendingRefunds.entrySet()) { sendRefund(pending.getKey(), pending.getValue()); } return pendingRefunds.size(); } /** Tries every call to the courier system that failed. Returns how many are still waiting. */ public int retryDispatch() { for (String orderId : courierRequestsToRetry) { Order order = order(orderId); if (!order.needsCourier()) { courierRequestsToRetry.remove(orderId); continue; } if (callDispatcher(() -> dispatcher.requestCourier(orderId, order.restaurantId()))) { courierRequestsToRetry.remove(orderId); } } for (String orderId : courierReleasesToRetry) { if (callDispatcher(() -> dispatcher.release(orderId))) { courierReleasesToRetry.remove(orderId); } } return courierRequestsToRetry.size() + courierReleasesToRetry.size(); } private void charge(Order order) { Money total = order.bill().total(); if (total.isZero()) { return; } boolean approved; try { approved = payments.charge(order.customerId(), total, order.paymentKey()); } catch (RuntimeException e) { // No answer: the card may have been charged, so the key waits for a refund. LOG.log(System.Logger.Level.WARNING, "Charge for " + order.id() + " got no answer", e); pendingRefunds.put(order.paymentKey(), new PendingRefund(order, total)); throw PaymentFailedException.unconfirmed(order.id(), total); } if (!approved) { throw PaymentFailedException.declined(order.id(), total); } } private void sendRefund(String key, PendingRefund refund) { boolean done; try { done = payments.refund(key, refund.amount()); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Refund for " + refund.order().id() + " got no answer", e); done = false; } if (done && pendingRefunds.remove(key, refund)) { refund.order().markRefunded(); } } private void requestCourier(Order order) { if (!callDispatcher(() -> dispatcher.requestCourier(order.id(), order.restaurantId()))) { courierRequestsToRetry.add(order.id()); } } private void releaseCourier(String orderId) { if (!callDispatcher(() -> dispatcher.release(orderId))) { courierReleasesToRetry.add(orderId); } } // The courier system is outside code: a failure is logged and retried, and never fails the order. private boolean callDispatcher(Runnable call) { try { call.run(); return true; } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "The courier system did not answer", e); return false; } } public Order order(String orderId) { Order order = orders.get(orderId); if (order == null) { throw new IllegalArgumentException("No order " + orderId); } return order; } private Restaurant restaurant(String restaurantId) { Restaurant restaurant = restaurants.get(restaurantId); if (restaurant == null) { throw new IllegalArgumentException("No restaurant " + restaurantId); } return restaurant; } private Cart cartOf(String customerId) { Objects.requireNonNull(customerId, "customerId"); return carts.computeIfAbsent(customerId, id -> new Cart()); }}demo/Main.java runs one evening at Spice Route, which has a single chicken biryani left. Asha orders with a coupon, Ben gets the biryani, and Dev's card is declined. Spice Route rejects Ben's paid order while the card processor is not answering. Then Chen cancels after acceptance, and Dev tries again:
Spice Route has 1 Chicken biryani left. Delivery is $2.99, free from $25 of food. Tax is 5%.
Asha adds 2 Paneer tikka and 3 Garlic naan
Asha adds a Masala dosa: refused. Your cart has dishes from Spice Route. Clear it to order from Dosa Corner
Asha orders with SAVE20: O-1, items $22.95, coupon -$4.00, tax $0.95, delivery $2.99, total $22.89
Ben orders the last Chicken biryani: O-2, total $14.80
Chen orders a Chicken biryani: refused. Not enough left at Spice Route: Chicken biryani
Dev orders 2 Mango lassi: refused. Payment of $10.34 for O-3 was declined
Mango lassi left: 20. Dev's cart still has {lassi=2}
Spice Route accepts O-1. The dispatcher sends Ravi: true
Spice Route rejects O-2: refund $14.80 is PENDING. Chicken biryani left: 1
The card processor answers again. Refunds pending: 0. O-2 is REFUNDED
Chen orders again: O-4, total $14.80. Spice Route accepts it
Chen cancels O-4 after it was accepted: refund $12.55 of $14.80, biryani left: 1
Asha cancels O-1 while it is PREPARING: refused. The customer cannot cancel O-1: it is PREPARING
Ravi picks up O-1 and delivers it: DELIVERED
Dev adds 3 Paneer tikka to the 2 Mango lassi in his cart and orders with FLAT3: O-5, items $32.47, coupon -$3.00, tax $1.47, delivery $0.00, total $30.94Notice three things in the output. Chen's first order was refused while Ben held the last biryani, and after Spice Route rejected Ben's order the same portion went to Chen as O-4. Ben's $14.80 refund stayed PENDING while the card processor was down, and the retry made it REFUNDED. And Dev's last order shows both rules on the $25 line. His $32.47 is the 3 paneer tikka at $25.47 plus the 2 mango lassi still in his cart from the declined attempt. Less a $3.00 coupon, that is $29.47 of food, so delivery is free, and tax is 5% of $29.47, rounded to $1.47.
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 |
|---|---|---|
| "Reject an order no one accepts in five minutes." | A timer calls cancel with Party.RESTAURANT after five minutes. The service takes a Clock, and Order records when it was placed. | The state table, refunds and stock. |
| "Let customers use two coupons." | billFor takes a list of coupons and applies them in a fixed order, each on what the last one left. | Order, refunds and payment. |
| "Order from two restaurants at once." | A checkout makes one Order per restaurant under one charge key per order, and reserves at both restaurants. If the second restaurant is short, the checkout releases the first. Cart holds a map per restaurant. | Order's states, the bill per order. |
| "Choose the courier ourselves." | A matching class behind CourierDispatcher, with the driver claim from Ride Sharing. | Order, which still only stores the courier's id. |
| "Show live order updates." | A listener list on Order, called after its lock is released. | Checkout, pricing and refunds. |
| "Add-ons, such as extra cheese." | CartContents keys a line by dish and add-ons, and OrderLine carries the add-on prices. reserve checks add-on stock too. | The bill's steps, the states and refunds. |
| "Let customers tip the courier." | A tip line on Bill, outside the tax. The cancellation refund includes the tip in full. | The states, stock and courier rules. |
| "Charge more for delivery when it rains." | The delivery fee moves behind an interface, like Coupon, given the weather at checkout. | Everything after the bill. |
| "Pay the restaurant and the courier." | A payout ledger written when an order is delivered or cancelled with a fee. | Checkout and the order's states. |
In most rows the change lands in a rule, a new record field, or a class beside the core, and Order's state table stays as it is. Two rows are bigger: an order across two restaurants changes the cart and the checkout, and a timer brings time into a design that has none today.
What the interviewer looks for
Mid-level
A mid-level candidate shows clear classes for the order, the cart and the restaurant, an enum for the order's states, a cart limited to one restaurant, and money in integer cents. They say that two customers can race for the last portion and that a lock is needed, even if the lock covers more than it has to.
Senior
A senior candidate shows everything above and gives the reasons. They draw the state table with who may cancel in each state and what comes back. They reserve stock all or nothing before the charge and give it back on every failure. They put accept and cancel under the order's lock and keep outside calls out of it. They fix the order of coupon, tax and delivery on the bill.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They raise these cases: a charge that times out, a refund that fails, a courier sent to an order that was just cancelled. They explain how a payment key that never repeats keeps every retry safe, and when holding the amount on the card would beat charging it.
Common mistakes
- A status string with no rules. Any screen can then set any state, and a delivered order can be cancelled.
- Checking the state, then changing it, without a lock. An accept and a cancel can both see
PLACED, and the kitchen cooks an order that was refunded in full. - Taking stock dish by dish. If the third dish is short, the first two stay taken by an order that never happens.
- Prices stored in the cart. The bill then charges yesterday's price, or the receipt disagrees with the menu.
doublefor money, or tax rounded per line. The total drifts by a cent, and the receipt disagrees with the charge.- Calling the card processor while holding a lock. One slow bank then blocks every tablet that touches that order or restaurant.
- Forgetting a refund that failed. The customer has paid, has no food, and nobody remembers to pay them back.
Summary
- Ask first whether a cart can mix restaurants, when the customer is charged and who may cancel. Each answer changes the code.
- A courier and a customer are ids.
Order,CartandRestaurantare classes, and each guards its own state. - The cart holds dishes and quantities, not prices or stock. Checkout takes every portion or none, under the restaurant's lock, before the charge.
- Keep money as a
longof cents. Apply the coupon, then tax once on what is left, then the delivery fee. - Write the order's states as a table, and check it under the order's lock, so an accept and a cancel are always put in a line.
- Call the card processor and the dispatcher with no lock held, and give each order a random payment key that never repeats.
- Write a refund down before sending it, and retry it with the same key until it goes through.