LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 13 OF 42

Design a Food Ordering System: LLD in Java

A food delivery app designed and coded: restaurants and menus, a cart locked to one restaurant, an order state machine, billing with discounts as Strategies and tax rounded in paise, nearest-rider assignment with compare-and-set, Observer notifications, a most-ordered items tracker, and the follow-ups, with a full Java 17 solution.

Patterns usedObserverStrategyState

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 20

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 310 lines, with a small main() demo. Save it as FoodOrdering.java, then run javac FoodOrdering.java && java FoodOrdering.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;

/** Food ordering: menus, a one-restaurant cart, an order state machine, billing, delivery and top items. */
public class FoodOrdering {

    // ---------- the model ----------
    record MenuItem(String id, String name, long priceCents) {}

    record Restaurant(String id, String name, int x, int y, Map<String, MenuItem> menu) {
        static Restaurant of(String id, String name, int x, int y, MenuItem... items) {
            Map<String, MenuItem> m = new LinkedHashMap<>();
            for (MenuItem i : items) m.put(i.id(), i);
            return new Restaurant(id, name, x, y, Map.copyOf(m));
        }
    }

    record Line(MenuItem item, int qty) {
        long cents() { return item.priceCents() * qty; }
    }

    /** One cart belongs to one customer and one restaurant at a time. */
    static final class Cart {
        private Restaurant restaurant;
        private final Map<String, Integer> qty = new LinkedHashMap<>();

        void add(Restaurant r, String itemId, int n) {
            if (restaurant != null && !restaurant.id().equals(r.id()))
                throw new IllegalStateException("cart already has items from " + restaurant.name());
            if (!r.menu().containsKey(itemId))
                throw new IllegalArgumentException("not on the menu: " + itemId);
            restaurant = r;
            qty.merge(itemId, n, Integer::sum);
        }

        List<Line> lines() {
            List<Line> out = new ArrayList<>();
            qty.forEach((id, n) -> out.add(new Line(restaurant.menu().get(id), n)));
            return out;
        }
    }

    /** The order lifecycle. Each state lists where it may go next; anything else is rejected. */
    enum Status {
        PLACED, ACCEPTED, PREPARING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED;

        Set<Status> next() {
            return switch (this) {
                case PLACED -> EnumSet.of(ACCEPTED, CANCELLED);
                case ACCEPTED -> EnumSet.of(PREPARING, CANCELLED);
                case PREPARING -> EnumSet.of(OUT_FOR_DELIVERY);
                case OUT_FOR_DELIVERY -> EnumSet.of(DELIVERED);
                case DELIVERED, CANCELLED -> EnumSet.noneOf(Status.class);
            };
        }
    }

    record Bill(long subtotal, long discount, long tax, long deliveryFee) {
        long total() { return subtotal - discount + tax + deliveryFee; }
    }

    static final class Order {
        final String id;
        final String customer;
        final Restaurant restaurant;
        final List<Line> lines;
        final Bill bill;
        private final AtomicReference<Status> status = new AtomicReference<>(Status.PLACED);
        volatile Agent agent;

        Order(String id, String customer, Restaurant r, List<Line> lines, Bill bill) {
            this.id = id;
            this.customer = customer;
            this.restaurant = r;
            this.lines = List.copyOf(lines);
            this.bill = bill;
        }

        Status status() { return status.get(); }
    }

    static final class Agent {
        final String id;
        final int x, y;
        private final AtomicReference<String> busyWith = new AtomicReference<>();

        Agent(String id, int x, int y) {
            this.id = id;
            this.x = x;
            this.y = y;
        }

        boolean tryAssign(String orderId) { return busyWith.compareAndSet(null, orderId); }

        void free() { busyWith.set(null); }

        boolean isFree() { return busyWith.get() == null; }
    }

    // ---------- strategies and observers ----------
    interface Discount { long off(long subtotal); }

    /** Percent off with a cap, e.g. 20% up to 100.00. */
    record PercentOff(int percent, long capCents) implements Discount {
        public long off(long subtotal) { return Math.min(subtotal * percent / 100, capCents); }
    }

    /** Flat amount off when the order is big enough. */
    record FlatOff(long cents, long minOrderCents) implements Discount {
        public long off(long subtotal) { return subtotal >= minOrderCents ? cents : 0; }
    }

    static final Discount NONE = subtotal -> 0;

    /** Billing: subtotal, minus discount, plus tax on the discounted amount (half up), plus delivery. */
    record BillCalculator(int taxBasisPoints, long deliveryFeeCents, long freeDeliveryAbove) {
        Bill bill(List<Line> lines, Discount d) {
            long subtotal = lines.stream().mapToLong(Line::cents).sum();
            long discount = Math.min(d.off(subtotal), subtotal);
            long taxable = subtotal - discount;
            long tax = (taxable * taxBasisPoints + 5_000) / 10_000;
            long delivery = taxable >= freeDeliveryAbove ? 0 : deliveryFeeCents;
            return new Bill(subtotal, discount, tax, delivery);
        }
    }

    interface AssignmentStrategy { List<Agent> rank(List<Agent> agents, Restaurant r); }

    /** Nearest free agent first (Manhattan distance on a grid). */
    static final AssignmentStrategy NEAREST = (agents, r) -> agents.stream().filter(Agent::isFree)
            .sorted(Comparator.comparingInt(a -> Math.abs(a.x - r.x()) + Math.abs(a.y - r.y()))).toList();

    interface OrderListener { void onStatus(Order o, Status s); }

    /** Most ordered items: a counter per item per restaurant, updated by an observer. */
    static final class TopItems implements OrderListener {
        private final Map<String, Map<String, LongAdder>> counts = new ConcurrentHashMap<>();

        public void onStatus(Order o, Status s) {
            if (s != Status.PLACED) return;
            Map<String, LongAdder> m =
                    counts.computeIfAbsent(o.restaurant.id(), k -> new ConcurrentHashMap<>());
            for (Line l : o.lines) m.computeIfAbsent(l.item().name(), k -> new LongAdder()).add(l.qty());
        }

        List<String> top(String restaurantId, int k) {
            return counts.getOrDefault(restaurantId, Map.of()).entrySet().stream()
                    .sorted((a, b) -> Long.compare(b.getValue().sum(), a.getValue().sum()))
                    .limit(k).map(e -> e.getKey() + " x" + e.getValue().sum()).toList();
        }
    }

    // ---------- the service ----------
    private final BillCalculator billing;
    private final AssignmentStrategy assignment;
    private final List<Agent> agents = new CopyOnWriteArrayList<>();
    private final Map<String, Order> orders = new ConcurrentHashMap<>();
    private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
    private final AtomicLong seq = new AtomicLong();

    FoodOrdering(BillCalculator billing, AssignmentStrategy assignment) {
        this.billing = billing;
        this.assignment = assignment;
    }

    void addAgent(Agent a) { agents.add(a); }

    void subscribe(OrderListener l) { listeners.add(l); }

    Order checkout(String customer, Cart cart, Discount discount) {
        List<Line> lines = cart.lines();
        if (lines.isEmpty()) throw new IllegalStateException("empty cart");
        Bill bill = billing.bill(lines, discount);
        Order o = new Order("O" + seq.incrementAndGet(), customer, cart.restaurant, lines, bill);
        orders.put(o.id, o);
        publish(o, Status.PLACED);
        return o;
    }

    /** Compare-and-set on the status: two staff tapping at once cannot both move the order. */
    void move(String orderId, Status to) {
        Order o = orders.get(orderId);
        Status from = o.status();
        if (!from.next().contains(to)) throw new IllegalStateException(orderId + ": " + from + " -> " + to);
        if (!o.status.compareAndSet(from, to))
            throw new IllegalStateException(orderId + " changed meanwhile");
        if (to == Status.DELIVERED && o.agent != null) o.agent.free();
        publish(o, to);
    }

    /** Try agents nearest first; each claim is a CAS, so one agent never carries two orders. */
    Optional<Agent> assignAgent(String orderId) {
        Order o = orders.get(orderId);
        for (Agent a : assignment.rank(agents, o.restaurant))
            if (a.tryAssign(orderId)) {
                o.agent = a;
                return Optional.of(a);
            }
        return Optional.empty();
    }

    private void publish(Order o, Status s) {
        for (OrderListener l : listeners) l.onStatus(o, s);
    }

    // ---------- demo ----------
    static String money(long cents) { return String.format("%.2f", cents / 100.0); }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) throws InterruptedException {
        Restaurant curry = Restaurant.of("R1", "Curry House", 0, 0,
                new MenuItem("biryani", "Biryani", 24000), new MenuItem("naan", "Butter naan", 4500),
                new MenuItem("lassi", "Lassi", 8000));
        Restaurant pizza = Restaurant.of("R2", "Pizza Place", 5, 5,
                new MenuItem("margherita", "Margherita", 29900));
        FoodOrdering app = new FoodOrdering(new BillCalculator(500, 4000, 50000), NEAREST);
        TopItems top = new TopItems();
        app.subscribe(top);
        app.subscribe((o, s) -> {
            if (s != Status.PLACED) System.out.println("  [notify " + o.customer + "] " + o.id + " " + s);
        });
        app.addAgent(new Agent("rider-far", 9, 9));
        app.addAgent(new Agent("rider-near", 1, 0));
        app.addAgent(new Agent("rider-mid", 3, 3));

        Cart cart = new Cart();
        cart.add(curry, "biryani", 1);
        cart.add(curry, "naan", 2);
        try {
            cart.add(pizza, "margherita", 1);
            throw new AssertionError("mixed restaurants");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        Order o1 = app.checkout("Student", cart, new PercentOff(20, 10000));
        Bill b = o1.bill;
        System.out.println(o1.id + " bill: subtotal " + money(b.subtotal()) + ", discount "
                + money(b.discount()) + ", tax " + money(b.tax()) + ", delivery " + money(b.deliveryFee())
                + ", total " + money(b.total()));
        check(b.subtotal() == 33000 && b.discount() == 6600 && b.tax() == 1320 && b.total() == 31720, "bill");

        app.move(o1.id, Status.ACCEPTED);
        app.move(o1.id, Status.PREPARING);
        System.out.println(o1.id + " rider: " + app.assignAgent(o1.id).map(a -> a.id).orElse("none"));
        check(o1.agent.id.equals("rider-near"), "nearest rider first");
        app.move(o1.id, Status.OUT_FOR_DELIVERY);
        try {
            app.move(o1.id, Status.CANCELLED);
            throw new AssertionError("cancelled on the road");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        app.move(o1.id, Status.DELIVERED);
        check(o1.agent.isFree(), "rider is free after delivery");

        for (String who : List.of("Office worker", "Parent", "Night owl")) {
            Cart c = new Cart();
            c.add(curry, "biryani", 2);
            c.add(curry, "lassi", 1);
            Order o = app.checkout(who, c, new FlatOff(5000, 40000));
            check(o.bill.discount() == 5000 && o.bill.deliveryFee() == 0, "flat off and free delivery");
        }
        System.out.println("Top at Curry House: " + top.top("R1", 3));
        check(top.top("R1", 1).get(0).equals("Biryani x7"), "biryani is the most ordered");

        // Six orders race for three riders: each rider gets exactly one.
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            Cart c = new Cart();
            c.add(pizza, "margherita", 1);
            ids.add(app.checkout("Racer" + i, c, NONE).id);
        }
        AtomicInteger got = new AtomicInteger(), waiting = new AtomicInteger();
        CountDownLatch go = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(6);
        for (String id : ids)
            pool.submit(() -> {
                try {
                    go.await();
                    (app.assignAgent(id).isPresent() ? got : waiting).incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        go.countDown();
        pool.shutdown();
        check(pool.awaitTermination(5, TimeUnit.SECONDS), "pool did not finish");
        System.out.println("Rider race: " + got.get() + " assigned, " + waiting.get() + " waiting");
        check(got.get() == 3, "a rider took two orders");
    }
}

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.

Requirements
  • 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
Clarify first
  • 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.

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

Cart.add()
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.

Status.next()
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.

BillCalculator.bill()
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.

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

checkout(customer, cart, d)
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.

assignAgent(orderId)
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.

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

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

Two races, one tool
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
Thread safety checklist
  • 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.

Extension points
  • 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.

Run it
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.

Follow-ups to expect
  • 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.

In the interview
  • "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."

Interview questions

How do you model the order lifecycle?

As a state machine: a Status enum where each value returns the set of statuses it may move to. move() checks the transition is allowed and then applies it with compareAndSet on an AtomicReference, so illegal or concurrent changes fail cleanly.

In what order do you compute the bill?

Subtotal from price times quantity, then the discount (never more than the subtotal), then tax on the discounted amount rounded half up, then the delivery fee, free above a threshold. Everything is whole paise in a long.

How are coupons and offers designed?

A Discount strategy with one method, off(subtotal). PercentOff with a cap and FlatOff with a minimum order are implementations, and NONE returns zero so there is no null check. New offer types are new classes.

How do you make sure a rider is not assigned two orders?

Each rider holds an AtomicReference to the order it carries, and assignment is compareAndSet(null, orderId). The strategy ranks free riders, the service tries them in order, and only one claim per rider can succeed.

Why can a cart hold items from only one restaurant?

One order is cooked by one kitchen and carried by one rider, and the bill, delivery fee and status all belong to that restaurant. The Cart enforces it in add(); mixing restaurants would mean splitting into several orders.

How do you track the most ordered items?

A listener on PLACED events adds each line's quantity to a LongAdder per item per restaurant in a ConcurrentHashMap. Top-k sorts the counters or uses a size-k min-heap; at large scale it becomes streaming counts aggregated per shard.

Why copy the cart lines into the order?

The order must keep the prices the customer agreed to. If the restaurant edits its menu afterwards, a frozen list of immutable lines and a precomputed bill keep the order, the invoice and any refund consistent.

How do notifications work without coupling?

Observer pattern: every status change is published to OrderListener implementations in a CopyOnWriteArrayList, such as customer push messages, the restaurant dashboard and the top items tracker. The service does not know which listeners exist.