Design a Top-K popular items system - every restaurant page of a food delivery marketplace shows the best-selling dishes of the last 1, 7 or 30 days, for 200,000 restaurants and 80 million order lines a day. The shelf is a published result, not a live query. The staff-level signal is a batch pipeline of append-only facts, daily totals and versioned snapshots that takes a late refund, a failed run and a hot restaurant without ever showing a half-finished ranking, and an honest answer to "why not streaming?".
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The happy path is one SQL query: group the order lines of a restaurant by dish, sum the quantity, sort, take ten. The interview is decided by four questions about what happens when an old order changes, a run fails, most of the data did not change, or the product wants more. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | A refund arrives for an order that is already in the published ranking. What do you do? | Subtract it from the published count | The ranks are not sorted again, the other windows are forgotten, and the next run puts the units back. Write a correction fact and recompute that one day |
| DD2 | The batch run dies halfway through publishing. What does the customer see? | The old data | |
The same three habits answer all four:
Do not spend your questions on how the shelf looks. Spend them on what counts and how fresh it must be.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| What counts as popular? | Units in finalized purchases. No clicks, no carts, no page views | One clear input that can be replayed and checked. Clicks are easy to fake and hard to define |
| How fresh? | Up to an hour old is fine, if the app can show how old | A scheduled batch job is enough. No stream processor is needed (DD4) |
| Which windows? | Three fixed ones: 1 day, 7 days, 30 days | One job can build all three from the same daily totals (DD3) |
Out of scope (say this out loud): personal recommendations, search ranking, sponsored placement, free-form analytics with custom windows, a marketplace-wide trending list, the menu system, and checkout and payment.
FR1 — Take in the facts. Every finalized order line reaches the system: which restaurant, which dish, how many. An order line is one dish on one order. Three carbonara on one order are one line with quantity 3, and they count as 3 units.
FR2 — Rank per restaurant and window. For each restaurant, the top K dishes by units for 1 day, 7 days and 30 days. K is 10 on this page.
FR3 — Serve the shelf. One call returns the ranked dish IDs with their unit counts for one restaurant and one window, plus how fresh the ranking is.
FR4 — Take corrections. A late refund, a delayed order or a bad input file changes the past. The ranking follows, and an operator can ask for a rebuild of chosen restaurants and days.
FR5 — Stay out of the menu. Names, photos, prices and "sold out" come from the menu service. The app can ask which windows exist instead of hard-coding them.
The key principle behind all five
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| An order was counted | Its units stay counted | It can be refunded days later. The count must be able to go down |
NFR1 — Scale. 200,000 restaurants, 20 million orders and 80 million order lines a day. A small share of the restaurants takes a large share of the orders.
NFR2 — Trust. Every published ranking comes from one cutoff time, can be computed again from stored facts, and can be explained later. Readers never see a mix of two runs.
NFR3 — Honest freshness. In normal operation the shelf is at most 60 minutes behind. The answer always carries the time it was computed up to.
NFR4 — Fast reads. p95 of 50 ms when the answer is in the cache, 150 ms when it is read from the database.
NFR5 — Reads survive the batch. When a run is late or fails, the last good ranking is served. Readers never wait for a job.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Restaurants | 200,000 |
| Orders | 20 million a day, 4 lines each: 80 million order lines a day, about 930 a second |
| An average restaurant | 100 orders a day: 400 lines a day, 12,000 in 30 days |
| A hot restaurant | Burger Barn: 20,000 orders a day: 80,000 lines a day, 2.4 million in 30 days |
| Skew | The top 1%, 2,000 restaurants, take 20% of the orders |
The number that identifies the real system is what one page view costs if the ranking is computed when it is asked for:
Luigi's, 30 days 400 lines a day x 30 = 12,000 lines per page view
Burger Barn, 30 days 80,000 lines a day x 30 = 2,400,000 lines per page view
Burger Barn at lunch 20 page views a second = 48 million lines a second, for one shelf
a published snapshot 10 small rows, read by key
For Luigi's the live query looks fine, which is why it survives the demo. For the restaurants that most people look at, it does not. The restaurant, order and line counts are the question's. Read traffic, cluster speed, run time and row sizes are illustrative assumptions.
Interviewer signal: candidates who reach for a stream processor and a sketch data structure have answered a different question. Here the counts must be exact, replayable and correctable, and an hour of delay is allowed. Candidates who say "the shelf is a published snapshot, the hard part is publishing and correcting it safely" have found the system.
Three ideas shape everything:
The batch path is slow and careful: read facts, add them up, rank, publish. It runs every 30 minutes and may take minutes. The read path is fast and dumb: look up one small, finished ranking by key. A page view never triggers a computation, and a computation never blocks a page view.
An order line is stored once and never changed. A refund is a new line with a negative quantity. Totals and rankings are derived from the facts and can be thrown away and built again. So there is one answer to "why does this dish show 211?": these facts, up to this time.
The job writes a new ranking next to the old one, under a new version number. One small switch makes it the current one. Before the switch, readers see the old version, complete. After it, the new one, complete. There is no moment in between.
The core recognition
This is a publishing system, not a counting system. The counting is a sum. The design work is in what is stored so a number can be recomputed, how a new result becomes visible, and what the reader is told about its age.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| Facts in append-only files, in folders by day and bucket | Cheap, replayable, and a run opens only the folders that changed |
| A correction is a new fact with a negative quantity | The past is never edited, so every count can be explained |
Four records carry the design: the fact, the daily total, the run manifest and the snapshot with its pointer. Each exists for one question: what happened, what does it add up to, which run produced this, and what do readers see.
One row per finalized order line, in a file that is never changed. The source of truth.
Swipe to see all columns
| order_line_fact | ||
|---|---|---|
| Field | Type | Comment |
fact_id | STRING | Unique per line, for example o_5001-1. A line that is delivered twice is counted once |
order_id | STRING | The order, for example o_5001 |
The files are columnar (a format such as Parquet, which stores each column together and is fast to scan) and sit in folders named by day and by bucket. A bucket is one of 256 groups of restaurants, chosen by a hash of the restaurant ID. Luigi's is in bucket 042.
One number per restaurant, dish and day. Written only by the batch job.
Swipe to see all columns
| daily_totals | ||
|---|---|---|
| Field | Type | Comment |
restaurant_id | STRING | Key, together with the next two |
item_id | STRING | The dish |
day | ||
Swipe to see all columns
| Records in the Snapshot store | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Snapshot row | (restaurant_id, window, batch_version, rank) with item_id and unit_count | One ranked dish. Ten rows are one snapshot: the shelf of one restaurant and window in one version |
The cutoff of a run is its start time. The run uses every fact that arrived up to then, and nothing later. It is the honest age of the result: a ranking published at 12:38 from a cutoff of 12:30 knows nothing about 12:35.
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Fact store (object storage) | Order-line facts in columnar files, by day and bucket | Append-only. The source of truth. Everything else can be rebuilt from it |
| Daily totals (object storage) | One number per restaurant, dish and day | Derived. Overwritten per restaurant and day by the batch job |
| Snapshot store (PostgreSQL) | Snapshot rows, pointers, the run manifest, rebuild requests | Transactional. A publish is one transaction |
One public read, two small helpers, and one internal command.
Swipe to see all columns
| The calls | ||
|---|---|---|
| Call | Who calls it | What it does |
GET /v1/restaurants/{restaurant_id}/popular-items?window=7d&limit=10 | App | The shelf: items with rank, item_id and unit_count, plus batch_version, computed_up_to |
staleness has three values. fresh: the ranking was computed up to a time that is at most 60 minutes ago. degraded_serving_last_good: it is older, because runs are failing, and this is the last good one. not_ready: no ranking was ever published for this restaurant and window. An empty items list with fresh means something else again: the restaurant has no finalized orders in the window.
The rebuild call is a command, not a request to wait for. It stores the order and returns. An idempotency key is an ID the caller invents for one logical request: the same key sent twice gives the same job_id, not two rebuilds.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 land the facts (black), Phase 2 the batch run (blue), Phase 3 publish and correct (green), Phase 4 read the shelf (purple). All four follow one order. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Land the facts (FR1) | Black | sam's order of 3 carbonara is finalized and written into a file | A fact in a file that is never changed |
| Phase 2: The batch run (FR2) | Blue | Run 812 finds what changed, recomputes those daily totals, sums the windows and ranks | Version 812, complete and invisible |
How to read the picture
o_5001 is finalized: 3 carbonara at Luigi's (r_42). Before it, Luigi's 7-day shelf reads margherita 212, carbonara 210, tiramisu 150.Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: store every finalized order line once and for good, in a place a batch job can read cheaply.
order line finalizedOrders service → Fact loaderNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The Orders service reports a finalized line to the Fact loader: order o_5001, line 1, r_42, carbonara, quantity 3, 12:10. | Nothing yet |
| 2 | The Fact loader collects the lines of that minute in memory, grouped by day and bucket. | Nothing yet |
| 3 | The loader writes one file into the Fact store: folder day 11-12, bucket 042, file arrived 12-11. | |
Why it is built this way
fact_id once.Because then the counter is the truth and the fact is a log nobody reads. A line that arrives twice adds 6. A refund has to find the right counter in every window. And when a count is disputed, there is nothing to recompute it from. Storing the fact and deriving the count later costs freshness, which this question does not need, and buys a number that can always be checked.
Goal: turn the new facts into a new, complete ranking for every restaurant that changed, without touching what readers see.
start run 812Scheduler → Batch job812new rowSwipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:30: the Scheduler starts run 812. Its cutoff is 12:30. | Manifest 812: RUNNING, cutoff 12:30 |
| 2 | The Batch job lists the files that arrived after 12:00 and up to 12:30: 4 million lines in 150,400 pairs of restaurant and day. One pair is (r_42, Nov 12). | Manifest 812: 150,400 dirty pairs |
| 3 | ||
Why it is built this way
A dirty pair is a restaurant and a day whose facts changed since the last cutoff. It is the unit of work in this design. A new sale makes (restaurant, today) dirty. A correction makes (restaurant, the day of the sale) dirty.
Adding is faster and wrong the first time something is repeated. If run 812 dies after writing the total and is started again, it adds the same lines a second time: 37 instead of 34. Recomputing from the facts has no memory, so it cannot double anything. The price is reading today's lines of a restaurant again in every run, at most 80,000 for the hottest one. That is a fraction of a second.
Goal: make the new version visible in one step, and give corrections one way in.
BEGIN; UPDATE topk_current SET batch_version = 812Batch job → Snapshot storer_42, 7dupdateSwipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The Batch job opens one transaction and moves the pointers of every recomputed restaurant, all three windows, to 812. | Pointer (r_42, 7d): 811 to 812, not visible yet |
| 2 | In the same transaction it marks the run as published, and commits. It is 12:38. | Manifest 812: PUBLISHED. Every reader now gets 812, computed up to 12:30 |
| 3 | ||
Why it is built this way
computed_up_to is global, the version is per restaurant. A restaurant with no change keeps its old version, and its answer still says 12:30, because nothing changed for it up to 12:30.Then that key keeps the old version until its 30 minutes are over, and the next read fills it with the current one. The shelf of one restaurant is one run older than it should be, and still a complete, published version. That is why every key has a time to live: the delete is the fast path, the expiry is the safety net.
Goal: answer a page view from a key lookup, and tell the app how old the answer is.
/v1/restaurants/r_42/popular-items?window=7d&limit=3Customer app → Popular Items APINothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:40: dana opens Luigi's page. The app asks the Popular Items API for the 7-day shelf of r_42 with limit 3. | Nothing |
| 2 | The API asks the cache for the key popular:r_42:7d. A miss: the key was cleared at 12:38. | Nothing |
| 3 | The API reads the Snapshot store: the pointer says 812, then the rows of 812, and the cutoff of the last published run, 12:30. | Nothing |
Why it is built this way
Because the list alone cannot be judged. With computed_up_to the app can write "updated 10 minutes ago" under the shelf, or hide a "today" label when the data is two hours old. With batch_version a support engineer can find the exact run, its cutoff and its code version in the manifest when a restaurant owner asks why a dish shows 211.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: after run 812, Luigi's 7-day shelf reads carbonara 213, margherita 212. At 13:05 order o_4410 is refunded: 2 carbonara, sold on Nov 10. The correct shelf is now margherita 212, carbonara 211. Margherita should be back at rank 1. How does the refund get into the ranking?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. When the refund arrives, a handler updates the published row: carbonara 213 becomes 211. It is immediate, and it is one statement.
Where it breaks. The row is changed, the ranks are not: the shelf now shows carbonara 211 above margherita 212. The 30-day shelf is a different row, and the handler forgot it. At 13:30 the next run recomputes the ranking from the facts, which never heard of the refund, and writes 213 again. And nobody can say later where "211" came from: no version, no cutoff, no fact.
The idea. Do not touch the published row. Write the refund as a new fact, with quantity -2 and the day Nov 10. Once a night, a full run rereads all 30 days and catches every correction.
What it fixes. There is one truth again: the facts. The nightly result is correct, and it can be explained.
What it still misses. The half-hourly runs recompute only today, so the total of Nov 10 stays 30 and the shelf says carbonara 213 until the night. The nightly run rereads 2.4 billion lines for 40 minutes and publishes at 02:40, 13 hours and 35 minutes after the refund. And an operator who finds a bad input file at 10:00 can only wait for the night, or run all 40 minutes for one restaurant.
The key idea. A correction is a normal fact that happens to count for an earlier day. The normal run already recomputes every pair of restaurant and day whose facts changed. So the refund needs no path of its own.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. A dashed box belongs to one design only.
UPDATE topk_snapshot SET unit_count = unit_count - 2Orders service → Refund handler → Snapshot storer_42, 7d, rank 1updateSwipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: subtract in place | Good: nightly full rebuild | Great: a dirty day | |
| Where the refund is written | Into the published row | As a new fact | As a new fact |
| When the shelf is right | Never: the next run undoes it | The next night, up to 24 hours | The next run, at most 38 minutes |
Check it against the scenario
| Corrections of every kind | |
|---|---|
| Situation | Outcome with the Great option |
| 2 carbonara of Nov 10 are refunded at 13:05 | A correction fact, one dirty pair in run 814. At 13:38: margherita 212, carbonara 211 |
| The refund event is delivered twice | Two files with the same fact_id. The daily total counts it once: 28, not 26 |
| An order of Nov 11 is finalized a day late | A normal fact with day Nov 11. The pair (restaurant, Nov 11) is dirty in the next run |
| A whole input file of Nov 10 was wrong | The corrected lines are written as new facts, or an operator asks for a rebuild of the affected restaurants and that day |
The trade-off to name. The refund is not visible at once. It waits for the next run: at most 30 minutes to the cutoff and 8 minutes to the publish. In return there is one way for numbers to change, and it is the same way for sales, refunds and operator fixes.
From the daily totals, not from the snapshot. The snapshot holds only ten rows, so an in-place fix would have nothing to promote. The run sums all dishes of the restaurant again, sorts them, and whatever is now tenth takes the place. This is one more reason the published rows are an output and never an input.
"I never edit a published count. A refund is written as a correction fact: same restaurant and dish, negative quantity, and the day of the original sale. Facts land in folders by day, so that file marks one pair of restaurant and day as dirty. The next half-hourly run recomputes that daily total from all its facts, sums the windows that contain that day, ranks again and publishes a new version through the normal pointer move. Readers see the old version until then, complete. Operator rebuilds use the same mechanism: they mark pairs dirty."
Follow-up: "Why not just decrement?" — Because the next run recomputes from the facts and would put the units back, and because a decremented row has no version or cutoff, so I could not explain the number afterwards.
Scenario: run 813 starts at 13:00 and has 150,000 restaurants to publish. At 13:07 it dies after 120,000 of them. At 13:08 dana opens Luigi's page. And Noodle Bar (r_900) opened this morning and has no finalized order yet. What does each shelf show?
Three ways to build it. Decide first, then click.
The idea. One table holds the current ranking. The job goes restaurant by restaurant: delete the old rows, insert the new ones, write the cache key. No versions, no extra tables.
Where it breaks. After the crash, 120,000 restaurants are new and 30,000 are old. Worse, the cut can run through one restaurant: Luigi's 7-day rows are from the cutoff 13:00, its 30-day rows from 12:30. One restaurant was between delete and insert, and its shelf is empty. There is no old version to go back to, and the API answers 200 as if all was well.
The idea. The job writes the rows of 813 next to those of 812 and then moves the pointers. A crash before the move leaves 812 in place, complete.
What it fixes. No mix inside the database. dana gets 812, whole.
What it still misses. The job had already written Luigi's cache key with the rows of 813, so the cache says 813 while the database says 812. The retries fail too, and at 14:30 the API still returns 812 with nothing that says it is two hours old. And Noodle Bar has no rows, so the API returns an empty list: "no orders yet" and "the batch never ran" look the same to the app.
The key idea. Three rules together: a version is invisible until one transaction publishes it, the cache is refreshed only after that transaction, and every answer carries its version, its cutoff and a state.
How it works
PUBLISHED. The cache keys are deleted only after the commit.fresh, 38 minutes old.degraded_serving_last_good, the app shows "updated about an hour ago", and the person on call is paged.The three designs side by side, in one picture:
Play the three options. A dashed box belongs to one design only.
DELETE the old rows; INSERT the new onesBatch job → Snapshot store, CacheNothing is written in this step.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: overwrite in place | Good: versions and a pointer | Great: publish whole, say how old | |
| A run dies mid-publish | A mix of old and new | The old version, whole | The old version, whole |
| The cache and the database | Both written by the job, can differ | Can differ | The cache holds only published answers |
Check it against the scenario
| Run 813 fails | |
|---|---|
| Situation | Outcome with the Great option |
| 13:07 the job dies while staging | Half-written rows of 813 exist and no pointer names them. A cleanup deletes them later |
| 13:07 the job dies inside the publish transaction | The database rolls back. All pointers still say 812 |
| 13:08 dana opens Luigi's page | Version 812, complete, computed up to 12:30, fresh |
| The job dies after the commit, before clearing the cache | Some keys hold 812 a little longer. They expire within 30 minutes. Each is a complete, published version |
The trade-off to name. Versions cost storage: up to 48 copies of the snapshots of a day, a few hundred million small rows before the cleanup. And the app has to handle three states instead of one list. Both are cheap next to a shelf that shows two different truths.
Because the next run makes it pointless. Run 814 has the cutoff 13:30 and recomputes every pair that is dirty since the last published cutoff, 12:30. That includes everything 813 saw. Finishing 813 at 13:35 would publish an older truth after a newer one. The rule is simple: a run that is not published leaves no trace, and the next run starts from the last one that was.
"The batch job never overwrites what readers see. It stages the new rankings under a new version number, then one database transaction moves the per-restaurant pointers and marks the run as published. A crash before the commit leaves the previous version in place, complete. The cache is cleared only after the commit, so it can never get ahead of the database. Every response carries the version, the cutoff time it was computed up to, and a state: fresh, degraded serving the last good one, or not ready. An empty list with fresh means the restaurant has no orders in that window."
Follow-up: "What does the app do with degraded?" — That is a product choice. It can show the shelf with "updated 2 hours ago", drop the "today" window, or hide the module. My job is to give it the facts to decide.
Scenario: 03:00 at night, run 793. Since 02:30 only 3,000 restaurants had an order. Burger Barn, open 24 hours, is one of them. Luigi's is closed. The batch cluster reads 1 million lines a second. What does the run read, and what does it publish?
Three ways to build it. Decide first, then click.
The idea. A batch job has time. Every run reads 30 days of order lines for every restaurant and builds all rankings from zero. No state between runs, nothing to get out of sync.
Where it breaks. 30 days are 2.4 billion lines. At 1 million lines a second that is 40 minutes, and the next run is due after 30. Runs overlap, and the shelf falls more than 60 minutes behind. All of it to recompute 200,000 restaurants when 3,000 changed. And 600,000 snapshots are published, so every cache key is cold again.
The idea. Keep one total per restaurant, dish and day. Each run recomputes only today's totals. A window is a sum of 1, 7 or 30 of them.
What it fixes. The run reads only today's facts: at most 80 million lines, 80 seconds, at the very end of the day. No raw line of an earlier day is read again.
What it still misses. It still ranks and publishes all 200,000 restaurants: 600,000 pointer moves and 600,000 cold cache keys every 30 minutes, for 3,000 that changed. And "only today" is a blind spot: a correction for Nov 10 is never seen (DD1).
The key idea. Let the new files say what changed. A file sits in a folder for one day and one bucket, and its lines name the restaurants. That list of pairs is the whole to-do list of the run.
How it works
The three designs side by side, in one picture:
Play the three options. A dashed box belongs to one design only.
read everythingBatch job → Fact storeNothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: everything | Good: today for everybody | Great: only the dirty pairs | |
| Lines read at 03:00 | 2.4 billion | Today's lines of all restaurants | Today's lines of 3,000 restaurants |
| Run time | 40 minutes | About a minute | Seconds |
Check it against the scenario
| Quiet hours and busy hours | |
|---|---|
| Situation | Outcome with the Great option |
| 03:00, 3,000 restaurants changed | 3,000 daily totals, 9,000 snapshots. The other 197,000 restaurants keep version and cache |
| 12:30, lunch | 150,400 dirty pairs. The run rereads today's lines of 150,000 restaurants and finishes in its 8 minutes |
| Burger Barn, 80,000 lines a day | Its folder of today is reread in every run: less than a tenth of a second of cluster time |
| 00:00, a new day starts | Every window loses its oldest day. The first run of the day ranks every restaurant again, from daily totals only. No raw line is read for that |
| A new scoring rule | |
The trade-off to name. The run now depends on finding the dirty pairs correctly. A file that is missed stays missed. So the list is taken from the storage itself, by arrival time against the last published cutoff, and not from a side channel. And once a day, at midnight, every restaurant is ranked again because the windows move.
Less than in a live design, but in two places. First in the files: if facts were grouped by restaurant alone, Burger Barn's group would be 200 times the average, and one slow task would hold up the run. Hashing restaurants into 256 buckets puts it in a folder with about 780 others and evens that out. Second on the read side: 20 page views a second for one shelf. The cache takes them all, because the answer for the next 30 minutes is the same ten rows.
"I keep a daily total per restaurant, dish and day, so a 30-day ranking is a sum of 30 small numbers. Each run works only on dirty pairs: restaurants and days whose fact files arrived since the last published cutoff. It recomputes those daily totals from their facts, re-ranks only the restaurants that have a dirty day, and publishes only those. At night that is a few thousand restaurants, at lunch most of them, and it is the same code. Restaurants with no change keep their version and their cache entry."
Follow-up: "And when the day changes?" — All windows shift by one day, so the first run after midnight re-ranks everybody. It only sums daily totals, so it is still minutes, not the 40-minute full scan.
Scenario: marketing wants a "Trending now" label. Burger Barn's new spicy_wrap sells 300 units between 12:00 and 12:30. It should be on the shelf within a minute of earning its place, not at 12:38. Do you throw the batch design away?
Three ways to build it. Decide first, then click.
The idea. The design works. Turn the schedule from 30 minutes to 1.
Where it breaks. A run takes 8 minutes: start the cluster, list the files, recompute, publish. So eight runs are in flight at once, and each publishes data that is at least 8 minutes old. A batch can never be fresher than its own run time. It costs 30 times the cluster hours. And run 815 can finish after run 816 and move the pointers backwards.
The idea. On every sale the Orders service also adds the units to a sorted set in the cache, one per restaurant. The API reads the top of that set. Fresh within a second.
What it fixes. The freshness, completely.
What it still misses. Everything this design was built for. A sale that is sent twice counts twice. A cache restart loses the counts. A counter has no days, so the sales of eight days ago never leave a "7 days" count, and a refund has nowhere to go. And there are now two truths: the live shelf says 301, the batch says 298, with no version and no cutoff to explain the difference.
The key idea. Keep the contract and add a faster producer behind it. A stream job is a program that reads events one by one from a log and keeps running totals. It handles today. The batch stays the authority and corrects it.
How it works
fact_id once and saves its state regularly.The three designs side by side, in one picture:
Play the three options. A dashed box belongs to one design only.
start a runScheduler → Batch jobNothing is written in this step.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: batch every minute | Good: a live counter | Great: a stream for today | |
| Freshness | 8 minutes at best | A second | About a minute |
| A sale that is sent twice | Counted once | Counted twice | Counted once |
Check it against the scenario
| spicy_wrap at lunch | |
|---|---|
| Situation | Outcome with the Great option |
| 12:14, spicy_wrap passes the tenth dish | The stream job publishes Burger Barn's shelf at 12:15 with the cutoff 12:15 |
| A sale event is delivered twice | The stream job has seen the fact_id and ignores it. The batch would correct it anyway |
| The stream job crashes at 12:20 | It restarts from its saved state and the log. Until then readers get the last published version, with its cutoff |
| A refund for a sale of yesterday | The stream ignores earlier days. The next batch run handles it as in DD1 |
The trade-off to name. Two producers write to one store, so the rules must be strict: the stream only touches today, the batch wins, and a version is never moved backwards. And a stream job has state to save, restore and resize. That operating cost is the reason not to start here.
This page is about exact counts per restaurant with an hour of slack. When the question is a global real-time ranking over millions of items, where exact counting no longer fits in memory, the design is different: see Top-K Videos.
It is tempting because it is one line of code and it demos well. The tell is the first question about time. "How does a sale leave the 7-day count after 7 days?" A single counter cannot answer that. It needs a counter per day, then an expiry, then a way to take refunds, then a way to recover after a restart, and at the end it is a worse copy of the facts and the daily totals.
"With an hour of allowed delay I would not build streaming: a scheduled batch is simpler, cheaper and easy to audit. If the product needs a minute, I keep everything the readers see, the versioned snapshot, the pointer, the freshness fields, and add a stream job that maintains today's totals from a durable log and publishes through the same path every minute. The batch keeps running every 30 minutes from the same facts and overwrites the stream's numbers, so duplicates and refunds are still fixed in one place. I would not add live counters next to the batch: that is a second source of truth with no windows and no corrections."
Follow-up: "Why not only the stream?" — Because corrections to earlier days, backfills after a rule change and audits are batch-shaped work. A stream is good at now, a batch is good at being right.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| A dish was removed from the menu, or is sold out | The menu service decides at read time. The app drops the dish and shows the next one. That is why ten rows are stored when three are shown |
| Why not store the dish name in the snapshot? | It saves a call and shows stale names and prices for up to a run. Keep display data out and join when the page is built |
| A new restaurant, or one with very few orders | An empty or short list with fresh. The product can show house specials instead. The API only has to make clear that the batch is fine |
| The scoring rule changes, for example how a combo meal counts | The manifest records the code version of every run. A backfill marks the pairs of a date range dirty and goes through the normal publish |
For the patterns behind this page, see Stream Processing and Real-Time Aggregation for what DD4 adds, Scaling Reads for the cache in front of a small result, and the Caching and Blob Storage building blocks.
It is correct and fine for a small restaurant. For a hot one it reads 2.4 million lines per view, and there is no last good result to serve when the data is wrong.
They are easy to fake and hard to define. Finalized purchase units are one input that can be replayed and defended.
The ranks are not sorted again and the next run puts the units back. Write a correction fact and let the run recompute that day.
A crash in the middle leaves two cutoffs on one page and nothing to go back to. Stage a new version and switch pointers in one transaction.
The cache then shows a version the database may never publish. Clear it after the commit, and give every key a time to live.
A list alone cannot be judged. Return the version, the cutoff and a state, and make "no orders yet" different from "not ready".
30 days of raw lines take longer than the time between two runs. Keep daily totals and work only on the pairs that changed.
It adds state, late events and a second pipeline for freshness nobody asked for. Start with the batch and say what requirement would change that.
The shape of a strong answer: store every finalized order line as a fact that is never changed. Every 30 minutes, find the pairs of restaurant and day that changed, recompute their daily totals, sum the windows and rank. Stage the result under a new version and publish it with one transaction. Serve the shelf from a cache in front of a keyed lookup, with its version, its cutoff and a state. Let refunds and operator fixes enter as new facts and dirty pairs. Add a stream only when the product needs minutes.
A published result, not a live query
The batch path computes, the read path looks up. A page view costs ten small rows, for Luigi's and for Burger Barn alike.
Facts are only added
A sale, a refund and a late order are all new facts. Totals and rankings are recomputed from them, so every number can be explained and repaired.
Whole or not at all, with its age
A version is invisible until one transaction publishes it. The answer says which run it came from and what time it was computed up to.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | Defines popularity as purchased units per dish. Separates the batch job from the read path and explains why a snapshot lookup beats a query per page view |
| Mid-level | Walks through facts in object storage, daily totals, versioned snapshots in a database and a cache for hot reads. Explains how a late refund becomes a scoped recompute and not a live decrement |
| Senior | Keeps the read contract in the centre: one cutoff per version, the atomic publish, cache after commit, freshness states. Handles skew and incremental recompute, and argues when batch is enough and when a stream is worth its cost |
These aren't toy problems — they reflect real infrastructure challenges at companies that publish computed results to millions of readers. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
Why is the shelf not computed with a GROUP BY when the page is opened?
Question 2 of 10
How does the batch run produce Luigi's 30-day ranking?
Question 3 of 10
One order holds a line "3 x carbonara". How much does it add to carbonara's count?
Question 4 of 10
At 13:05 a refund arrives for 2 carbonara that were sold two days ago. What does the system do?
Question 5 of 10
Why would subtracting the refund from the published row not even last?
Question 6 of 10
Run 813 has staged its rows and dies before the pointer move. What do readers get?
Question 7 of 10
When does the batch job clear the cache keys of a restaurant?
Question 8 of 10
Since the last run, 3,000 of 200,000 restaurants had an order. What does the run compute?
Question 9 of 10
The API returns an empty items list with staleness "fresh" for Noodle Bar. What does that mean?
Question 10 of 10
Which change in the requirements justifies adding a stream job?
| Only if the publish is one switch. Overwriting rows leaves a mix of two cutoffs. And the answer must say how old it is, and tell "no orders yet" from "not ready" |
| DD3 | 3,000 of 200,000 restaurants had an order in the last half hour. What does the run recompute? | Everything: it is a batch job, it has time | 30 days of raw lines are 2.4 billion: 40 minutes for a run that is due every 30. Keep daily totals and recompute only what changed |
| DD4 | The product wants the shelf fresh within a minute. What now? | Run the batch more often, or count live in a cache | A batch is never fresher than its run time, and a live counter is a second truth with no days and no refunds. Add a stream for today, behind the same published contract |
| Late refunds and cancellations? | They must show up, but not in the same second | They enter through a recompute, never through an edit of a published number (DD1) |
| The batch is late, or a restaurant has no orders? | Serve the last good ranking and say so. An empty shelf and a missing one are different answers | The read contract has states, not just a list (DD2) |
| Names, photos, prices? | From the existing menu service | The ranking returns dish IDs and counts only (Phase 4) |
| The batch job finished its work | Readers see the result | A result is visible only after the publish step, and that step can fail |
| The shelf is empty | The system is broken | A new restaurant has no finalized orders yet. That is a valid, fresh answer |
| The API answered 200 | The ranking is current | It may be the last good one, an hour or more old. The answer has to say so |
| A dish is rank 1 | It can be ordered now | The dish may be sold out or gone from the menu. The menu service knows, the ranking does not |
| Facts |
| About 100 bytes a line: 8 GB a day, about 3 TB a year |
| Daily totals | About 40 different dishes sold per restaurant and day: 8 million rows a day, 240 million for 30 days |
| Snapshots | 200,000 restaurants x 3 windows = 600,000, with 10 rows each |
| Batch | One run every 30 minutes, about 8 minutes long. The cluster reads 1 million lines a second |
| Reads | 50 million shelf reads a day: 580 a second on average, 3,000 a second at lunch |
| One total per restaurant, dish and day |
| A 30-day window is a sum of 30 small numbers, not 30 days of raw lines |
| Recompute only dirty pairs of restaurant and day | 3,000 restaurants changed, so 3,000 are recomputed |
| A version number per run, a pointer per restaurant and window | A new ranking is invisible until the pointers move in one transaction |
| The cache is cleared after the commit, never before | The cache can only hold answers that were published |
| Version, cutoff time and a state in every answer | The app can show "updated 40 minutes ago" and tell empty from not ready |
| Dish IDs and counts only | Names, prices and sold-out belong to the menu service and change on their own schedule |
restaurant_idSTRING |
| For example r_42 |
item_id | STRING | The dish, for example carbonara |
quantity | INT | Units. Negative in a correction |
day | DATE | The day the units count for. A correction carries the day of the original sale |
kind | ENUM | SALE or CORRECTION |
DATE |
| A calendar day in the restaurant's timezone |
units | INT | The sum of quantity over all facts of that restaurant, dish and day, each fact_id once |
| Pointer |
(restaurant_id, window) with batch_version |
| Which version readers get. Moving it is the publish |
| Run manifest | batch_version, input_cutoff, dirty_pairs, code_version, status RUNNING, STAGED, PUBLISHED or FAILED, published_at | The record of a run: which facts it used and whether it was published. It settles disputes later |
| Rebuild request | job_id, idempotency_key (unique), restaurants, days, reason, status PENDING or DONE | An operator's order to recompute chosen pairs in the next run |
| Cache (Redis) | One key per restaurant and window with one whole published answer | Disposable. Cleared after a publish, 30 minutes to live |
stalenesslimitGET /v1/restaurants/{restaurant_id}/popular-items/windows | App | The windows that exist, with labels: 1d, 7d, 30d. The app does not hard-code them |
GET /v1/restaurants/{restaurant_id}/popular-items/freshness | Dashboards | The last publish, its cutoff, and when the next run is due |
POST /internal/popular-items/rebuild | Operators (internal) | Asks for a recompute of chosen restaurants and days, with a reason and an idempotency key. Answers 202 with a job_id |
GET /menu/items?ids= | App (menu service, not ours) | Names, photos, prices and availability for the dish IDs of the shelf |
| Phase 3: Publish and correct (FR2, FR4) |
| Green |
| One transaction moves the pointers. The cache is cleared. An operator asks for a rebuild |
| Every reader gets 812 |
| Phase 4: Read the shelf (FR3, FR5) | Purple | dana opens Luigi's page and sees carbonara at rank 1, with its age | One warm cache key |
SALE| 4 | Only now the loader confirms the lines to the Orders service. | Nothing |
| 5 | The confirmation is lost. The Orders service sends the line again, and it lands in the file of 12:12 with the same fact_id. | A second copy. The batch run counts a fact_id once |
fact_id| Daily total (r_42, carbonara, Nov 12): 31 to 34 |
| 4 | For each restaurant with a dirty day it adds up 1, 7 and 30 daily totals per dish. Luigi's, 7 days: carbonara 179 + 34 = 213, margherita 212, tiramisu 150. | Nothing |
| 5 | It sorts by units, keeps the top 10 and writes the rows under version 812. It is 12:37. | Snapshot (r_42, 7d, 812): carbonara 213, margherita 212, tiramisu 150. Manifest 812: STAGED |
| After the commit the job deletes the cache keys of the recomputed restaurants. |
| The keys popular:r_42:1d, 7d and 30d are gone |
| 4 | An operator has found a bad input file and calls the rebuild command: r_42, day Nov 10, with an idempotency key. The answer is 202 with job ID rb_17. | Rebuild request rb_17: PENDING |
| 5 | Run 813 at 13:00 reads the pending rebuild requests and adds their pairs to its dirty pairs: (r_42, Nov 10). | rb_17: DONE when 813 is published |
| 4 | The API writes the whole answer into the cache with 30 minutes to live. | The key holds version 812 |
| 5 | The API answers: carbonara 213, margherita 212, tiramisu 150, version 812, computed up to 12:30, fresh. | Nothing |
| 6 | The app asks the Menu service for names, photos and prices of the three dishes. Tiramisu is sold out today, so the app leaves it off. | Nothing |
| DD1 |
| A refund for an order that is already counted |
| 2 carbonara of two days ago are refunded |
| NFR2 — Trust |
| DD2 | The run dies in the middle of publishing | 120,000 of 150,000 restaurants are done | NFR2, NFR3, NFR5 — Trust, freshness, reads survive |
| DD3 | 3,000 of 200,000 restaurants changed | The run at 03:00 at night | NFR1, NFR3 — Scale, freshness |
| DD4 | The product wants the shelf fresh within a minute | A new dish sells 300 units over lunch | NFR3 — when the requirement itself moves |
| Work for one refund |
| One update |
| 2.4 billion lines |
| One daily total, three windows of one restaurant |
| Can a count be explained later | No | Yes | Yes |
| An operator's fix | Edit rows by hand | The full rebuild | The same dirty pair |
| The refund is for an order 40 days old |
| The day is outside every window. The daily total changes, no ranking does |
fresh. That means "no orders yet". A restaurant with no pointer at all gets not_ready.| The reader knows the age |
| No |
| No |
| Version, cutoff and a state |
| A restaurant with no orders | An empty list, or an error | An empty list, meaning unclear | An empty list with fresh, or not_ready |
| Going back one version | Not possible | Move the pointers back | Move the pointers back |
| Runs fail until 14:30 |
Still 812, now degraded_serving_last_good with its cutoff. The app decides what to show. On-call is paged |
| Version 814 turns out to be wrong | An operator moves the pointers back to 812. 48 versions are kept |
| Restaurants ranked again |
| 200,000 |
| 200,000 |
| 3,000 |
| Cache keys made cold | 600,000 | 600,000 | 9,000 |
| A correction for an earlier day | Seen | Missed | Seen |
| A backfill marks every pair of the last 30 days dirty: the 40-minute job, run once and on purpose |
| Handled |
| Not handled |
| Handled, by the batch |
| Sources of truth | One | Two that disagree | One: the facts |
| What it costs | 30 times the cluster hours | Little, until it is wrong | A second pipeline to operate |
| What exactly is "1 day"? | Calendar days in the restaurant's timezone, today included. Just after midnight the 1-day shelf is nearly empty, so the product may show yesterday until there is enough of today |
| A published version is wrong | Move the pointers back to an older version and clear the cache. 48 versions are kept, one day |
| A restaurant tries to push its own dish up | Only finalized purchases count, so it has to buy its own food. Refunded orders are removed by a correction fact |
| The rebuild call is sent twice | The idempotency key is unique in the table. The second call gets the same job ID |