The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S3 · V1·03

Indexes and Queues

Volume 1, chapter 03. TiffinBox's core gets its first data structures chosen for real access patterns: a `Menu` with O(1) lookup by dish id and prefix search over dish names (a trie), a `KitchenQueue` that serves the earliest pickup first and keeps equal times in arrival order (a heap with a tie-breaker), and `tbx --by-kitchen` grouped in a sorted map. You'll measure each choice against the naive one, find that a trie alone was only 3.6× faster until its nodes were pre-sorted, and record when to build an index in memory and when to leave it to the database.

6 parts · ~7 min to read
Updated Suggest a correction

Stage 3: indexes and queues

The brief

What you'll build. Three structures in core/, plus one feature in tbx:

  • Menu: built once from a kitchen's dishes, read thousands of times. byId(id) in O(1) through a presized HashMap, rejecting duplicate ids. search(prefix, limit) finds dishes with any word starting with the prefix ("mas" finds "Masala dosa" and "Mysore masala dosa"), in display order.
  • DishTrie: the prefix index behind search, with every node's dishes pre-sorted once when loading finishes.
  • KitchenQueue: orders waiting for a kitchen, served by earliest promised pickup time, with first-come-first-served among equal times.
  • tbx orders stats --by-kitchen: per-kitchen counts and totals, in a stable order.

Why a real company needs this. Every food app has these three shapes: "find this item by id" (every cart, every order line), "search as I type" (the menu screen), and "what should the kitchen cook next" (the kitchen display). Choosing badly doesn't fail a test. It shows up months later as a search box that lags at 50,000 dishes, or a kitchen that keeps serving the newest of several equal orders first.

Why now. Chapter 03 gives you the structures and their costs. Stage 2 gave you immutable Dish values that are safe to index: an index over mutable values breaks the moment one changes.

What you'll have at the end.

  • Menu, DishTrie and KitchenQueue with 4 new tests (15 in total);
  • a benchmark with real numbers for each choice against the naive alternative;
  • tbx --by-kitchen;
  • ADR-0005: in-memory indexes, what they cost, and when they belong in the database instead.

Theory to own

  1. Access patterns first. For the menu, list the operations, how often each runs, and which must be fast. Which structure does each one suggest? (Chapter: "Choosing a data structure".)
  2. Hash map costs. What makes HashMap.get O(1), what assumption does that rest on, and what does presizing avoid? (Chapter: "Hash tables"; Companion, gaps 1 and theoretical gap 2.)
  3. Tries. What does a trie make cheap, and what doesn't it make cheap? Where does the cost go when a common prefix matches thousands of dishes? (Chapter: "Tries".)
  4. Heaps and stability. A PriorityQueue ordered by pickup time gets six orders with the same time. In what order do they come out, and why? (Chapter: "Heaps and priority queues"; Companion, gap 2.)
  5. Sorted maps. --by-kitchen uses a TreeMap<String, …>. Why a sorted map rather than a HashMap for output, and what order will k7, k9 and k12 print in? (Chapter: "Balanced search trees".)

Build it

Step 1: Menu, with lookup by id

Create core/src/in/tiffinbox/core/Menu.java. The constructor takes the dishes, builds a presized HashMap from id to dish, and rejects a duplicate id. Expose byId(String) returning Optional<Dish>, and size().

Checkpoint. A menu built from two dishes with the same id throws IllegalArgumentException naming the id, and byId returns empty for an unknown id.

Step 2: a trie over the words of dish names

Create DishTrie with add(Dish) and withWordStarting(String prefix). Split each name into words, lower-case them with Locale.ROOT (stage 1's lesson), and insert each word one character per level. Each node remembers which dishes have a word passing through it. Search walks down the prefix and returns that node's dishes, sorted for display.

Checkpoint. On a menu of "Masala dosa", "Paneer masala", "Idli" and "Mysore masala dosa", search("MAS", 10) returns all three masala dishes in name order; search("pizza", 10) and search(" ", 10) return empty.

Step 3: move the sort from search time to build time

A menu is built a few times a day and searched on every keystroke. Add freeze(Comparator<Dish>): walk every node once, sort its dishes, store them as an immutable list, and drop the set. Searches then return the stored list.

Checkpoint. All four tests still pass, and the benchmark in step 4 shows search time falling by orders of magnitude.

Step 4: measure it

Write Bench.java (outside the test suite: benchmarks don't belong in a pass/fail build) that builds a menu of 50,000 generated dishes and compares:

  • 200 prefix searches through Menu.search against a linear scan that filters, sorts and takes 10;
  • 10,000 lookups by id through Menu.byId against scanning the list.

Run each comparison three times and report the third, so the JIT has compiled the code (Volume 1, chapter 7 explains why).

Checkpoint. Both methods return the same number of results, and you have real numbers for the trie before and after step 3.

Step 5: KitchenQueue, with first-come-first-served ties

Create KitchenQueue with add(orderId, promisedAt), next(), peek() and size(). First build it with a PriorityQueue ordered by promisedAt only, add six orders with the same time and one earlier, and print the service order. Then fix it.

Checkpoint. A test adds o1…o6 at the same time and o0 a minute earlier, and asserts service order o0, o1, o2, o3, o4, o5, o6.

Step 6: tests

Add StructuresTest with four tests: prefix search across words and case, limit and misses, duplicate ids, and FIFO ties.

Checkpoint. The build prints tests: 15 passed.

Step 7: tbx orders stats --by-kitchen

Add a --by-kitchen flag that prints one line per kitchen (count and total), then the overall line. The file format is stage 1's order_id,kitchen_id,amount.

Checkpoint. On a four-line sample with kitchens k7, k12 and k9, the output is the same on every run, and the kitchen lines total the overall line.

Senior and architect lens

1. Choose structures from access patterns, then measure. The order of thought in this stage is the one to keep: list the operations and their frequencies, pick the structure, then measure against the naive version. The measurement found something the theory didn't: the trie was the right structure, and the first implementation still spent its time in the wrong place. Big-O told you where to look; the benchmark told you what was slow.

2. Move work from the frequent path to the rare one. Pre-sorting traded build time (677 to 1,283 ms) and memory for searches about 1,800 times faster. This is the most common performance move in real systems: materialised views, denormalised read models, pre-computed search indexes, caches. The questions are always the same: how often does the data change, how stale may the derived data be, and who rebuilds it? Here: rarely, never (rebuild on every change), and the constructor.

3. ADR-0005: in-memory indexes. Write it with these points:

  • Decision: a kitchen's Menu is an immutable in-memory index (hash map by id, pre-sorted trie by word prefix), rebuilt whole when the menu changes.
  • Why: menus are small (hundreds to low thousands of dishes per kitchen), change a few times a day, and are read on every keystroke and order line.
  • Costs: memory (a sorted list per trie node), about a second of build time at 50,000 dishes, and one copy per server instance.
  • Revisit when: search must be fuzzy or typo-tolerant, ranked by popularity, or span all kitchens in a city. Those belong in a database index or search engine (Volume 4: Postgres trigram indexes; later, a search service), not a hand-built trie.

4. Determinism is a feature. The FIFO tie-breaker, DISPLAY's tie-break on id, and the TreeMap in tbx all exist for one reason: the same input must always give the same output. Non-deterministic order breaks tests intermittently, makes reports impossible to diff, and makes customers feel cheated ("I ordered first"). Every comparator in TiffinBox ends with a unique field.

5. Thread safety is a separate decision, made later and explicitly. Menu is immutable, so it is already safe to share between threads. KitchenQueue is mutable and not thread-safe, which is fine for one kitchen display. When stage 9 serves requests concurrently, the choices are a lock around it, a PriorityBlockingQueue, or one queue per kitchen owned by one thread. The class's Javadoc should say which it is today.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
sorting and searching large order histories nothing yet indexes orders by time or customer stage 4 (algorithms)
kitchen ids that people read and sort k12 sorts before k7 stage 6
a menu shared by concurrent requests, a queue fed by them KitchenQueue isn't thread-safe stage 9 and Volume 3
typo-tolerant, ranked or city-wide search a trie only does exact prefixes in one menu Volume 4 (database indexes and full-text search)
menus changing while searches run rebuilding must not block readers stage 9 (swap an immutable menu through one reference)

Evidence

  • Menu, DishTrie and KitchenQueue are in core/, and the build prints tests: 15 passed.
  • Your benchmark output, before and after pre-sorting, is pasted into the README with your machine's numbers.
  • The time-only PriorityQueue output (orders served out of arrival order) is in the README beside the fixed test.
  • tbx orders stats --by-kitchen output is in the README, with a sentence explaining why k12 prints before k7.
  • ADR-0005 (in-memory indexes: decision, costs, revisit triggers) is committed.

Carry forward

  • Menu is how the rest of TiffinBox finds dishes. Stage 9's HTTP server serves /menu/search?q= from it, Volume 2's frontend calls that endpoint on every keystroke, and Volume 3 replaces the in-memory build with one loaded from the database.
  • KitchenQueue drives the kitchen display, and its ordering rule (time, then arrival) becomes a requirement that later versions must keep.
  • Every comparator ends with a unique field. Volume 4 meets the same rule as ORDER BY … , id for stable pagination.
  • Measure against the naive version. Every later performance decision in the build starts with a benchmark like step 4's.