Workbench / The TiffinBox Build
S4 · V1·04
Rankings and Routes
Volume 1, chapter 04. TiffinBox learns to rank its most popular dishes (a count plus a size-k heap) and to find the fastest delivery route across a city (Dijkstra with lazy deletion over a road graph that refuses negative travel times). Each is checked against a slow, obviously-correct oracle on hundreds of random inputs, and measured at 1× and 100× the load. The measurements overturn one assumption (the heap barely mattered: counting did) and confirm another (the array-scan Dijkstra would take about 11 minutes per route at city scale).
Stage 4: rankings and routes
The brief
What you'll build. Three additions to core/:
TopDishes.of(orders, k): the k most-ordered dishes by quantity, with ties broken by dish id.CityGraph: an immutable road network of junctions and one-way roads with travel times in whole seconds, built through aBuilderthat rejects negative times.Routes.fastest(graph, from, to): the fastest route and its time, by Dijkstra's algorithm, or empty if the destination is unreachable.
Plus two oracle tests that compare each fast algorithm with a slow, simple one on random inputs, and a scaling benchmark at 1× and 100× the load.
Why a real company needs this. "Popular near you" and "arrives in 25 minutes" are on the home screen of every food app. Both are run constantly, both get bigger every month, and both fail quietly: a wrong ranking or a slightly-too-long route throws no exception. The two questions that matter in production are "is it right?" and "what does it cost when we're 100 times bigger?", and this stage builds the habit of answering both with evidence.
Why now. Chapter 04 gives you the algorithms and the tools to reason about their cost. Stage 3 gave you the heap (PriorityQueue with a tie-breaker) and the habit of measuring against the naive version.
What you'll have at the end.
TopDishes,CityGraphandRouteswith 4 new tests (19 in total), two of them oracle tests over random inputs;- a scaling benchmark with real numbers at two sizes;
- ADR-0006: computing routes in-process, and what would move them out.
Theory to own
- Top-k. Why does a size-k min-heap find the k largest of d counts in O(d log k)? Which is the bigger cost in "top 10 dishes from 2 million orders": choosing the top 10, or counting? (Chapter: "Heaps"; Chapter Exercises P7.)
- Dijkstra's invariant. What is true about a junction when it is popped from the heap, and which assumption does the proof need? (Chapter: "Dijkstra's algorithm"; Companion, Interview prep Q2.)
- Lazy deletion. Java's
PriorityQueuehas no decrease-key. What does the chapter's implementation do instead, and why must heap entries be immutable? (Companion, drill D1.) - Testing an algorithm. How do you test a shortest-path function when you can't work out the answers by hand for large graphs? (Chapter: "Bellman–Ford".)
- Scaling. If an algorithm is O(n log n), how much slower should it be at 100× the input? And if it's O(n²)? (Chapter: "Complexity analysis".)
Build it
Step 1: TopDishes
Create TopDishes with a Count(dishId, quantity) record, a public RANK comparator (most first, then by dish id), and of(Iterable<Order>, int k): count quantities per dish id in a HashMap, keep the best k in a heap, and return them sorted by RANK.
Checkpoint. For orders of d3×5, d1×5, d2×9, d3×1 and d4×5, of(orders, 3) returns d2:9, d3:6, d1:5. d1 and d4 both have 5, and d1 wins on id.
Step 2: an oracle test for TopDishes
Write a test that generates 5,000 random orders over 300 dishes, computes the expected answer the obvious way (count everything, sort everything by RANK, take k), and checks TopDishes.of against it for k = 1, 10, 299 and 1,000.
Checkpoint. All four values of k pass, including k larger than the number of dishes.
Step 3: CityGraph, which can't hold a negative travel time
Create an immutable CityGraph with junctions 0..n-1 and a Road(to, seconds) record, built by a Builder with road(from, to, seconds) and twoWay(a, b, seconds). The builder rejects out-of-range junctions and negative times.
Checkpoint. new CityGraph.Builder(2).road(0, 1, -5) throws IllegalArgumentException, and a built graph's road lists can't be modified.
Step 4: Routes.fastest
Implement Dijkstra with a PriorityQueue of immutable entries, lazy deletion, a prev array to rebuild the path, and an early exit when the destination is settled. Return Optional.empty() when it's unreachable.
Checkpoint. On a four-junction map where 0–1–3 takes 200 s and 0–2–3 takes 90 s, fastest(g, 0, 3) returns junctions [0, 2, 3] and 90 s. A route from a junction to itself is [j] with 0 s.
Step 5: an oracle test for Routes
Add a package-private allDistancesSlowly(graph, from) using Bellman–Ford. Then test 200 random graphs of 2–31 junctions, with random one-way roads (including self-loops, parallel roads and zero-second roads): for every junction, fastest must agree with Bellman–Ford, including "unreachable".
Checkpoint. All 200 trials pass, and the build prints tests: 19 passed.
Step 6: measure at 1× and 100×
Write Bench4.java (outside the test suite) that measures:
TopDishes.of(orders, 10)against counting-then-sorting-everything, at 20,000 and 2,000,000 orders over 2,000 dishes with a skewed popularity;Routes.fastestfrom a corner to the centre of a square grid city with random 30–120 s roads, at 10,000 and 1,000,000 junctions;- the textbook array-scan Dijkstra (no heap, O(V²)) at 10,000 and 40,000 junctions.
Checkpoint. Every comparison reports the same answer from both methods, and you can state each growth ratio.
Senior and architect lens
1. Test algorithms against oracles, not only examples. Hand-written examples test the cases you thought of. An oracle test (a slow, simple implementation checked against the fast one on hundreds of random inputs) tests the ones you didn't: self-loops, parallel roads, zero-second roads, unreachable junctions. This is how compilers, databases and sorting libraries are tested in practice, and it's cheap to write. Stage 5 extends the idea to exhaustive checking of the order lifecycle.
2. Put an algorithm's preconditions in the types. "Dijkstra needs non-negative weights" lives in the CityGraph.Builder, not in a comment. When a future feature wants negative weights ("a discount for routes past a partner restaurant"), the build fails loudly at the first negative road, and the decision to switch algorithms (Bellman–Ford, or rethinking the feature) is made deliberately.
3. Answer "what does it cost at 100×?" with two measurements and a ratio. One measurement tells you the speed today. Two, at sizes 100× apart, tell you the exponent, which is what decides whether the design survives growth. Keep the benchmark in the repository and rerun it when the code changes. Volume 3 turns this into a performance test in CI (JMH, with thresholds).
4. ADR-0006: routes computed in-process, from an in-memory graph. Write it with these points:
- Decision:
Routes.fastestruns inside the TiffinBox service on an immutable in-memoryCityGraph, rebuilt when road data changes. - Why: one city's graph fits in memory (a million-junction grid is about 4 million
Roadobjects: roughly 150 MB with Java's object overhead, estimated rather than measured), and one route takes well under a second. - Costs: memory per instance, cold-start time to load the graph, and no live traffic.
- Revisit when: routes are needed for many cities at once (memory), latency targets drop below about 50 ms at city scale (precomputation, such as contraction hierarchies, or A* with a good heuristic), or traffic data arrives (a dedicated routing service or a provider's API). That last one is how real food delivery companies do it, and it's an architecture decision, not an algorithm tweak.
5. Choose by the real shape of the data. Popularity is skewed; road networks are sparse and nearly planar; orders arrive nearly sorted by time. Every one of those facts changes which algorithm wins (and by how much), and every one was ignored by the textbook worst case. Generate benchmark data with the same shape as production, or use (anonymised) production data.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| proving the lifecycle correct, not just testing it | example tests can miss a transition | stage 5 |
| rankings per city, per hour, for millions of orders | recounting everything per request | stage 7 (analytics layout) and Volume 3 (precomputed, cached) |
| routes with live traffic and many cities | an in-memory static graph per instance | ADR-0006's revisit triggers; Volume 5 (distributed systems) |
| ranking ties that people notice | "Popular" order changes between loads | already handled: RANK ends with the dish id |
| many routes per second from concurrent requests | CityGraph is immutable and safe; per-request arrays allocate |
stage 9 and Volume 3 (measure allocation, then pool or not) |
Evidence
TopDishes,CityGraphandRoutesare incore/, and the build printstests: 19 passed.- Both oracle tests run in the build, with fixed seeds.
- Removing the negative-weight check from
CityGraph.Builderand adding a negative road to the random test makes the Dijkstra oracle test fail (try it, then restore the check). - Your benchmark output, at both sizes, is in the README with the growth ratio of each method and one sentence on what it means.
- ADR-0006 (routes in-process; revisit triggers) is committed.
Carry forward
TopDishesfeeds the "Popular" section of the menu endpoint in stage 9, Volume 2's home screen, and a cached ranking in Volume 3.RoutesandCityGraphbecome the ETA estimate for an order. Volume 3 exposes them through an API; later volumes replace the static graph as ADR-0006 predicts.- Oracle tests become the standard for any non-trivial algorithm in TiffinBox.
- Every benchmark is run at two sizes and reported as a ratio, from here to the load tests of later volumes.