diff --git a/README.md b/README.md
index c9f163e..87f68ea 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ One module per article. This repository currently holds:
| [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit |
| [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit |
| [`experienced-2-3y`](experienced-2-3y/) | Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers) | this commit |
+| [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit |
## `collections` module
diff --git a/food-delivery/README.md b/food-delivery/README.md
new file mode 100644
index 0000000..55ce8e3
--- /dev/null
+++ b/food-delivery/README.md
@@ -0,0 +1,70 @@
+# food-delivery
+
+Companion code for the ankurm.com article **Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java**.
+
+The core of an order-to-door system in plain Java: an order lifecycle as a state table, restaurant search with two rankings, bills in exact
+paise, three rider-assignment strategies behind one interface, a dispatcher with a first-in-first-out waiting queue, atomic stock and kitchen
+capacity, idempotent placing, and a seeded minute-by-minute simulation that compares the strategies on identical demand. Every figure and
+console line in the article is quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. There is no
+`docs/` folder: the explanations live in the article itself.
+
+## Versions
+
+| Component | Version | Verified against |
+|---|---|---|
+| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` |
+| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA; 6.2.0-M1 is a milestone) |
+| Maven | 3.9.11 | `mvn -version` |
+| maven-surefire-plugin | 3.6.1 | `maven-metadata.xml` on Maven Central (latest GA) |
+
+No frameworks and no runtime dependencies: everything in `src/main` is plain Java.
+
+## Quickstart
+
+```bash
+cd food-delivery
+export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
+./scripts/run-all.sh # runs every test and regenerates output/*.txt
+```
+
+The first Maven run must be online so the plugins land in the local cache. Three transcripts contain figures that depend on thread timing
+(`09-stock-race.txt`, `10-partner-claim.txt`, `11b-reject-vs-cancel.txt`); they say so in their first lines and can differ from run to run.
+Every other transcript is identical on every run.
+
+## The pieces
+
+| Class | Role |
+|---|---|
+| `OrderStatus` | the whole lifecycle as one table: eight legal moves out of sixty-four |
+| `Order` | the only place a status changes; every mutator is synchronized, so a race on one order has one winner |
+| `FoodDeliveryService` | the facade: search, place, accept, reject, prepare, ready, pick up, deliver, cancel |
+| `Restaurant` | menu, rating, location and a kitchen capacity taken with a compare-and-set loop |
+| `DeliveryPartner` | a rider whose claim is one `compareAndSet(AVAILABLE, BUSY)` |
+| `PartnerAssignmentStrategy` | picks one rider from a list; `NearestPartner`, `RatedWithinRadius`, `LongestIdle` |
+| `Dispatcher` | matches accepted orders to riders; orders with no rider wait in a FIFO queue |
+| `StockLedger`, `Inventory` | all-or-nothing reservation of limited portions under one lock per restaurant |
+| `PricingPolicy`, `StandardPricing` | subtotal, distance fee, free-delivery threshold, 5% tax rounded half up |
+| `RestaurantRanking` | `NEAREST` and `TOP_RATED`, both ending in the id so ties never swap |
+| `OrderListener`, `OrderEvent` | Observer: every status change and rider assignment is published |
+| `Simulation` | seeded city and demand; runs a strategy to the last delivery |
+| `FoodDeliveryException` | sealed family of business-rule failures |
+
+The tests also hold two deliberately wrong versions, `NaiveInventory` and a naive rider claim, so the failures can be reproduced.
+
+## Transcripts
+
+| File | Written by | What it shows |
+|---|---|---|
+| `01-happy-path.txt` | `LifecycleTest` | one order from placed to delivered: bill, rider, event log |
+| `02-state-machine.txt`, `02b-illegal-moves.txt`, `02c-no-partner.txt` | `StateMachineTest` | the 8x8 table, exact messages for illegal moves, pick-up without a rider |
+| `03-pricing.txt` | `PricingTest` | delivery fee by distance, free delivery, half-up tax |
+| `04-validation.txt` | `ValidationTest` | ten bad requests with exact messages, stock untouched |
+| `05-search.txt` | `SearchTest` | the same restaurants ranked two ways |
+| `06-assignment.txt`, `06b-radius-fallback.txt` | `AssignmentTest` | one order, three strategies, three riders |
+| `07-dispatch-queue.txt`, `07b-cancel-while-waiting.txt` | `DispatchQueueTest` | the waiting queue and what frees it |
+| `08-cancel-reject.txt` | `CancelRejectTest` | stock, kitchen slot and rider all come back |
+| `09-stock-race.txt` | `StockRaceTest` | 16 buyers, 10 portions: naive versus locked |
+| `10-partner-claim.txt`, `10b-dispatch-under-load.txt` | `PartnerClaimTest` | naive versus compare-and-set; 200 orders, 20 riders, 8 threads |
+| `11-accept-capacity.txt`, `11b-reject-vs-cancel.txt` | `AcceptRaceTest` | capacity holds; reject versus cancel has one winner |
+| `12-idempotency.txt` | `IdempotencyTest` | a double tap and 16 racing retries create one order |
+| `13-simulation.txt` | `SimulationTest` | three strategies at three load levels on identical orders |
diff --git a/food-delivery/output/01-happy-path.txt b/food-delivery/output/01-happy-path.txt
new file mode 100644
index 0000000..01c6ffd
--- /dev/null
+++ b/food-delivery/output/01-happy-path.txt
@@ -0,0 +1,16 @@
+One order, from placed to delivered
+===================================
+
+Meera (4,4) orders from Biryani House (2,3), 3 km away
+ food Rs 547.00 + delivery Rs 44.00 + tax Rs 27.35 = Rs 618.35
+
+Event log
+ t=00 O-0001 - -> PLACED
+ t=02 O-0001 PLACED -> ACCEPTED
+ t=02 O-0001 partner P1 assigned
+ t=03 O-0001 ACCEPTED -> PREPARING
+ t=14 O-0001 PREPARING -> READY
+ t=15 O-0001 READY -> PICKED_UP
+ t=21 O-0001 PICKED_UP -> DELIVERED
+
+After delivery: Imran is AVAILABLE at (4,4), idle since minute 21, deliveries 1
diff --git a/food-delivery/output/02-state-machine.txt b/food-delivery/output/02-state-machine.txt
new file mode 100644
index 0000000..b6cd70d
--- /dev/null
+++ b/food-delivery/output/02-state-machine.txt
@@ -0,0 +1,14 @@
+Order state machine: which of the 64 moves are legal
+====================================================
+
+from \ to PLA ACC PRE REA PIC DEL REJ CAN
+PLACED . yes . . . . yes yes
+ACCEPTED . . yes . . . . yes
+PREPARING . . . yes . . . .
+READY . . . . yes . . .
+PICKED_UP . . . . . yes . .
+DELIVERED . . . . . . . .
+REJECTED . . . . . . . .
+CANCELLED . . . . . . . .
+
+legal moves: 8 of 64
diff --git a/food-delivery/output/02b-illegal-moves.txt b/food-delivery/output/02b-illegal-moves.txt
new file mode 100644
index 0000000..1322d29
--- /dev/null
+++ b/food-delivery/output/02b-illegal-moves.txt
@@ -0,0 +1,9 @@
+Illegal moves: the exact message, and the status afterwards
+===========================================================
+
+PLACED, markReady : O-0001 cannot move from PLACED to READY; allowed from PLACED: [ACCEPTED, REJECTED, CANCELLED]
+status afterwards : PLACED
+
+PREPARING, cancel : O-0001 cannot move from PREPARING to CANCELLED; allowed from PREPARING: [READY]
+
+DELIVERED, cancel : O-0001 cannot move from DELIVERED to CANCELLED; allowed from DELIVERED: []
diff --git a/food-delivery/output/02c-no-partner.txt b/food-delivery/output/02c-no-partner.txt
new file mode 100644
index 0000000..2d45bea
--- /dev/null
+++ b/food-delivery/output/02c-no-partner.txt
@@ -0,0 +1,6 @@
+READY to PICKED_UP is legal on paper, but not without a rider
+=============================================================
+
+all riders offline, order READY
+pickUp: O-0001 has no delivery partner yet, so it cannot be picked up
+status afterwards: READY
diff --git a/food-delivery/output/03-pricing.txt b/food-delivery/output/03-pricing.txt
new file mode 100644
index 0000000..1d56a35
--- /dev/null
+++ b/food-delivery/output/03-pricing.txt
@@ -0,0 +1,9 @@
+Bills: delivery by distance, free delivery from Rs 599, tax rounded half up
+===========================================================================
+
+food Rs 99.00 6 km -> food Rs 99.00 + delivery Rs 68.00 + tax Rs 4.95 = Rs 171.95
+food Rs 547.00 3 km -> food Rs 547.00 + delivery Rs 44.00 + tax Rs 27.35 = Rs 618.35
+food Rs 599.00 12 km -> food Rs 599.00 + delivery Rs 0.00 + tax Rs 29.95 = Rs 628.95
+food Rs 598.99 12 km -> food Rs 598.99 + delivery Rs 116.00 + tax Rs 29.95 = Rs 744.94
+food Rs 100.10 1 km -> food Rs 100.10 + delivery Rs 28.00 + tax Rs 5.01 = Rs 133.11
+food Rs 100.30 1 km -> food Rs 100.30 + delivery Rs 28.00 + tax Rs 5.02 = Rs 133.32
diff --git a/food-delivery/output/04-validation.txt b/food-delivery/output/04-validation.txt
new file mode 100644
index 0000000..f8115f4
--- /dev/null
+++ b/food-delivery/output/04-validation.txt
@@ -0,0 +1,15 @@
+Bad requests: the exact message for each, and the stock afterwards
+==================================================================
+
+blank key InvalidOrder: an idempotency key is required
+unknown customer NotFound: customer C9 not found
+unknown restaurant NotFound: restaurant R9 not found
+empty cart InvalidOrder: the cart is empty
+item from another menu InvalidOrder: Biryani House has no item p1
+quantity zero InvalidOrder: quantity for Chicken Biryani must be 1 to 20, got 0
+quantity 21 InvalidOrder: quantity for Chicken Biryani must be 1 to 20, got 21
+24 km away InvalidOrder: Pizza Point is 24 km away; we deliver up to 15 km
+more than the stock OutOfStock: b1: wanted 6, only 5 left
+closed restaurant Dosa Corner is closed
+
+two-line cart where the second line is short: Veg Biryani stock still 3
diff --git a/food-delivery/output/05-search.txt b/food-delivery/output/05-search.txt
new file mode 100644
index 0000000..d3b84f7
--- /dev/null
+++ b/food-delivery/output/05-search.txt
@@ -0,0 +1,20 @@
+Search from Meera at (4,4): nearest first versus top rated first
+================================================================
+
+blank query, 10 km, NEAREST
+ Biryani House 3 km rating 4.4
+ Dosa Corner 6 km rating 4.6
+ Pizza Point 6 km rating 4.1
+ Burger Lab 6 km rating 3.9
+
+blank query, 10 km, TOP_RATED
+ Dosa Corner 6 km rating 4.6
+ Biryani House 3 km rating 4.4
+ Pizza Point 6 km rating 4.1
+ Burger Lab 6 km rating 3.9
+
+query "burger"
+ Burger Lab: [Chicken Burger, Veg Burger]
+
+radius 4 km: [Biryani House]
+radius 4 km after Biryani House closes: 0 results
diff --git a/food-delivery/output/06-assignment.txt b/food-delivery/output/06-assignment.txt
new file mode 100644
index 0000000..c0caacd
--- /dev/null
+++ b/food-delivery/output/06-assignment.txt
@@ -0,0 +1,12 @@
+Same order, same three free riders, three strategies
+====================================================
+
+Order pickup: Biryani House (2,3)
+ P1 Imran at (3,3) 1 km away rating 4.2 idle since minute 30
+ P2 Kavya at (6,2) 5 km away rating 4.8 idle since minute 20
+ P3 Sunil at (2,6) 3 km away rating 4.5 idle since minute 10
+
+nearest -> P1
+rated<=5km -> P2 (all three are within 5 km, so the best rating wins)
+rated<=2km -> P1 (only P1 is within 2 km)
+longest-idle -> P3 (P3 has waited longest)
diff --git a/food-delivery/output/06b-radius-fallback.txt b/food-delivery/output/06b-radius-fallback.txt
new file mode 100644
index 0000000..f180d38
--- /dev/null
+++ b/food-delivery/output/06b-radius-fallback.txt
@@ -0,0 +1,4 @@
+rated<=0km: nobody is that close, so it falls back to the nearest
+=================================================================
+
+assigned: P1
diff --git a/food-delivery/output/07-dispatch-queue.txt b/food-delivery/output/07-dispatch-queue.txt
new file mode 100644
index 0000000..df3cd9b
--- /dev/null
+++ b/food-delivery/output/07-dispatch-queue.txt
@@ -0,0 +1,17 @@
+One rider, three orders: the queue and what frees it
+====================================================
+
+three orders accepted, one rider (P1) online
+ O-0001 rider P1
+ O-0002 rider null
+ O-0003 rider null
+ waiting: [O-0002, O-0003]
+
+O-0001 delivered at minute 20, P1 free again
+ O-0002 rider P1
+ O-0003 rider null
+ waiting: [O-0003]
+
+P3 comes online at minute 20
+ O-0003 rider P3
+ waiting: []
diff --git a/food-delivery/output/07b-cancel-while-waiting.txt b/food-delivery/output/07b-cancel-while-waiting.txt
new file mode 100644
index 0000000..1605e41
--- /dev/null
+++ b/food-delivery/output/07b-cancel-while-waiting.txt
@@ -0,0 +1,8 @@
+A cancelled order does not take a rider when one appears
+========================================================
+
+no riders online; waiting: [O-0001, O-0002]
+O-0001 cancelled, then P1 comes online
+ O-0001 rider null, status CANCELLED
+ O-0002 rider P1
+ waiting: []
diff --git a/food-delivery/output/08-cancel-reject.txt b/food-delivery/output/08-cancel-reject.txt
new file mode 100644
index 0000000..2a0f231
--- /dev/null
+++ b/food-delivery/output/08-cancel-reject.txt
@@ -0,0 +1,9 @@
+Cancel and reject give back stock, kitchen slot and rider
+=========================================================
+
+start : stock b1=10, kitchen slots used=0, P1=AVAILABLE
+placed 3 x b1 : stock b1=7, kitchen slots used=0, P1=AVAILABLE
+cancelled while PLACED : stock b1=10, kitchen slots used=0, P1=AVAILABLE
+placed 4, accepted : stock b1=6, kitchen slots used=1, P1=BUSY (rider P1)
+cancelled while ACCEPTED : stock b1=10, kitchen slots used=0, P1=AVAILABLE
+placed 2, rejected : stock b1=10, kitchen slots used=0, P1=AVAILABLE
diff --git a/food-delivery/output/09-stock-race.txt b/food-delivery/output/09-stock-race.txt
new file mode 100644
index 0000000..12c3256
--- /dev/null
+++ b/food-delivery/output/09-stock-race.txt
@@ -0,0 +1,7 @@
+16 buyers, 10 portions, 5000 rounds
+===================================
+
+Timing dependent: the naive counts differ from run to run; the locked counts never do.
+
+naive (check, then write): rounds that sold more than 10: 21 of 5000, worst round sold 12
+locked (check and write together): rounds that oversold: 0, undersold: 0 of 5000
diff --git a/food-delivery/output/10-partner-claim.txt b/food-delivery/output/10-partner-claim.txt
new file mode 100644
index 0000000..df7577b
--- /dev/null
+++ b/food-delivery/output/10-partner-claim.txt
@@ -0,0 +1,8 @@
+16 orders reach for one free rider, 5000 rounds
+===============================================
+
+Timing dependent: the naive count differs from run to run; the compare-and-set count never does.
+
+naive, check then write, nothing in between: rounds where more than one order got the rider: 0 of 5000, most winners in one round 1
+naive, with a yield between the check and the write: rounds where more than one order got the rider: 389 of 5000, most winners in one round 7
+atomic (compare-and-set), no gap needed: rounds with anything other than one winner: 0 of 5000
diff --git a/food-delivery/output/10b-dispatch-under-load.txt b/food-delivery/output/10b-dispatch-under-load.txt
new file mode 100644
index 0000000..f93e4d8
--- /dev/null
+++ b/food-delivery/output/10b-dispatch-under-load.txt
@@ -0,0 +1,6 @@
+200 orders accepted from 8 threads, 20 riders
+=============================================
+
+orders with a rider: 20
+distinct riders used : 20
+still waiting : 180
diff --git a/food-delivery/output/11-accept-capacity.txt b/food-delivery/output/11-accept-capacity.txt
new file mode 100644
index 0000000..2a4a561
--- /dev/null
+++ b/food-delivery/output/11-accept-capacity.txt
@@ -0,0 +1,7 @@
+Burger Lab cooks 2 at a time: 50 orders, 16 threads tapping accept
+==================================================================
+
+rounds: 300
+accepted per round: 2 (every round)
+refused per round : 48 (every round)
+totals: accepted 600, refused 14400
diff --git a/food-delivery/output/11b-reject-vs-cancel.txt b/food-delivery/output/11b-reject-vs-cancel.txt
new file mode 100644
index 0000000..bc22779
--- /dev/null
+++ b/food-delivery/output/11b-reject-vs-cancel.txt
@@ -0,0 +1,7 @@
+The restaurant rejects while the customer cancels, 2000 rounds
+==============================================================
+
+The thread released first tends to win, so the two roles swap threads every round to exercise both orders.
+Who wins depends on timing; that exactly one wins, and that stock comes back once, never does.
+
+rounds: 2000, reject won 1000, cancel won 1000
diff --git a/food-delivery/output/12-idempotency.txt b/food-delivery/output/12-idempotency.txt
new file mode 100644
index 0000000..46f3acc
--- /dev/null
+++ b/food-delivery/output/12-idempotency.txt
@@ -0,0 +1,6 @@
+Double tap and client retries: one key, one order
+=================================================
+
+same key twice: O-0001 and O-0001, stock left 8
+new key : O-0002, stock left 6
+16 threads, one key: distinct orders 1, stock left 5
diff --git a/food-delivery/output/13-simulation.txt b/food-delivery/output/13-simulation.txt
new file mode 100644
index 0000000..f1dc427
--- /dev/null
+++ b/food-delivery/output/13-simulation.txt
@@ -0,0 +1,25 @@
+12 restaurants, 20x20 km grid, 240 minutes of orders, seed 42
+=============================================================
+
+Every strategy faces the identical orders. Columns: average and 90th percentile minutes from placing to door,
+average km a rider rides empty to the restaurant, average minutes ready food waits for a rider, average minutes
+a rider waits at the restaurant for the food, longest the waiting queue got, deliveries per rider (fewest-most).
+
+Comfortable: 40 riders, 200 orders
+ strategy avg min p90 min empty km food wait rider wt max queue per rider
+ nearest 26.4 34 4.1 0.4 6.3 0 2-8
+ rated<=5km 26.4 34 4.3 0.4 5.9 0 0-8
+ longest-idle 35.8 54 10.9 9.8 2.2 0 4-7
+
+Tight: 30 riders, 200 orders
+ strategy avg min p90 min empty km food wait rider wt max queue per rider
+ nearest 30.4 43 7.3 4.5 3.9 1 4-8
+ rated<=5km 29.6 40 6.8 3.6 4.0 0 4-9
+ longest-idle 42.0 59 12.5 16.1 1.4 13 5-8
+
+Saturated: 30 riders, 300 orders
+ strategy avg min p90 min empty km food wait rider wt max queue per rider
+ nearest 93.1 147 12.6 67.4 0.5 90 8-12
+ rated<=5km 98.5 156 13.0 72.8 0.4 99 7-12
+ longest-idle 93.1 147 12.6 67.4 0.5 90 8-12
+
diff --git a/food-delivery/pom.xml b/food-delivery/pom.xml
new file mode 100644
index 0000000..5dc5399
--- /dev/null
+++ b/food-delivery/pom.xml
@@ -0,0 +1,64 @@
+
+
+ 4.0.0
+ com.ankurm.interviewlab
+ food-delivery
+ 1.0.0
+ jar
+
+ java-interview-lab :: food-delivery
+
+ Runnable companion code for ankurm.com's "Low-Level Design: Food Delivery App in Java" article: order state machine, partner assignment
+ strategies, a dispatcher with a pending queue, atomic stock and kitchen capacity, and a seeded tick simulation.
+
+
+
+ 25
+ UTF-8
+ 6.1.3
+
+
+
+
+
+ org.junit
+ junit-bom
+ ${junit.version}
+ pom
+ import
+
+
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.14.0
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.6.1
+
+ -Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8
+
+
+
+
+
diff --git a/food-delivery/scripts/run-all.sh b/food-delivery/scripts/run-all.sh
new file mode 100755
index 0000000..38df9a6
--- /dev/null
+++ b/food-delivery/scripts/run-all.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
+# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
+# in the article are assertions: they fail the build the moment they stop being true.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+mkdir -p output
+mvn -B -q -T1 test
+echo "done:"; ls -1 output
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Bill.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Bill.java
new file mode 100644
index 0000000..0e211f9
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Bill.java
@@ -0,0 +1,7 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+public record Bill(long subtotalPaise, long deliveryFeePaise, long taxPaise) {
+ public long totalPaise() {
+ return subtotalPaise + deliveryFeePaise + taxPaise;
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Customer.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Customer.java
new file mode 100644
index 0000000..a1324b5
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Customer.java
@@ -0,0 +1,3 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+public record Customer(String id, String name, Point location) {}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/DeliveryPartner.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/DeliveryPartner.java
new file mode 100644
index 0000000..8798cca
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/DeliveryPartner.java
@@ -0,0 +1,59 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/** A rider. The claim on a rider is one compare-and-set, so two orders can never both get the same rider. */
+public final class DeliveryPartner {
+ private final String id;
+ private final String name;
+ private final double rating;
+ private final AtomicReference status = new AtomicReference<>(PartnerStatus.AVAILABLE);
+ private final AtomicInteger deliveries = new AtomicInteger();
+ private volatile Point location;
+ private volatile long idleSince;
+
+ public DeliveryPartner(String id, String name, double rating, Point location) {
+ this.id = id;
+ this.name = name;
+ this.rating = rating;
+ this.location = location;
+ }
+
+ public String id() { return id; }
+ public String name() { return name; }
+ public double rating() { return rating; }
+ public Point location() { return location; }
+ public long idleSince() { return idleSince; }
+ public int deliveries() { return deliveries.get(); }
+ public PartnerStatus status() { return status.get(); }
+ public boolean isAvailable() { return status.get() == PartnerStatus.AVAILABLE; }
+
+ /** Atomically AVAILABLE to BUSY. Exactly one caller out of any number of racing callers gets true. */
+ public boolean tryClaim() {
+ return status.compareAndSet(PartnerStatus.AVAILABLE, PartnerStatus.BUSY);
+ }
+
+ /** Puts a claimed partner back without touching location or idle time (an assignment that did not stick). */
+ void unclaim() {
+ status.compareAndSet(PartnerStatus.BUSY, PartnerStatus.AVAILABLE);
+ }
+
+ /** A finished (or cancelled) job: the partner is where the job ended and idle from now. */
+ void release(Point where, long now) {
+ this.location = where;
+ this.idleSince = now;
+ status.compareAndSet(PartnerStatus.BUSY, PartnerStatus.AVAILABLE);
+ }
+
+ void recordDelivery() { deliveries.incrementAndGet(); }
+
+ public boolean goOffline() {
+ return status.compareAndSet(PartnerStatus.AVAILABLE, PartnerStatus.OFFLINE);
+ }
+
+ public boolean goOnline(long now) {
+ idleSince = now;
+ return status.compareAndSet(PartnerStatus.OFFLINE, PartnerStatus.AVAILABLE);
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Dispatcher.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Dispatcher.java
new file mode 100644
index 0000000..3de3cb4
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Dispatcher.java
@@ -0,0 +1,81 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.BiConsumer;
+
+/**
+ * Matches accepted orders to free partners. Orders that find nobody wait in a first-in-first-out queue and are
+ * matched the moment a partner frees up. A single drain lock keeps the queue consistent; the partner itself is
+ * still claimed with a compare-and-set, so a partner going offline at the same moment cannot be double-booked.
+ */
+public final class Dispatcher {
+ private final List partners = new CopyOnWriteArrayList<>();
+ private final Queue pending = new ConcurrentLinkedQueue<>();
+ private final Object drainLock = new Object();
+ private final PartnerAssignmentStrategy strategy;
+ private final BiConsumer onAssigned;
+
+ Dispatcher(PartnerAssignmentStrategy strategy, BiConsumer onAssigned) {
+ this.strategy = strategy;
+ this.onAssigned = onAssigned;
+ }
+
+ void register(DeliveryPartner partner) {
+ partners.add(partner);
+ }
+
+ public int pendingCount() { return pending.size(); }
+
+ public List pendingIds() { return pending.stream().map(Order::id).toList(); }
+
+ void dispatch(Order order) {
+ pending.add(order);
+ drain();
+ }
+
+ void partnerFreed(DeliveryPartner partner, Point where, long now) {
+ partner.release(where, now);
+ drain();
+ }
+
+ void partnerOnline(DeliveryPartner partner, long now) {
+ partner.goOnline(now);
+ drain();
+ }
+
+ private void drain() {
+ synchronized (drainLock) {
+ while (true) {
+ Order head = pending.peek();
+ if (head == null) return;
+ if (!head.needsPartner()) { // cancelled or already served while it waited
+ pending.poll();
+ continue;
+ }
+ DeliveryPartner claimed = claimFor(head);
+ if (claimed == null) return; // nobody free: the head waits, and so does everyone behind it
+ pending.poll();
+ if (head.tryAssign(claimed.id())) {
+ onAssigned.accept(head, claimed);
+ } else {
+ claimed.unclaim(); // the order was cancelled between the check and the assignment
+ }
+ }
+ }
+ }
+
+ private DeliveryPartner claimFor(Order order) {
+ List candidates = new ArrayList<>(partners.stream().filter(DeliveryPartner::isAvailable).toList());
+ while (!candidates.isEmpty()) {
+ DeliveryPartner pick = strategy.pick(order.pickup(), candidates).orElse(null);
+ if (pick == null) return null;
+ if (pick.tryClaim()) return pick;
+ candidates.remove(pick); // somebody else got there first; choose again from the rest
+ }
+ return null;
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryException.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryException.java
new file mode 100644
index 0000000..2074a7a
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryException.java
@@ -0,0 +1,36 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** Every business-rule failure is one of these, so a caller can catch the family or a single case. */
+public abstract sealed class FoodDeliveryException extends RuntimeException {
+ protected FoodDeliveryException(String message) {
+ super(message);
+ }
+
+ public static final class NotFound extends FoodDeliveryException {
+ public NotFound(String what) { super(what + " not found"); }
+ }
+
+ public static final class InvalidOrder extends FoodDeliveryException {
+ public InvalidOrder(String why) { super(why); }
+ }
+
+ public static final class OutOfStock extends FoodDeliveryException {
+ public OutOfStock(String why) { super(why); }
+ }
+
+ public static final class KitchenBusy extends FoodDeliveryException {
+ public KitchenBusy(String restaurant, int capacity) {
+ super(restaurant + " is at kitchen capacity (" + capacity + " active orders)");
+ }
+ }
+
+ public static final class IllegalTransition extends FoodDeliveryException {
+ public IllegalTransition(String orderId, OrderStatus from, OrderStatus to) {
+ super(orderId + " cannot move from " + from + " to " + to + "; allowed from " + from + ": " + from.allowedNext());
+ }
+ }
+
+ public static final class NoPartnerAssigned extends FoodDeliveryException {
+ public NoPartnerAssigned(String orderId) { super(orderId + " has no delivery partner yet, so it cannot be picked up"); }
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryService.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryService.java
new file mode 100644
index 0000000..7d43616
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/FoodDeliveryService.java
@@ -0,0 +1,203 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicLong;
+
+/** The facade a controller would call. It owns the rules; {@link Order} owns the status. */
+public final class FoodDeliveryService {
+ public static final int MAX_QUANTITY_PER_ITEM = 20;
+ public static final int MAX_DELIVERY_KM = 15;
+
+ private final Map restaurants = new ConcurrentHashMap<>();
+ private final Map customers = new ConcurrentHashMap<>();
+ private final Map partners = new ConcurrentHashMap<>();
+ private final Map orders = new ConcurrentHashMap<>();
+ private final Map byIdempotencyKey = new ConcurrentHashMap<>();
+ private final List listeners = new CopyOnWriteArrayList<>();
+ private final AtomicLong sequence = new AtomicLong();
+ private final TickClock clock;
+ private final PricingPolicy pricing;
+ private final StockLedger stock;
+ private final Dispatcher dispatcher;
+
+ public FoodDeliveryService(TickClock clock, PricingPolicy pricing, StockLedger stock, PartnerAssignmentStrategy strategy) {
+ this.clock = clock;
+ this.pricing = pricing;
+ this.stock = stock;
+ this.dispatcher = new Dispatcher(strategy, (order, partner) ->
+ listeners.forEach(l -> l.partnerAssigned(order.id(), partner.id(), clock.now())));
+ }
+
+ // ---- registration ------------------------------------------------------------------------------------------
+
+ public void addRestaurant(Restaurant r) { restaurants.put(r.id(), r); }
+ public void addCustomer(Customer c) { customers.put(c.id(), c); }
+
+ public void addPartner(DeliveryPartner p) {
+ partners.put(p.id(), p);
+ dispatcher.register(p);
+ }
+
+ public void addListener(OrderListener l) { listeners.add(l); }
+
+ public Dispatcher dispatcher() { return dispatcher; }
+ public StockLedger stock() { return stock; }
+ public Restaurant restaurant(String id) { return find(restaurants, id, "restaurant"); }
+ public DeliveryPartner partner(String id) { return find(partners, id, "partner"); }
+ public Order order(String id) { return find(orders, id, "order"); }
+
+ // ---- search ------------------------------------------------------------------------------------------------
+
+ /** Open restaurants within {@code radiusKm} of {@code from} that serve a dish containing {@code dish} (blank matches all). */
+ public List search(Point from, String dish, int radiusKm, RestaurantRanking ranking) {
+ String needle = dish == null ? "" : dish.toLowerCase();
+ List results = new ArrayList<>();
+ for (Restaurant r : restaurants.values()) {
+ int km = from.km(r.location());
+ if (!r.isOpen() || km > radiusKm) continue;
+ List matches = r.menu().values().stream()
+ .map(MenuItem::name).filter(n -> n.toLowerCase().contains(needle)).sorted().toList();
+ if (!matches.isEmpty()) results.add(new RestaurantResult(r, km, matches));
+ }
+ results.sort(ranking);
+ return results;
+ }
+
+ // ---- placing -----------------------------------------------------------------------------------------------
+
+ /**
+ * Places an order. The same idempotency key always returns the same order, so a double tap or a client
+ * retry after a timeout cannot create (or charge for) a second one.
+ */
+ public Order placeOrder(String idempotencyKey, String customerId, String restaurantId, Map items) {
+ if (idempotencyKey == null || idempotencyKey.isBlank()) {
+ throw new FoodDeliveryException.InvalidOrder("an idempotency key is required");
+ }
+ return byIdempotencyKey.computeIfAbsent(idempotencyKey, k -> create(customerId, restaurantId, items));
+ }
+
+ private Order create(String customerId, String restaurantId, Map items) {
+ Customer customer = find(customers, customerId, "customer");
+ Restaurant restaurant = find(restaurants, restaurantId, "restaurant");
+ if (!restaurant.isOpen()) throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " is closed");
+ if (items == null || items.isEmpty()) throw new FoodDeliveryException.InvalidOrder("the cart is empty");
+ int km = customer.location().km(restaurant.location());
+ if (km > MAX_DELIVERY_KM) {
+ throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " is " + km + " km away; we deliver up to " + MAX_DELIVERY_KM + " km");
+ }
+ List lines = new ArrayList<>();
+ long subtotal = 0;
+ for (var e : items.entrySet()) {
+ MenuItem item = restaurant.item(e.getKey());
+ if (item == null) throw new FoodDeliveryException.InvalidOrder(restaurant.name() + " has no item " + e.getKey());
+ int qty = e.getValue();
+ if (qty < 1 || qty > MAX_QUANTITY_PER_ITEM) {
+ throw new FoodDeliveryException.InvalidOrder("quantity for " + item.name() + " must be 1 to " + MAX_QUANTITY_PER_ITEM + ", got " + qty);
+ }
+ OrderLine line = new OrderLine(item.id(), item.name(), qty, item.pricePaise());
+ lines.add(line);
+ subtotal += line.totalPaise();
+ }
+ stock.reserve(restaurantId, items);
+ String id = String.format("O-%04d", sequence.incrementAndGet());
+ Order order = new Order(id, customerId, restaurantId, lines, pricing.price(subtotal, km),
+ restaurant.location(), customer.location(), clock.now());
+ orders.put(id, order);
+ publish(order.history().get(0));
+ return order;
+ }
+
+ // ---- restaurant side ---------------------------------------------------------------------------------------
+
+ /** Takes a kitchen slot, accepts the order and asks the dispatcher for a partner. */
+ public Order accept(String orderId) {
+ Order order = order(orderId);
+ Restaurant restaurant = restaurant(order.restaurantId());
+ if (!restaurant.tryReserveKitchenSlot()) {
+ throw new FoodDeliveryException.KitchenBusy(restaurant.name(), restaurant.capacity());
+ }
+ OrderEvent event;
+ try {
+ event = order.moveTo(OrderStatus.ACCEPTED, clock.now());
+ } catch (RuntimeException e) {
+ restaurant.releaseKitchenSlot(); // the slot was taken for an order that could not be accepted
+ throw e;
+ }
+ publish(event);
+ dispatcher.dispatch(order);
+ return order;
+ }
+
+ public Order reject(String orderId) {
+ Order order = order(orderId);
+ publish(order.moveTo(OrderStatus.REJECTED, clock.now()));
+ stock.release(order.restaurantId(), order.quantities());
+ return order;
+ }
+
+ public Order startPreparing(String orderId) {
+ Order order = order(orderId);
+ publish(order.moveTo(OrderStatus.PREPARING, clock.now()));
+ return order;
+ }
+
+ public Order markReady(String orderId) {
+ Order order = order(orderId);
+ publish(order.moveTo(OrderStatus.READY, clock.now()));
+ restaurant(order.restaurantId()).releaseKitchenSlot();
+ return order;
+ }
+
+ // ---- customer and partner side -----------------------------------------------------------------------------
+
+ /** Allowed until the kitchen starts cooking (PLACED or ACCEPTED); gives back stock, the kitchen slot and the partner. */
+ public Order cancel(String orderId) {
+ Order order = order(orderId);
+ OrderEvent event = order.moveTo(OrderStatus.CANCELLED, clock.now());
+ publish(event);
+ stock.release(order.restaurantId(), order.quantities());
+ if (event.from() == OrderStatus.ACCEPTED) {
+ restaurant(order.restaurantId()).releaseKitchenSlot();
+ if (event.partnerId() != null) {
+ DeliveryPartner partner = partner(event.partnerId());
+ dispatcher.partnerFreed(partner, partner.location(), clock.now());
+ }
+ }
+ return order;
+ }
+
+ public Order pickUp(String orderId) {
+ Order order = order(orderId);
+ publish(order.moveTo(OrderStatus.PICKED_UP, clock.now()));
+ return order;
+ }
+
+ public Order deliver(String orderId) {
+ Order order = order(orderId);
+ OrderEvent event = order.moveTo(OrderStatus.DELIVERED, clock.now());
+ publish(event);
+ DeliveryPartner partner = partner(event.partnerId());
+ partner.recordDelivery();
+ dispatcher.partnerFreed(partner, order.dropoff(), clock.now());
+ return order;
+ }
+
+ public void partnerOffline(String partnerId) { partner(partnerId).goOffline(); }
+ public void partnerOnline(String partnerId) { dispatcher.partnerOnline(partner(partnerId), clock.now()); }
+
+ // ---- helpers -----------------------------------------------------------------------------------------------
+
+ private void publish(OrderEvent event) {
+ listeners.forEach(l -> l.statusChanged(event));
+ }
+
+ private static T find(Map map, String id, String what) {
+ T found = map.get(id);
+ if (found == null) throw new FoodDeliveryException.NotFound(what + " " + id);
+ return found;
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Inventory.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Inventory.java
new file mode 100644
index 0000000..208eb1b
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Inventory.java
@@ -0,0 +1,60 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Stock held per restaurant. The check and the decrement happen inside one lock on that restaurant's stock,
+ * so the check can never be stale by the time it is acted on; different restaurants never wait for each other.
+ */
+public final class Inventory implements StockLedger {
+ private final Map> byRestaurant = new ConcurrentHashMap<>();
+
+ @Override
+ public void setStock(String restaurantId, String itemId, int quantity) {
+ Map stock = stockOf(restaurantId);
+ synchronized (stock) {
+ stock.put(itemId, quantity);
+ }
+ }
+
+ @Override
+ public void reserve(String restaurantId, Map quantities) {
+ Map stock = stockOf(restaurantId);
+ synchronized (stock) {
+ for (var e : quantities.entrySet()) {
+ Integer have = stock.get(e.getKey());
+ if (have != null && have < e.getValue()) {
+ throw new FoodDeliveryException.OutOfStock(
+ e.getKey() + ": wanted " + e.getValue() + ", only " + have + " left");
+ }
+ }
+ for (var e : quantities.entrySet()) {
+ stock.computeIfPresent(e.getKey(), (k, have) -> have - e.getValue());
+ }
+ }
+ }
+
+ @Override
+ public void release(String restaurantId, Map quantities) {
+ Map stock = stockOf(restaurantId);
+ synchronized (stock) {
+ for (var e : quantities.entrySet()) {
+ stock.computeIfPresent(e.getKey(), (k, have) -> have + e.getValue());
+ }
+ }
+ }
+
+ @Override
+ public int available(String restaurantId, String itemId) {
+ Map stock = stockOf(restaurantId);
+ synchronized (stock) {
+ return stock.getOrDefault(itemId, Integer.MAX_VALUE);
+ }
+ }
+
+ private Map stockOf(String restaurantId) {
+ return byRestaurant.computeIfAbsent(restaurantId, r -> new HashMap<>());
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/LongestIdle.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/LongestIdle.java
new file mode 100644
index 0000000..7112444
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/LongestIdle.java
@@ -0,0 +1,19 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+
+/** The partner who has waited longest without a job: a fairness rule, not an efficiency rule. */
+public final class LongestIdle implements PartnerAssignmentStrategy {
+ @Override
+ public Optional pick(Point restaurant, List available) {
+ return available.stream().min(Comparator
+ .comparingLong(DeliveryPartner::idleSince)
+ .thenComparingInt((DeliveryPartner p) -> p.location().km(restaurant))
+ .thenComparing(DeliveryPartner::id));
+ }
+
+ @Override
+ public String name() { return "longest-idle"; }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/MenuItem.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/MenuItem.java
new file mode 100644
index 0000000..c118477
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/MenuItem.java
@@ -0,0 +1,7 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+public record MenuItem(String id, String name, long pricePaise) {
+ public MenuItem {
+ if (pricePaise <= 0) throw new IllegalArgumentException("price must be positive: " + id);
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Money.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Money.java
new file mode 100644
index 0000000..0a17f41
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Money.java
@@ -0,0 +1,12 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** Money is a whole number of paise everywhere; this class only turns it into text. */
+public final class Money {
+ private Money() {}
+
+ public static String rs(long paise) {
+ String sign = paise < 0 ? "-" : "";
+ long abs = Math.abs(paise);
+ return String.format("%sRs %d.%02d", sign, abs / 100, abs % 100);
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/NearestPartner.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/NearestPartner.java
new file mode 100644
index 0000000..caedcdb
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/NearestPartner.java
@@ -0,0 +1,17 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+
+/** The closest free partner to the restaurant; ties go to the lower id so a run is repeatable. */
+public final class NearestPartner implements PartnerAssignmentStrategy {
+ @Override
+ public Optional pick(Point restaurant, List available) {
+ return available.stream().min(
+ Comparator.comparingInt((DeliveryPartner p) -> p.location().km(restaurant)).thenComparing(DeliveryPartner::id));
+ }
+
+ @Override
+ public String name() { return "nearest"; }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Order.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Order.java
new file mode 100644
index 0000000..1157ee5
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Order.java
@@ -0,0 +1,82 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * An order and the only place its status changes. Every mutator is synchronized on the order, so two
+ * threads racing to move the same order (restaurant rejects while the customer cancels) are serialized
+ * and exactly one of them finds the status it expected.
+ */
+public final class Order {
+ private final String id;
+ private final String customerId;
+ private final String restaurantId;
+ private final List lines;
+ private final Bill bill;
+ private final Point pickup;
+ private final Point dropoff;
+ private final List history = new ArrayList<>();
+ private OrderStatus status = OrderStatus.PLACED;
+ private String partnerId;
+
+ Order(String id, String customerId, String restaurantId, List lines, Bill bill, Point pickup, Point dropoff, long now) {
+ this.id = id;
+ this.customerId = customerId;
+ this.restaurantId = restaurantId;
+ this.lines = List.copyOf(lines);
+ this.bill = bill;
+ this.pickup = pickup;
+ this.dropoff = dropoff;
+ history.add(new OrderEvent(id, null, OrderStatus.PLACED, now, null));
+ }
+
+ public String id() { return id; }
+ public String customerId() { return customerId; }
+ public String restaurantId() { return restaurantId; }
+ public List lines() { return lines; }
+ public Bill bill() { return bill; }
+ public Point pickup() { return pickup; }
+ public Point dropoff() { return dropoff; }
+
+ /** Item id to quantity, in the order the customer added them. */
+ public Map quantities() {
+ Map q = new LinkedHashMap<>();
+ for (OrderLine l : lines) q.merge(l.itemId(), l.quantity(), Integer::sum);
+ return q;
+ }
+
+ public synchronized OrderStatus status() { return status; }
+ public synchronized String partnerId() { return partnerId; }
+ public synchronized List history() { return List.copyOf(history); }
+
+ /** Moves to {@code next} if the table allows it from the current status; otherwise throws and changes nothing. */
+ synchronized OrderEvent moveTo(OrderStatus next, long now) {
+ if (!status.canMoveTo(next)) {
+ throw new FoodDeliveryException.IllegalTransition(id, status, next);
+ }
+ if (next == OrderStatus.PICKED_UP && partnerId == null) {
+ throw new FoodDeliveryException.NoPartnerAssigned(id);
+ }
+ OrderEvent event = new OrderEvent(id, status, next, now, partnerId);
+ status = next;
+ history.add(event);
+ return event;
+ }
+
+ /** A partner can only be attached while the food is still on its way to being handed over. */
+ private static final Set NEEDS_PARTNER = Set.of(OrderStatus.ACCEPTED, OrderStatus.PREPARING, OrderStatus.READY);
+
+ synchronized boolean needsPartner() {
+ return partnerId == null && NEEDS_PARTNER.contains(status);
+ }
+
+ synchronized boolean tryAssign(String partner) {
+ if (!needsPartner()) return false;
+ partnerId = partner;
+ return true;
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderEvent.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderEvent.java
new file mode 100644
index 0000000..39aa872
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderEvent.java
@@ -0,0 +1,4 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** One step in an order's history. {@code from} is null for the first event. */
+public record OrderEvent(String orderId, OrderStatus from, OrderStatus to, long at, String partnerId) {}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderLine.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderLine.java
new file mode 100644
index 0000000..97a97c8
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderLine.java
@@ -0,0 +1,8 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** A line copies the name and price at order time, so a later menu change cannot rewrite a past order. */
+public record OrderLine(String itemId, String name, int quantity, long unitPricePaise) {
+ public long totalPaise() {
+ return unitPricePaise * quantity;
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderListener.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderListener.java
new file mode 100644
index 0000000..783f305
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderListener.java
@@ -0,0 +1,8 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** Observer: notifications, analytics and the customer's live tracking screen all hang off this. */
+public interface OrderListener {
+ void statusChanged(OrderEvent event);
+
+ default void partnerAssigned(String orderId, String partnerId, long at) {}
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderStatus.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderStatus.java
new file mode 100644
index 0000000..ae04d04
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/OrderStatus.java
@@ -0,0 +1,31 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.EnumSet;
+import java.util.Set;
+
+/**
+ * The whole order lifecycle as one table. There are eight legal moves out of sixty-four possible pairs;
+ * everything else is rejected by {@link Order#moveTo}.
+ */
+public enum OrderStatus {
+ PLACED, ACCEPTED, PREPARING, READY, PICKED_UP, DELIVERED, REJECTED, CANCELLED;
+
+ public Set allowedNext() {
+ return switch (this) {
+ case PLACED -> EnumSet.of(ACCEPTED, REJECTED, CANCELLED);
+ case ACCEPTED -> EnumSet.of(PREPARING, CANCELLED);
+ case PREPARING -> EnumSet.of(READY);
+ case READY -> EnumSet.of(PICKED_UP);
+ case PICKED_UP -> EnumSet.of(DELIVERED);
+ case DELIVERED, REJECTED, CANCELLED -> EnumSet.noneOf(OrderStatus.class);
+ };
+ }
+
+ public boolean canMoveTo(OrderStatus next) {
+ return allowedNext().contains(next);
+ }
+
+ public boolean isTerminal() {
+ return allowedNext().isEmpty();
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerAssignmentStrategy.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerAssignmentStrategy.java
new file mode 100644
index 0000000..36438b3
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerAssignmentStrategy.java
@@ -0,0 +1,11 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.List;
+import java.util.Optional;
+
+/** Picks one partner from a list of free ones. It does not claim anyone; the dispatcher does that atomically. */
+public interface PartnerAssignmentStrategy {
+ Optional pick(Point restaurant, List available);
+
+ String name();
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerStatus.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerStatus.java
new file mode 100644
index 0000000..450e9c3
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PartnerStatus.java
@@ -0,0 +1,3 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+public enum PartnerStatus { AVAILABLE, BUSY, OFFLINE }
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Point.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Point.java
new file mode 100644
index 0000000..93ab410
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Point.java
@@ -0,0 +1,13 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** A spot on a city grid. One unit is one kilometre; distance is Manhattan, because roads are a grid, not a straight line. */
+public record Point(int x, int y) {
+ public int km(Point other) {
+ return Math.abs(x - other.x) + Math.abs(y - other.y);
+ }
+
+ @Override
+ public String toString() {
+ return "(" + x + "," + y + ")";
+ }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PricingPolicy.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PricingPolicy.java
new file mode 100644
index 0000000..f1df8d5
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/PricingPolicy.java
@@ -0,0 +1,6 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+/** Turns a food subtotal and a distance into a bill. Pricing changes often, so it sits behind an interface. */
+public interface PricingPolicy {
+ Bill price(long subtotalPaise, int distanceKm);
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/RatedWithinRadius.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/RatedWithinRadius.java
new file mode 100644
index 0000000..1a0650b
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/RatedWithinRadius.java
@@ -0,0 +1,28 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+
+/** The best-rated partner within {@code radiusKm} of the restaurant; if nobody is that close, falls back to the nearest. */
+public final class RatedWithinRadius implements PartnerAssignmentStrategy {
+ private final int radiusKm;
+ private final NearestPartner fallback = new NearestPartner();
+
+ public RatedWithinRadius(int radiusKm) {
+ this.radiusKm = radiusKm;
+ }
+
+ @Override
+ public Optional pick(Point restaurant, List available) {
+ List near = available.stream().filter(p -> p.location().km(restaurant) <= radiusKm).toList();
+ if (near.isEmpty()) return fallback.pick(restaurant, available);
+ return near.stream().min(Comparator
+ .comparingDouble(DeliveryPartner::rating).reversed()
+ .thenComparingInt((DeliveryPartner p) -> p.location().km(restaurant))
+ .thenComparing(DeliveryPartner::id));
+ }
+
+ @Override
+ public String name() { return "rated<=" + radiusKm + "km"; }
+}
diff --git a/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Restaurant.java b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Restaurant.java
new file mode 100644
index 0000000..a7a62db
--- /dev/null
+++ b/food-delivery/src/main/java/com/ankurm/interviewlab/fooddelivery/Restaurant.java
@@ -0,0 +1,54 @@
+package com.ankurm.interviewlab.fooddelivery;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/** A kitchen with a menu and a limit on how many orders it can cook at once. */
+public final class Restaurant {
+ private final String id;
+ private final String name;
+ private final Point location;
+ private final double rating;
+ private final int capacity;
+ private final Map menu = new LinkedHashMap<>();
+ private final AtomicInteger activeOrders = new AtomicInteger();
+ private volatile boolean open = true;
+
+ public Restaurant(String id, String name, Point location, double rating, int capacity, List