Workbench / The TiffinBox Build
S7 · V1·07
A Day in Columns
Volume 1, chapter 07. A day's orders are turned into columns, each field in its own primitive array with ids encoded as small integers, and the analytics queries (revenue per kitchen, orders per kitchen per hour, a kitchen's top dishes) are rewritten as single passes over those arrays. On 3 million orders, the same answers come back in 4 ms instead of 800, using 100 MB of heap instead of 729. The stage takes the speed-up apart to see where it comes from, checks the columns against the obvious object code, and fixes the hour-of-day to the business's time zone.
Stage 7: a day in columns
The brief
What you'll build.
Dictionary: a two-way map between strings and dense integers ("k12"↔ 3), so hot loops index arrays instead of hashing strings.DayColumns: one day's orders stored column by column (kitchen code, total, minute of the day in IST; and for lines: kitchen, dish, quantity), with queries for revenue by kitchen, orders by kitchen and hour, a parallel revenue query, and a kitchen's top dishes.AnalyticsTest: the columns checked against straightforward object-and-stream code on 20,000 random orders, plus tests that queries never modify the dictionary and that hours are counted in the business's time zone.Bench7: the object version and the column version of each query, on 300,000 and 3 million orders, with heap use.
Why a real company needs this. Every evening, someone wants to know how each kitchen did: revenue, busy hours, best sellers. Run naively over objects, those reports get slower every month as orders grow, and they compete for memory with the live service. Columnar layouts are why analytical databases (and Volume 4's warehouses) answer such questions in milliseconds; building a tiny one by hand shows exactly where the time goes.
Why now. Chapter 07 explains the cost model this stage exploits: cache lines, prefetching, pointer chasing, and memory bandwidth. Stage 4's rankings recount everything on every call, which its "what breaks first" table sent here.
What you'll have at the end.
DictionaryandDayColumnswith 3 new tests (33 in total);- measured times and heap sizes for objects against columns at two sizes, and a breakdown of the difference;
- ADR-0009: analytics read a columnar snapshot built after the day closes, never the live objects.
Theory to own
- Bytes touched. To total revenue by kitchen, how many bytes per order does the computation need? How many does it touch when each order is a Java object with a list of line objects, dish objects and strings? (Chapter: "Cache lines, associativity and replacement"; Companion, Interview prep Q4.)
- Pointer chasing. Why does a loop over a
List<Order>get slower when the orders were allocated in a different order from the list's order? (Chapter: "Locality, measured"; Companion, theoretical gap 3.) - Roofline. Revenue by kitchen does one addition per order. Is it compute-bound or memory-bound, and what does that predict about using more threads? (Companion, theoretical gap 2.)
- Sharing between threads. Two threads adding into one shared
long[]of per-kitchen totals: what goes wrong, both for correctness and for speed? (Chapter: "Cache coherence"; "False sharing".) - Time zones. An order placed at 07:30 in Hyderabad: which hour bucket is it in, if you take the hour from the
Instantwithout a zone? (Chapter Exercises leaves out "time as a number".)
Build it
Step 1: the baseline, measured
Write Bench7.java (outside the test suite) that generates a day of orders (500 kitchens, a 200-dish menu, 1–3 lines each, times spread over the IST day), shuffles the list to mimic objects allocated over a real day, and measures three queries the obvious way, with streams over the objects:
- revenue by kitchen:
groupingBy(Order::kitchenId, summingLong(o -> o.total().paise())); - orders by kitchen and hour: nested
groupingBywitho.status().at().atZone(IST).getHour(); - top 10 dishes of kitchen k7: filter, then stage 4's
TopDishes.of.
Also measure heap use: System.gc() a few times, then total minus free memory, before and after building the list.
Checkpoint. You have times for 3 million orders and know how many megabytes the objects occupy.
Step 2: dictionary-encode the ids
Create Dictionary with code(String) (adding new values), find(String) (returning −1 for unknown values, never adding), value(int) and size(). Kitchens and dishes get codes 0, 1, 2, … in order of first appearance.
Checkpoint. code("k12") returns the same integer every time, and find on an unknown id leaves size() unchanged.
Step 3: DayColumns
Build the columns in the constructor: count lines first so every array is allocated once at its final size, then fill:
- per order:
int[] kitchen,long[] totalPaise,short[] minuteOfDay(0–1439, computed in the givenZoneId); - per line:
int[] lineKitchen(copied from the order, so line queries don't need a join),int[] lineDish,byte[] lineQty.
Then write the queries as single loops: revenueByKitchen() into long[], ordersByKitchenHour() into int[kitchens][24], and topDishes(kitchenId, k) by summing lineQty into a long[] per dish for one kitchen, then sorting with stage 4's TopDishes.RANK.
Checkpoint. The class compiles with no List, Map or object in any query loop.
Step 4: a parallel query without sharing
Add revenueByKitchenParallel(chunks): split the order range into chunks, give each chunk its own long[] of totals, and merge the arrays at the end.
Checkpoint. It returns exactly the same totals as the sequential version.
Step 5: tests against the obvious code
Write AnalyticsTest:
- generate 20,000 orders; compute revenue by kitchen and orders by kitchen and hour with streams over objects; compare every kitchen and every hour with the column results, sequential and parallel; compare
topDishes("k7", 5)withTopDishes.ofon k7's orders; - check that asking for an unknown kitchen returns an empty list and leaves the dictionary's size unchanged;
- check that an order at 07:30 IST lands in hour 7 with
Asia/Kolkataand hour 2 with UTC.
Checkpoint. The build prints tests: 33 passed.
Step 6: measure, and take the speed-up apart
Extend Bench7 with the column queries, the parallel query, and two extra object loops that separate the costs: a plain loop that only counts orders per kitchen in a HashMap<String, long[]> (no total()), and a plain loop that sums total() the same way. Run at 300,000 and 3 million orders, checking that every method agrees.
Checkpoint. You can say how much of the difference comes from streams, from total(), and from the layout.
Senior and architect lens
1. Separate the read model from the write model. Live orders are objects, because they change and carry behaviour (stage 2's lifecycle). Analytics read a different shape built for scanning. This is the CQRS idea (Volume 3 and Volume 5) and the reason data warehouses exist (Volume 4): one model can't be good at both writes and scans.
2. ADR-0009: analytics read a columnar snapshot. Write it with these points:
- Decision: after the business day closes (in IST), build a
DayColumnssnapshot of that day; all daily reports query the snapshot, never the live objects. - Why: 200× faster queries and 7× less memory at 3 million orders (measured), and no reporting load on the live order objects.
- Costs: a 2-second build per 3 million orders, data that is up to a day old, a second representation to keep consistent (guarded by
AnalyticsTest's comparison with the object code). - Revisit when: reports need intra-day freshness (incremental columns, or a streaming aggregate), or data no longer fits in one JVM's memory (a columnar database: Volume 4).
3. Find the cost before choosing the fix. The obvious suspects (streams, single-threading) contributed nothing measurable. The breakdown loop, counting without total(), was the experiment that located the time: in pointer chasing. Senior performance work is mostly designing that kind of experiment, then changing the one thing it points to.
4. Time zones belong to the business, and they're decided once. "Which hour" and "which day" are business rules, made in DayColumns's constructor with an explicit ZoneId, and tested. Every report built on the columns inherits the right answer. A system that computes hours in UTC in one report and IST in another produces numbers that can't be reconciled (the Companion to chapter 05, Interview prep Q5).
5. Parallelism is the last step, not the first. Two threads bought 1.5× on large inputs and lost on small ones, after layout had already bought 200×. Parallelising the object version would have spent cores to wait on memory twice as fast. Fix the layout, then measure whether threads still help.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| the process restarts | snapshots and orders live in memory | stage 8 (durable log; snapshots rebuilt from it) |
| intra-day dashboards | the snapshot is built after the day closes | Volume 3 (incremental aggregates), Volume 21 (streaming) |
| a month or a year of history | columns for every day in one JVM | Volume 4 (columnar storage, Parquet, warehouses) |
| new questions every week | each query is hand-written Java | Volume 4 (SQL over columnar data) |
| a kitchen renamed mid-day | codes are per snapshot | dictionary per snapshot is fine; cross-day reports join on ids (Volume 4) |
Evidence
Dictionary,DayColumnsandAnalyticsTestare incore/, and the build printstests: 33 passed.- Your
Bench7output at both sizes is in the README, including the breakdown loop, with one sentence on where the time went. - Heap use for objects and columns is recorded, with bytes per order for each.
- The time-zone test passes, and the README states that all business hours are in Asia/Kolkata.
- ADR-0009 (columnar snapshot for analytics, costs, revisit triggers) is committed.
Carry forward
DayColumnsserves the daily reports. Stage 8 rebuilds it from the durable log after a restart; Volume 3 exposes the reports through the API; Volume 4 replaces the hand-built columns with a columnar database when one day per JVM stops being enough.Dictionaryencoding reappears wherever strings are repeated in bulk: in stage 8's log compaction and in Volume 4's storage formats.- The "obvious code as oracle" test guards every optimisation from here on.
- Business time zone = Asia/Kolkata, decided in one place, is the rule for every "per day" and "per hour" in TiffinBox.