Notes
Requirements
The requirements. Restaurants have menus. A customer adds items with quantities to a cart and checks out, getting a bill with discounts, tax and a delivery fee. The order moves through placed, accepted, preparing, out for delivery and delivered, and can only be cancelled before cooking starts. The nearest free rider is assigned, the customer is notified at each step, and each restaurant can see its most ordered items.
Clarify the billing rules, because they decide the order of operations. Can one cart mix restaurants? No. Is tax charged before or after the discount? After, on the discounted amount. Rounding is half up to the paisa. Delivery is free above an order value. And a rider carries one order at a time for now; batching is an extension.
- restaurants with menus
- cart: add items with quantity
- checkout: bill with discount,
- tax and delivery fee
- order: placed, accepted,
- preparing, out, delivered
- cancel only before cooking
- assign the nearest free rider
- notify the customer each step
- most ordered items per place
- cart from two restaurants?
- no, one at a time
- tax before or after discount?
- after: on the discounted amount
- rounding?
- half up, to the paisa
- free delivery?
- above an order value
- one rider, many orders?
- one order per rider for now
Entities
The entities. A restaurant has menu items. A cart collects lines from one restaurant. Checkout turns the cart into an order with a frozen copy of the lines and a bill. The order has a status from a fixed set and, once it is cooking, a rider. Freezing the lines matters: if the restaurant changes a price later, the order keeps what the customer agreed to pay.
Class diagram
In code, menu items, restaurants, lines and bills are records. A bill holds the subtotal, discount, tax and delivery fee as paise, and computes its total. Only two classes hold changing state: an order, whose status is an atomic reference, and a rider, who is either free or busy with one order. Keeping mutation that small makes the concurrency story short.
record MenuItem(String id, String name,
long priceCents)
record Restaurant(id, name, x, y,
Map<String, MenuItem> menu)
record Line(MenuItem item, int qty)
record Bill(subtotal, discount, tax,
deliveryFee) { total() }
class Order { id, customer, lines,
bill, AtomicReference<Status>, agent }
class Agent { id, x, y, busyWith } The cart
The cart enforces its own rule: once it holds food from one restaurant, adding an item from another is rejected, and an item must be on that restaurant's menu. Adding the same item twice merges the quantity. Real apps then offer to clear the cart and start again, which is a user interface choice on top of this one check.
void add(Restaurant r, String id, int n) {
if (restaurant != null
&& !restaurant.id().equals(r.id()))
throw: cart has items from another
if (!r.menu().containsKey(id))
throw: not on the menu
restaurant = r;
qty.merge(id, n, Integer::sum);
} State machine
The order lifecycle is a state machine, and the simplest honest way to write it is an enum where each status returns the set of statuses it may move to. Placed can go to accepted or cancelled, preparing can only go out for delivery, and delivered and cancelled are final. Because it is a switch over the enum, adding a new status, like ready for pickup, forces you to decide its transitions.
PLACED -> ACCEPTED, CANCELLED ACCEPTED -> PREPARING, CANCELLED PREPARING -> OUT_FOR_DELIVERY OUT_FOR_DELIVERY -> DELIVERED DELIVERED, CANCELLED -> nothing switch over the enum: the compiler makes you handle a new status cancel while out for delivery: rejected
Billing
Billing follows a fixed order. Add up price times quantity. Apply the discount, never more than the subtotal. Charge tax on what is left, stored as basis points and rounded half up by adding five thousand before dividing by ten thousand, all in whole paise. Delivery is free above five hundred. A biryani and two naan come to three hundred and thirty, minus sixty six, plus thirteen twenty tax, plus forty delivery: three hundred and seventeen twenty.
subtotal = sum(price x qty) discount = min(d.off(subtotal), subtotal) taxable = subtotal - discount tax = (taxable x bps + 5000) / 10000 delivery = taxable >= 500.00 ? 0 : 40.00 biryani + 2 naan = 330.00 20% off, cap 100: -66.00 tax 5% of 264.00: 13.20 delivery 40.00: total 317.20
Strategy: discounts
Discounts are a strategy with one method: given a subtotal, how much comes off. Percent off has a cap, like twenty percent up to a hundred. Flat off needs a minimum order. No coupon is a lambda that returns zero, so the bill code never checks for null. Buy one get one, first order offers and bank offers are new classes, and the bill calculator does not change.
interface Discount { long off(long sub); }
record PercentOff(int pct, long cap)
min(sub x pct / 100, cap)
record FlatOff(long cents, long minOrder)
sub >= minOrder ? cents : 0
NONE = sub -> 0
buy one get one, first order,
bank offer: new classes Flow: checkout
Checkout copies the cart lines so later menu edits cannot change the order, rejects an empty cart, and asks the bill calculator for the bill with the chosen discount. It creates the order in the placed state, stores it in a concurrent map and publishes the placed event to every listener. Payment would sit between billing and storing; it is out of scope, but say where it goes.
lines = cart.lines()
if lines empty: throw
bill = billing.bill(lines, d)
o = new Order(nextId(), customer,
restaurant, lines, bill)
orders.put(o.id, o)
publish(o, PLACED)
return o Strategy: riders
Choosing a rider is another strategy: rank the free riders for this restaurant. Our default sorts by grid distance, so the rider one block away beats the others. A smarter strategy could weigh ratings, current load or the direction the rider is heading. The service then tries to claim riders in that order and takes the first that succeeds. If nobody is free, the order waits in a queue and is retried.
for (Agent a : strategy.rank(agents, r))
if (a.tryAssign(orderId)) {
order.agent = a; return a
}
return empty: queue and retry
NEAREST: free riders sorted by
|x - rx| + |y - ry|
rider-near (1 away) beats
rider-mid and rider-far Observer
Every status change is published to listeners: the Observer pattern. The customer notification is one listener, the restaurant dashboard another, and the most ordered items tracker a third. A ratings prompt after delivery would be one more. The order service knows none of them by name, so adding a channel never touches the ordering code.
interface OrderListener {
void onStatus(Order o, Status s);
}
push / SMS to the customer
restaurant dashboard
TopItems: counts on PLACED
payouts, ratings prompts
the service knows none of them Most ordered items
The most ordered items tracker is a listener that, on every placed order, adds each line's quantity to a counter per item per restaurant. Long adders let many threads increment the same hot item without contention. To answer top k, sort the counters, or keep a min-heap of size k for big menus. After four orders, biryani leads with seven.
Map<restaurant, Map<item, LongAdder>> onStatus(o, PLACED): for each line: counter.add(qty) top(r, k): sort by count, limit k or a size-k min-heap: n log k Curry House: Biryani x7, Lassi x3, Butter naan x2
Concurrency
Two races matter. Six orders may grab riders at the same moment; each rider holds an atomic reference to the order it carries, and claiming is a compare-and-set from empty, so a rider can never get two orders. Status changes use the same trick: check the transition is allowed, then compare-and-set from the old status, so if a cook and a manager tap at once, only one change lands. Delivery frees the rider.
Give every shared field a safe home. Orders live in a concurrent map. Status and rider assignment are atomic references changed by compare-and-set. The assigned rider field is volatile so other threads see it. Counters are long adders. Listeners sit in a copy-on-write list. A cart belongs to one customer session, so it needs no lock, and every record is immutable.
rider: busyWith.compareAndSet(null, id) 6 orders, 3 riders: 3 assigned, 3 waiting, never 2 orders on 1 status: check from.next() has to, then status.compareAndSet(from, to) two staff taps: one wins rider freed on DELIVERED
- orders: ConcurrentHashMap
- status: AtomicReference + CAS
- rider: AtomicReference + CAS
- order.agent: volatile
- item counts: LongAdder in
- ConcurrentHashMap
- listeners: CopyOnWriteArrayList
- cart: one per customer session
- records: immutable, shareable
Extensibility
Extensions. Rider batching turns the busy field into a small list with a capacity. A busy kitchen can reject orders when too many are cooking. Scheduled orders carry a start time. Tips, packaging and surge fees are more lines on the bill, and refunds are a reversing bill rather than an edit. Ratings are one more listener on delivered.
- rider batching: busyWith becomes
- a small list with a capacity
- restaurant capacity: reject
- when too many are cooking
- scheduled orders: a start time
- tips, packaging, surge fees:
- more lines on the Bill
- refunds: a reversing Bill
- ratings: a DELIVERED listener
Testing
The full code is below the player. The demo refuses a mixed cart, asserts every paisa of a bill with a capped percentage coupon, walks the order through its states with notifications, refuses a cancel while the food is on the road, checks flat discounts and free delivery on three more orders, prints the top items, and races six orders for three riders. Exactly three are assigned, every time.
Rejected: cart already has items from Curry House O1 bill: subtotal 330.00, discount 66.00, tax 13.20, delivery 40.00, total 317.20 O1 rider: rider-near Rejected: O1: OUT_FOR_DELIVERY -> CANCELLED Top at Curry House: [Biryani x7, Lassi x3, Butter naan x2] Rider race: 3 assigned, 3 waiting
Follow-ups
Expect follow-ups. Why tax after the discount? That is the usual rule and the customer pays tax on what they actually pay. Why freeze the lines? Prices change. A failed payment needs a payment pending state with an expiry. A rejected order cancels and refunds automatically. Top items at huge scale become streaming counts with a top k per shard, merged. And a rider who goes offline is reassigned, with the change logged.
- why tax after discount?
- why freeze the cart lines?
- payment fails after placing?
- PAYMENT_PENDING state, expiry
- restaurant rejects the order?
- ACCEPTED fails, auto refund
- top items for millions?
- stream counts, top-k per shard
- rider goes offline mid-trip?
- reassign, keep an audit trail
Say it like this
The short version. A cart holds items from one restaurant, and checkout freezes it into an order with a bill in paise: discount first, tax on the rest, then delivery. The status is an enum state machine changed by compare-and-set. Discounts and rider choice are strategies, riders are claimed by compare-and-set, and listeners handle notifications and the most ordered items.
- "A cart holds one restaurant and
- checkout freezes it into an
- order with a bill in paise:
- discount, tax, delivery. Status
- is an enum state machine moved
- by compare-and-set; riders are
- ranked by a strategy and claimed
- by CAS; listeners notify and
- count the top items."