SyntaxPilot
Courses/Low-Level Design/Lesson 80
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 80 of 90

Design a food delivery app

food delivery requirementsRestaurantMenuMenuItemCustomerOrderorder lifecycleDeliveryPartnerdelivery assignment strategyETA estimationratingsorder tracking with Observercancellation rules

These are the notes for Low-Level Design (LLD) episode 80: designing a food delivery app, the kind of app you open to order dinner (apps like Swiggy or Zomato). We start with a neighbourhood dhaba that takes orders on the phone and grow it into an app, one problem at a time: Restaurant, Menu, MenuItem, Customer and Order classes, an order lifecycle that refuses illegal jumps, a DeliveryPartner and a swappable delivery assignment strategy, a simple ETA estimate, order tracking with Observer, cancellation rules and ratings.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly, including the exception messages. The dhaba, dishes, prices, people, fees and speeds are made up for the example; nothing here describes how any real company builds its app.

1. The problem: Sharma ji's dhaba and its phone

Real life In the design
Sharma ji's dhaba, its list of dishes, one dish on that list Restaurant, Menu, MenuItem
Asha phones and asks for 2 kheer; he writes it in a notebook Customer, Order
"2 kheer!" ...but the kheer finished an hour ago Ordering an unavailable item must be refused
The order goes: taken, cooking, sent out, delivered The order lifecycle
Three delivery boys; he sends the one 10 km away DeliveryPartner, delivery assignment strategy
"How long will it take?" ETA estimation
Customers call every 5 minutes: "where is my food?" Order tracking with Observer (not polling)
A customer cancels after the food left on the bike Cancellation rules
"The dal was great, the delivery was slow" Ratings

2. Requirements and the words

Food delivery requirements (what the app must do):

  1. A customer browses restaurants and their menus.
  2. A customer orders available dishes; unavailable dishes are refused.
  3. The restaurant accepts and cooks; a delivery partner picks the food up and delivers it.
  4. The app picks a delivery partner and shows an ETA.
  5. The customer, the kitchen and the partner are told about every status change.
  6. The customer can cancel under rules that depend on how far the order has gone.
  7. After delivery, the customer rates the restaurant and the partner from 1 to 5 stars.

The classes:

  • Restaurant: a place that cooks food, with a name and a menu. Example: Sharma Dhaba.
  • Menu: the restaurant's list of dishes. Example: dal makhani and kheer.
  • MenuItem: one dish on the menu, with a name, a price and an available flag. Example: MenuItem("Kheer", 90, false): kheer, 90 rupees, not available tonight.
  • Customer: the person who orders. Example: Customer("Asha").
  • Order: who ordered, which dish, how many, and its status (where the order is right now). Example: Asha, 2 x dal makhani, PLACED.

3. Attempt 1: the notebook, typed in

The obvious first app copies the notebook: a map of prices, a set of finished dishes, orders as strings, and the status as a string in a history list.

import java.util.*;
public class Main { public static void main(String[] args) {
    Map<String, Integer> menu = Map.of("Dal makhani", 180, "Kheer", 90);
    Set<String> finished = Set.of("Kheer");     // the kitchen ran out at 8 pm
    List<String> orders = new ArrayList<>();
    orders.add("Asha: 2 x Kheer");              // nobody checks the kitchen
    List<String> history = new ArrayList<>(List.of("PLACED"));
    history.add("DELIVERED");                   // a wrong tap
    history.add("PREPARING");                   // the kitchen updates late
    history.add("Deliverd");                    // a typo, no error
    System.out.println(orders.get(0) + ", bill " + 2 * menu.get("Kheer"));
    System.out.println("History: " + history);
} }

Real output:

Asha: 2 x Kheer, bill 180
History: [PLACED, DELIVERED, PREPARING, Deliverd]

Why it failed

  • The finished set exists, but nothing forces anyone to look at it: Asha is charged 180 rupees for kheer that doesn't exist.
  • A string status accepts any word in any order: DELIVERED and then PREPARING (food delivered, then cooked again), and even the typo Deliverd. No error anywhere.

The fix has two parts: an order can only be built through the menu, which refuses unavailable dishes; and the status becomes an enum with legal moves.

4. The fix: classes and the order lifecycle

The order lifecycle is the fixed list of steps every order walks through:

PLACED → ACCEPTED → PREPARING → PICKED_UP → DELIVERED
   └────────┴───────────┴──→ CANCELLED (only before pickup)
  • PLACED: the customer ordered; the restaurant hasn't answered yet.
  • ACCEPTED: the restaurant said yes.
  • PREPARING: the food is cooking.
  • PICKED_UP: the delivery partner has the food.
  • DELIVERED: the customer has it.
  • CANCELLED: the order was cancelled (allowed only up to PREPARING).

It's written as an enum (a type with a fixed set of named values) with a canGo method. Any move that canGo doesn't allow throws an exception: a small state machine (episode 37, the State pattern).

import java.util.*;
enum Status { PLACED, ACCEPTED, PREPARING, PICKED_UP, DELIVERED, CANCELLED;
    boolean canGo(Status to) {                     // cancel before pickup, else ONE step forward
        return to == CANCELLED ? compareTo(PREPARING) <= 0 : to.ordinal() == ordinal() + 1; } }
record MenuItem(String name, int price, boolean available) {}   record Customer(String name) {}
record Menu(List<MenuItem> items) {
    MenuItem find(String dish) {
        return items.stream().filter(m -> m.name().equals(dish) && m.available()).findFirst()
            .orElseThrow(() -> new IllegalArgumentException(dish + " is not available")); } }
record Restaurant(String name, Menu menu) {}
class Order { Customer customer;  MenuItem item;  int qty;  Status status = Status.PLACED;
    Order(Restaurant r, Customer c, String dish, int q) { item = r.menu().find(dish);
        customer = c;  qty = q; }
    void moveTo(Status to) {
        if (!status.canGo(to)) throw new IllegalStateException("cannot go " + status + " -> " + to);
        System.out.println("  " + status + " -> " + to);  status = to; } }
public class Main { public static void main(String[] args) {
    Menu menu = new Menu(List.of(new MenuItem("Dal makhani", 180, true),
                                 new MenuItem("Kheer", 90, false)));   // finished for today
    Restaurant dhaba = new Restaurant("Sharma Dhaba", menu);  Customer asha = new Customer("Asha");
    try { new Order(dhaba, asha, "Kheer", 2); } catch (Exception e) { System.out.println(e); }
    Order o = new Order(dhaba, asha, "Dal makhani", 2);
    System.out.println("Order for " + o.customer.name() + ", total " + o.qty * o.item.price());
    o.moveTo(Status.ACCEPTED);  o.moveTo(Status.PREPARING);  o.moveTo(Status.DELIVERED); } }

Real output:

java.lang.IllegalArgumentException: Kheer is not available
Order for Asha, total 360
  PLACED -> ACCEPTED
  ACCEPTED -> PREPARING
Exception in thread "main" java.lang.IllegalStateException: cannot go PREPARING -> DELIVERED
    at Order.moveTo(Main.java:15)
    at Main.main(Main.java:24)

Line by line:

  • canGo: CANCELLED is allowed while the status is at most PREPARING (compareTo(PREPARING) <= 0); any other move must be exactly the next step (ordinal() + 1). ordinal() is an enum value's position in the list: PLACED is 0, ACCEPTED is 1, and so on.
  • MenuItem, Customer, Menu and Restaurant are records: short classes that just hold data (Java makes the constructor and getters like name() for you).
  • Menu.find returns the dish or throws IllegalArgumentException if it is missing or not available. The Order constructor calls it, so an order for an unavailable dish can never exist.
  • moveTo checks canGo before changing anything, so a refused move leaves the order as it was.

A real app's order holds many dishes (a list of order lines); one dish keeps the video's program short. The mini project uses order lines.

5. Who delivers it? DeliveryPartner and the assignment strategy

A DeliveryPartner is the person who rides the food from the restaurant to the customer. At any moment a partner is free or busy.

The obvious rule is Sharma ji's: send the first free partner in the list. It ignores distance, and the partner at the top of the list gets every order (unfair to the others). The rule will keep changing (nearest first, then the one who waited longest, then something else), so we make the rule an interface: the delivery assignment strategy. This is the Strategy pattern (episode 34): each rule is one class, and the app can swap them without changing anything else.

Distances: a simple grid in kilometres. The dhaba is at (0, 0); Asha lives at (3, 4), which is √(3² + 4²) = 5 km away (straight-line distance, Math.hypot).

ETA estimation: ETA means estimated time of arrival, how long until the food reaches the customer. The partner rides to the restaurant while the food cooks, so we wait for whichever is longer, then add the ride to the customer:

ETA = max(prep time, ride to restaurant) + ride to customer
speed 20 km an hour = 3 minutes per km
import java.util.*;
record Point(double x, double y) { double km(Point o) { return Math.hypot(x - o.x, y - o.y); } }
record DeliveryPartner(String name, Point at, boolean free) {}
interface AssignmentStrategy { DeliveryPartner pick(List<DeliveryPartner> all, Point restaurant); }
class FirstFree implements AssignmentStrategy {               // attempt: first free in the list
    public DeliveryPartner pick(List<DeliveryPartner> all, Point r) {
        return all.stream().filter(DeliveryPartner::free).findFirst().orElseThrow(); } }
class NearestFree implements AssignmentStrategy {             // fix: the nearest free partner
    public DeliveryPartner pick(List<DeliveryPartner> all, Point r) {
        return all.stream().filter(DeliveryPartner::free)
                  .min(Comparator.comparingDouble(p -> p.at().km(r))).orElseThrow(); } }
public class Main {
    static final double PREP = 15, MIN_PER_KM = 3;            // 20 km an hour = 3 minutes per km
    static double eta(DeliveryPartner p, Point dhaba, Point home) {   // ride in while food cooks
        return Math.max(PREP, p.at().km(dhaba) * MIN_PER_KM) + dhaba.km(home) * MIN_PER_KM; }
    public static void main(String[] args) {
        Point dhaba = new Point(0, 0), asha = new Point(3, 4);
        List<DeliveryPartner> team = List.of(new DeliveryPartner("Ravi", new Point(6, 8), true),
                                             new DeliveryPartner("Imran", new Point(0, 1), false),
                                             new DeliveryPartner("Deepa", new Point(0, 2), true));
        for (AssignmentStrategy s : List.of(new FirstFree(), new NearestFree())) {
            DeliveryPartner p = s.pick(team, dhaba);  double km = p.at().km(dhaba);
            System.out.printf("%-11s -> %s, %.1f km away, ETA %.0f min%n",
                s.getClass().getSimpleName(), p.name(), km, eta(p, dhaba, asha)); } } }

Real output:

FirstFree   -> Ravi, 10.0 km away, ETA 45 min
NearestFree -> Deepa, 2.0 km away, ETA 30 min
  • FirstFree picks Ravi (first in the list), 10 km away: max(15, 10 × 3 = 30) + 5 × 3 = 30 + 15 = 45 minutes.
  • NearestFree skips busy Imran and picks Deepa, 2 km away: max(15, 2 × 3 = 6) + 15 = 15 + 15 = 30 minutes.
  • Same app, one class swapped, 15 minutes saved. Comparator.comparingDouble(p -> p.at().km(r)) compares partners by their distance to the restaurant; min takes the closest.

6. "Where is my food?" Order tracking with Observer

Two obvious attempts, both bad:

  • Polling: the customer's app asks the server "any news?" every minute, even when nothing has changed. Most requests are wasted.
  • Hard-coded calls: moveTo calls the customer app, then the kitchen screen, then the partner's phone, by name. Every new screen (an SMS, a smartwatch) means editing Order.

The fix is the Observer pattern (episode 35). The order is the subject; listeners (observers) subscribe to it; on every move, the order notifies all of them, and each reacts its own way. That is order tracking.

import java.util.*;
enum Status { PLACED, ACCEPTED, PREPARING, PICKED_UP, DELIVERED }
interface OrderListener { void onChange(String orderId, Status now); }       // the observer
class Order {                                                                // the subject
    final String id;  private Status status = Status.PLACED;
    private final List<OrderListener> listeners = new ArrayList<>();
    Order(String id) { this.id = id; }
    void subscribe(OrderListener l) { listeners.add(l); }
    Status status() { return status; }
    void moveTo(Status s) { status = s;  for (OrderListener l : listeners) l.onChange(id, s); } }
public class Main { public static void main(String[] args) {
    Order a = new Order("#101");  int polls = 0, news = 0;  Status seen = a.status();
    for (int minute = 1; minute <= 40; minute++) {        // attempt: the app asks every minute
        if (minute % 10 == 0) a.moveTo(Status.values()[minute / 10]);    // 4 real changes
        polls++;  if (a.status() != seen) { news++;  seen = a.status(); } }
    System.out.println("Polling: " + polls + " requests, " + news + " with news");
    Order b = new Order("#102");  var out = System.out;   // fix: Observer
    b.subscribe((id, s) -> out.println("  Customer app: " + id + " is " + s));
    b.subscribe((id, s) -> { if (s == Status.ACCEPTED) out.println("  Kitchen: cook " + id); });
    b.subscribe((id, s) -> { if (s == Status.PREPARING) out.println("  Partner: go to dhaba"); });
    for (Status s : List.of(Status.ACCEPTED, Status.PREPARING, Status.PICKED_UP, Status.DELIVERED))
        b.moveTo(s);
} }

Real output:

Polling: 40 requests, 4 with news
  Customer app: #102 is ACCEPTED
  Kitchen: cook #102
  Customer app: #102 is PREPARING
  Partner: go to dhaba
  Customer app: #102 is PICKED_UP
  Customer app: #102 is DELIVERED
  • Polling made 40 requests and only 4 had news: 36 wasted.
  • With Observer, nobody asks. The customer app hears every change, the kitchen is told to cook on ACCEPTED, and the partner is told to go on PREPARING.
  • The listeners are lambdas (short unnamed functions): (id, s) -> ... is a whole OrderListener.
  • The lifecycle check is left out of this program to keep it short; the mini project has both together.

7. Cancellation rules and ratings

If customers can cancel any time for free, the restaurant pays for food nobody eats and the partner rides for nothing. Cancellation rules depend on the status:

Status when cancelling Fee Why
PLACED 0 (free) Nothing has started
ACCEPTED 10% The kitchen has planned it
PREPARING 50% The food is cooking
PICKED_UP, DELIVERED not allowed The food is on the bike or eaten

Ratings: after delivery the customer gives 1 to 5 stars to the restaurant and to the partner. Anything outside 1 to 5 is refused. The app keeps the average per restaurant and per partner, so good ones can be shown first.

import java.util.*;
enum Status { PLACED, ACCEPTED, PREPARING, PICKED_UP, DELIVERED, CANCELLED }
class CancellationPolicy {
    static int fee(Status s, int total) {
        return switch (s) {
            case PLACED -> 0;                                   // nothing started: free
            case ACCEPTED -> total / 10;                        // kitchen planned it: 10%
            case PREPARING -> total / 2;                        // food is cooking: half
            default -> throw new IllegalStateException("cannot cancel once " + s); }; } }
class Ratings { private final Map<String, List<Integer>> stars = new HashMap<>();   // who -> stars
    void rate(String who, int n) {
        if (n < 1 || n > 5) throw new IllegalArgumentException("stars must be 1 to 5, got " + n);
        stars.computeIfAbsent(who, k -> new ArrayList<>()).add(n); }
    double average(String who) {
        return stars.get(who).stream().mapToInt(i -> i).average().orElse(0); } }
public class Main { public static void main(String[] args) {
    for (Status s : List.of(Status.PLACED, Status.ACCEPTED, Status.PREPARING))
        System.out.println("Cancel while " + s + ": fee " + CancellationPolicy.fee(s, 360));
    Ratings r = new Ratings();
    r.rate("Sharma Dhaba", 5);  r.rate("Sharma Dhaba", 4);  r.rate("Deepa", 5);  r.rate("Deepa", 3);
    try { r.rate("Deepa", 6); } catch (Exception e) { System.out.println(e.getMessage()); }
    System.out.printf("Sharma Dhaba %.1f stars, Deepa %.1f stars%n",
                      r.average("Sharma Dhaba"), r.average("Deepa"));
    CancellationPolicy.fee(Status.PICKED_UP, 360); } }

Real output:

Cancel while PLACED: fee 0
Cancel while ACCEPTED: fee 36
Cancel while PREPARING: fee 180
stars must be 1 to 5, got 6
Sharma Dhaba 4.5 stars, Deepa 4.0 stars
Exception in thread "main" java.lang.IllegalStateException: cannot cancel once PICKED_UP
    at CancellationPolicy.fee(Main.java:9)
    at Main.main(Main.java:24)
  • A 360 rupee order: fee 0 while placed, 36 (a tenth) once accepted, 180 (half) while preparing.
  • switch with -> arrows returns a value; default -> throw ... covers every status after pickup.
  • 6 stars is refused; the averages are (5 + 4) / 2 = 4.5 and (5 + 3) / 2 = 4.0.

8. The class diagram

Restaurant(name) ─ has ─▶ Menu ─ lists ─▶ MenuItem(name, price, available)
Customer ─ places ─▶ Order(customer, item, qty, status)   find() refuses unavailable dishes
Status: PLACED → ACCEPTED → PREPARING → PICKED_UP → DELIVERED, CANCELLED until PREPARING
AssignmentStrategy ◁─ FirstFree · NearestFree     pick(free DeliveryPartners, restaurant)
ETA = max(prep time, partner ride to restaurant) + ride to customer   (3 minutes per km)
OrderListener (Observer) ◁─ customer app · kitchen · partner   notified on every moveTo()
CancellationPolicy: PLACED free · ACCEPTED 10% · PREPARING 50% · after pickup: refused
Ratings: 1 to 5 stars, validated · average per restaurant and per partner

9. Interview follow-ups

Question Answer
Many dishes in one order? The order keeps a List<OrderLine>, each OrderLine(item, qty); the total is the sum of the lines.
Two orders grab the same partner at once? Make assign synchronized and mark the partner busy in the same step (episode 78's read-check-write lesson). With many servers, let the database do it: update the partner row only WHERE free = true.
Thousands of partners? Don't measure everyone. Split the city into grid cells and search only the restaurant's cell and its neighbours.
Rain or traffic? Use a speed per area and hour in the ETA instead of one fixed speed; update the ETA as the partner moves.
The restaurant never accepts? A timeout: if still PLACED after, say, 5 minutes, cancel for free and tell the customer.
Refunds? Refund = total − cancellation fee (mini project: refund 90 of 180).
Fair to partners? Another strategy: the free partner who has waited longest, within a few km (practice 1).

10. Common mistakes

Mistake What you see (real) Fix
Orders and status as plain strings Asha: 2 x Kheer, bill 180 and History: [PLACED, DELIVERED, PREPARING, Deliverd] Build orders through Menu.find(); status as an enum
Skipping a step, PREPARING straight to DELIVERED java.lang.IllegalStateException: cannot go PREPARING -> DELIVERED Follow the lifecycle: PICKED_UP first
Always the first free partner FirstFree -> Ravi, 10.0 km away, ETA 45 min A swappable NearestFree strategy
Polling for status Polling: 40 requests, 4 with news Observer: listeners are told on each change
Cancelling any time, free The restaurant pays for wasted food Status-based fees; cannot cancel once PICKED_UP
Accepting any rating A 6-star or 0-star rating breaks the average Validate: stars must be 1 to 5, got 6

Mini project: the whole food delivery app

One FoodApp with order lines, a menu that refuses unavailable dishes, the lifecycle, a nearest-free strategy written as a lambda, a synchronized assign that marks the partner busy, an ETA, a tracking listener, cancellation with a refund, and ratings.

import java.util.*;

enum Status { PLACED, ACCEPTED, PREPARING, PICKED_UP, DELIVERED, CANCELLED;
    boolean canGo(Status to) {          // cancel up to PREPARING, otherwise exactly one step forward
        return to == CANCELLED ? compareTo(PREPARING) <= 0 : to.ordinal() == ordinal() + 1; } }

record Point(double x, double y) { double km(Point o) { return Math.hypot(x - o.x, y - o.y); } }
record MenuItem(String name, int price, boolean available) {}
record OrderLine(MenuItem item, int qty) { int cost() { return item.price() * qty; } }
record Customer(String name, Point home) {}

class Menu {
    private final Map<String, MenuItem> items = new LinkedHashMap<>();
    Menu(MenuItem... all) { for (MenuItem m : all) items.put(m.name(), m); }
    MenuItem find(String dish) {
        MenuItem m = items.get(dish);
        if (m == null || !m.available()) throw new IllegalArgumentException(dish + " is not available");
        return m; } }

record Restaurant(String name, Point at, Menu menu, int prepMinutes) {}

class DeliveryPartner {
    final String name;  Point at;  boolean free = true;
    DeliveryPartner(String name, Point at) { this.name = name;  this.at = at; } }

interface AssignmentStrategy { Optional<DeliveryPartner> pick(List<DeliveryPartner> free, Point restaurant); }
interface OrderListener { void onChange(Order o, Status from, Status to); }

class Order {
    private static int next = 101;
    final int id = next++;  final Customer customer;  final Restaurant restaurant;  final List<OrderLine> lines;
    Status status = Status.PLACED;  DeliveryPartner partner;
    private final List<OrderListener> listeners = new ArrayList<>();
    Order(Customer c, Restaurant r, List<OrderLine> lines) { customer = c;  restaurant = r;  this.lines = lines; }
    int total() { return lines.stream().mapToInt(OrderLine::cost).sum(); }
    void subscribe(OrderListener l) { listeners.add(l); }
    void moveTo(Status to) {
        if (!status.canGo(to)) throw new IllegalStateException("#" + id + ": cannot go " + status + " -> " + to);
        Status from = status;  status = to;
        for (OrderListener l : listeners) l.onChange(this, from, to); } }

class CancellationPolicy {
    static int fee(Status s, int total) {
        return switch (s) {
            case PLACED -> 0;
            case ACCEPTED -> total / 10;
            case PREPARING -> total / 2;
            default -> throw new IllegalStateException("cannot cancel once " + s); }; } }

class Ratings {
    private final Map<String, List<Integer>> stars = new HashMap<>();
    void rate(String who, int n) {
        if (n < 1 || n > 5) throw new IllegalArgumentException("stars must be 1 to 5, got " + n);
        stars.computeIfAbsent(who, k -> new ArrayList<>()).add(n); }
    double average(String who) {
        return stars.getOrDefault(who, List.of()).stream().mapToInt(i -> i).average().orElse(0); } }

class FoodApp {
    static final double MIN_PER_KM = 3;                                  // 20 km an hour
    final List<DeliveryPartner> partners = new ArrayList<>();
    final Ratings ratings = new Ratings();
    AssignmentStrategy strategy;
    FoodApp(AssignmentStrategy s) { strategy = s; }

    Order place(Customer c, Restaurant r, Map<String, Integer> dishes) {
        List<OrderLine> lines = new ArrayList<>();
        dishes.forEach((dish, qty) -> lines.add(new OrderLine(r.menu().find(dish), qty)));
        return new Order(c, r, lines); }

    synchronized boolean assign(Order o) {                               // pick and mark busy in ONE step
        List<DeliveryPartner> free = partners.stream().filter(p -> p.free).toList();
        Optional<DeliveryPartner> p = strategy.pick(free, o.restaurant.at());
        p.ifPresent(d -> { d.free = false;  o.partner = d; });
        return p.isPresent(); }

    long eta(Order o) {
        double rideIn = o.partner.at.km(o.restaurant.at()) * MIN_PER_KM;
        double rideOut = o.restaurant.at().km(o.customer.home()) * MIN_PER_KM;
        return Math.round(Math.max(o.restaurant.prepMinutes(), rideIn) + rideOut); }

    int cancel(Order o) {                                                // returns the refund
        int fee = CancellationPolicy.fee(o.status, o.total());
        o.moveTo(Status.CANCELLED);
        if (o.partner != null) o.partner.free = true;
        return o.total() - fee; }

    void deliver(Order o) {
        o.moveTo(Status.DELIVERED);
        o.partner.at = o.customer.home();  o.partner.free = true; } }

public class Main {
    public static void main(String[] args) {
        AssignmentStrategy nearest = (free, r) ->
            free.stream().min(Comparator.comparingDouble(p -> p.at.km(r)));
        FoodApp app = new FoodApp(nearest);
        app.partners.add(new DeliveryPartner("Ravi", new Point(6, 8)));
        app.partners.add(new DeliveryPartner("Deepa", new Point(0, 2)));

        Menu menu = new Menu(new MenuItem("Dal makhani", 180, true), new MenuItem("Butter roti", 20, true),
                             new MenuItem("Kheer", 90, false));
        Restaurant dhaba = new Restaurant("Sharma Dhaba", new Point(0, 0), menu, 15);
        Customer asha = new Customer("Asha", new Point(3, 4)), vikram = new Customer("Vikram", new Point(0, 4));

        try { app.place(asha, dhaba, Map.of("Kheer", 1)); }
        catch (IllegalArgumentException e) { System.out.println("Refused: " + e.getMessage()); }

        Map<String, Integer> dishes = new LinkedHashMap<>();
        dishes.put("Dal makhani", 2);  dishes.put("Butter roti", 4);
        Order a = app.place(asha, dhaba, dishes);
        a.subscribe((o, from, to) -> System.out.println("  [app] #" + o.id + " " + from + " -> " + to));
        System.out.println("Order #" + a.id + " total " + a.total());
        a.moveTo(Status.ACCEPTED);
        app.assign(a);
        System.out.println("Partner " + a.partner.name + ", ETA " + app.eta(a) + " min");
        a.moveTo(Status.PREPARING);  a.moveTo(Status.PICKED_UP);  app.deliver(a);
        app.ratings.rate(dhaba.name(), 5);  app.ratings.rate(a.partner.name, 4);

        Order b = app.place(vikram, dhaba, Map.of("Dal makhani", 1));
        b.moveTo(Status.ACCEPTED);  app.assign(b);
        System.out.println("Order #" + b.id + " partner " + b.partner.name + ", ETA " + app.eta(b) + " min");
        b.moveTo(Status.PREPARING);
        System.out.println("Vikram cancels while PREPARING: refund " + app.cancel(b) + " of " + b.total());
        System.out.println("Deepa free again? " + app.partners.get(1).free);
        System.out.printf("Ratings: %s %.1f, Deepa %.1f%n", dhaba.name(), app.ratings.average(dhaba.name()),
                          app.ratings.average("Deepa"));
        try { app.cancel(a); }
        catch (IllegalStateException e) { System.out.println("Cancel #" + a.id + ": " + e.getMessage()); }
    }
}

Real output:

Refused: Kheer is not available
Order #101 total 440
  [app] #101 PLACED -> ACCEPTED
Partner Deepa, ETA 30 min
  [app] #101 ACCEPTED -> PREPARING
  [app] #101 PREPARING -> PICKED_UP
  [app] #101 PICKED_UP -> DELIVERED
Order #102 partner Deepa, ETA 27 min
Vikram cancels while PREPARING: refund 90 of 180
Deepa free again? true
Ratings: Sharma Dhaba 5.0, Deepa 4.0
Cancel #101: cannot cancel once DELIVERED

What to notice:

  • Order #101 is 2 dal makhani (360) + 4 butter roti (80) = 440.
  • Deepa is nearest (2 km): ETA max(15, 6) + 15 = 30 min. After delivering she is at Asha's home (3, 4), 5 km from the dhaba, still nearer than Ravi (10 km), so she also gets #102: max(15, 15) + 4 × 3 = 27 min to Vikram at (0, 4).
  • Vikram cancels while PREPARING: fee 90, refund 90 of 180, and Deepa is free again.
  • Cancelling a delivered order is refused: cannot cancel once DELIVERED.

Practice

1. Write a fair strategy: the free partner who has waited longest, but only within 5 km of the restaurant.

Answer
import java.util.*;
record Point(double x, double y) { double km(Point o) { return Math.hypot(x - o.x, y - o.y); } }
record DeliveryPartner(String name, Point at, boolean free, int idleMinutes) {}
interface AssignmentStrategy { DeliveryPartner pick(List<DeliveryPartner> all, Point restaurant); }
class LongestWaiting implements AssignmentStrategy {     // fairness: who has waited longest, within 5 km
    public DeliveryPartner pick(List<DeliveryPartner> all, Point r) {
        return all.stream().filter(p -> p.free() && p.at().km(r) <= 5)
                  .max(Comparator.comparingInt(DeliveryPartner::idleMinutes)).orElseThrow(); } }
public class Main { public static void main(String[] args) {
    List<DeliveryPartner> team = List.of(new DeliveryPartner("Ravi", new Point(6, 8), true, 40),
                                         new DeliveryPartner("Deepa", new Point(0, 2), true, 5),
                                         new DeliveryPartner("Imran", new Point(3, 0), true, 25));
    System.out.println("Longest waiting nearby: " + new LongestWaiting().pick(team, new Point(0, 0)).name());
} }

Real output:

Longest waiting nearby: Imran

Ravi has waited longest (40 minutes) but is 10 km away, so he is filtered out. Of Deepa (5 minutes) and Imran (25 minutes), Imran has waited longer.

2. Prep time 10 minutes, the partner is 5 km from the restaurant, the customer 2 km away, 3 minutes per km. What is the ETA?

Answer

Ride in = 5 × 3 = 15 minutes, longer than the 10 minutes of cooking, so the partner decides: 15. Ride out = 2 × 3 = 6. ETA = 15 + 6 = 21 minutes.

3. Add an SMS listener that only sends a message when the order is PICKED_UP.

Answer

b.subscribe((id, s) -> { if (s == Status.PICKED_UP) System.out.println(" SMS: your food is on the way"); }); Nothing in Order changes: that is the point of Observer.

4. Why does moveTo check canGo before changing status?

Answer

So a refused move leaves the order exactly as it was. If it changed the status first and then threw, the order would be stuck in an illegal state (for example DELIVERED without a pickup).

5. Two threads call assign at the same time and both see Deepa as free. What goes wrong, and how does the mini project prevent it?

Answer

Both orders get Deepa: one partner, two orders at once. The mini project's assign is synchronized and sets d.free = false inside the same method, so the second thread sees her as busy.

6. A 500 rupee order is cancelled while ACCEPTED. What are the fee and the refund?

Answer

Fee = 500 / 10 = 50; refund = 500 − 50 = 450.

Quick quiz

Prep time 20 minutes, partner 4 km from the restaurant, customer 6 km from the restaurant, 3 minutes per km. ETA = max(prep, ride in) + ride out. What is the ETA? (a) 30 minutes (b) 38 minutes (c) 50 minutes (d) 32 minutes

Answer

(b) 38 minutes. Ride in = 4 × 3 = 12, shorter than the 20 minutes of cooking, so wait 20. Ride out = 6 × 3 = 18. 20 + 18 = 38. (50 adds everything; 30 forgets the cooking time.)

Interview questions

  1. What are the main classes of a food delivery app? Restaurant, Menu, MenuItem, Customer, Order (with order lines), DeliveryPartner, plus AssignmentStrategy, OrderListener, CancellationPolicy and Ratings.
  2. How do you stop orders for unavailable dishes? Build an order only through Menu.find(), which throws for missing or unavailable items.
  3. What is the order lifecycle? PLACED → ACCEPTED → PREPARING → PICKED_UP → DELIVERED, with CANCELLED only before pickup; an enum with canGo, and illegal moves throw.
  4. How do you choose a delivery partner? Behind an AssignmentStrategy interface: nearest free first, swappable for fairness or load rules.
  5. How do you estimate ETA? max(prep time, ride to restaurant) + ride to customer, with distance / speed; improve with traffic-aware speeds.
  6. Why Observer for tracking? The order notifies every subscriber on each change; no polling, and new screens don't change Order.
  7. What are your cancellation rules? By status: free, 10%, 50%, then not allowed after pickup; refund = total − fee.
  8. How do you keep ratings honest? Validate 1 to 5, one rating per order, keep the average (and count) per restaurant and partner.
  9. How do you avoid assigning one partner twice? Pick and mark busy in one atomic step: synchronized in one JVM, a conditional database update across servers.
  10. What changes for a ride-sharing app? Almost the same shape: Driver for DeliveryPartner, Trip for Order, a matching strategy and fare calculation (next episode).

Glossary

Term Meaning, with an example
Food delivery requirements What the app must do: browse, order, assign, track, cancel, rate
Restaurant A place that cooks food, with a name and a menu: Sharma Dhaba
Menu A restaurant's list of dishes: dal makhani, kheer
MenuItem One dish with a name, price and available flag: MenuItem("Kheer", 90, false)
Customer The person who orders: Customer("Asha")
Order Who ordered which dishes, how many, and the status: Asha, 2 x dal makhani, PLACED
OrderLine One dish and its quantity inside an order: OrderLine(dal, 2)
Status Where an order is right now: PREPARING
Order lifecycle The fixed steps of an order: PLACED → ACCEPTED → PREPARING → PICKED_UP → DELIVERED, or CANCELLED
Illegal jump A status move the lifecycle doesn't allow: PREPARING → DELIVERED
State machine Only allowed moves between states; others throw
enum A type with a fixed set of named values: Status.PLACED
ordinal() An enum value's position: PLACED is 0, ACCEPTED is 1
record A short class that just holds data: record Customer(String name) {}
DeliveryPartner The person who rides the food to the customer; free or busy: Deepa at (0, 2)
Delivery assignment strategy The swappable rule that picks a partner for an order: NearestFree
Strategy pattern One interface, many interchangeable rule classes
Interface A list of methods a class promises to have: pick(...)
FirstFree The naive strategy: first free partner in the list (Ravi, 10 km)
NearestFree The free partner closest to the restaurant (Deepa, 2 km)
Grid coordinates Positions in km on a simple map: Asha at (3, 4)
Straight-line distance Math.hypot(dx, dy): (0, 0) to (3, 4) is 5 km
ETA (estimated time of arrival) How long until the food arrives: max(prep, ride in) + ride out = 30 min
Prep time Minutes the kitchen needs to cook: 15
ETA estimation Computing the ETA from prep time, distance and speed
Order tracking Telling everyone about each status change of an order
Polling Asking "any news?" again and again: 40 requests, 4 with news
Hard-coded calls The subject calling each screen by name; every new screen edits the class
Observer pattern Listeners subscribe to a subject and are notified of changes
Subject The thing being watched: the Order
Observer / listener The thing told about changes: OrderListener (customer app, kitchen, partner)
Subscribe / notify Add yourself to the list / the subject calls everyone on the list
Lambda A short unnamed function: (id, s) -> System.out.println(...)
Cancellation rules Fees and limits for cancelling, by status: free, 10%, 50%, not after pickup
CancellationPolicy The class that turns a status into a fee or a refusal
Refund Money returned: total − cancellation fee (90 of 180)
Ratings 1 to 5 stars per restaurant or partner, validated, averaged: 4.5
Average rating Sum of stars / number of ratings: (5 + 4) / 2 = 4.5
IllegalArgumentException Java's exception for a bad argument: Kheer is not available
IllegalStateException Java's exception for a call at the wrong time: cannot go PREPARING -> DELIVERED
synchronized Java keyword: only one thread at a time runs this method
Optional A box that may hold a value or be empty: no free partner → empty
Comparator An object that compares two things: by distance to the restaurant

Summary

  • Restaurant, Menu, MenuItem, Customer, Order: an order is built only through Menu.find(), so unavailable dishes are refused (Kheer is not available).
  • The order lifecycle is an enum that moves one step at a time; an illegal jump throws cannot go PREPARING -> DELIVERED.
  • A DeliveryPartner is chosen by a swappable AssignmentStrategy: first free sent Ravi 10 km (ETA 45 min), nearest free sent Deepa 2 km (ETA 30 min).
  • ETA = max(prep time, ride in) + ride out, at 3 minutes per km.
  • Order tracking with Observer replaces polling (40 requests, 4 with news): the order tells every listener.
  • Cancellation rules follow the status (0 / 36 / 180 on a 360 order; refused after pickup), and ratings are 1 to 5 stars, averaged per restaurant and partner.
  • Next episode: design a ride-sharing app: riders, drivers, trips, driver matching and fares.