The interview problem
Design a service that returns the 100 most-viewed items during the previous complete hour, refreshed every minute. It ingests 200,000 accepted view events per second across 100 partitions. Explain event-time windows, duplicate delivery, hot items and whether merging each partition's top 100 is correct. Offer an approximate mode with an explicit accuracy contract.
Original system-design practice, not a reported company interview. All workloads and numerical examples are illustrative. Primary documentation retrieved September 27, 2026; publication date unstated; interview date not applicable.
1. Define the ranking before the infrastructure
At minute boundary T, rank counts in the half-open event-time interval [T − 60 minutes, T). Order by descending count, then ascending stable item ID. Count accepted view events, not unique viewers. Admission rules reject malformed events and known abuse; they do not prove that every remaining view came from a person.
Return window boundaries, publication version, data watermark, completeness and accuracy mode with the list. Allow events to arrive up to two minutes late, producing provisional versions followed by a final version. Final means closed under this lateness policy, not complete knowledge of all real-world events. Later arrivals enter a correction workflow rather than silently changing a supposedly final snapshot.
The product label should say “most viewed in the last hour.” A growth-rate or personalized trend score is a different ranking function. An item with one million steady views and another that rose from ten to one thousand demonstrate why count and acceleration are not interchangeable.
2. Show why local winners can miss the global winner
| Item | Shard 1 | Shard 2 | Global count |
|---|---|---|---|
| A | 101 | 0 | 101 |
| B | 0 | 101 | 101 |
| X | 100 | 100 | 200 |
Each shard sends its top one: A and B. X is absent, even though it is the global winner. Fetching exact global counts for A and B cannot recover the missing candidate. The same construction works for top K: create K shard-specific items with count 101 on each shard, while X has count 100 on both.
Increasing the local list to an arbitrary fixed multiple of K improves recall on some workloads but does not prove completeness. A workload can place enough shard-specific items above X locally. Summing counts is safe; truncating candidates before summing is the dangerous step.
There is a useful exception. If every item's complete window count belongs to exactly one owner shard, the union of each owner's top K contains the global top K. An excluded item has at least K items ahead of it on its own owner under the same total ordering; those same K items also precede it globally. This proof needs complete counts, a common snapshot and identical tie-breaking.
3. Aggregate by item before truncating
authenticated events → admission + durable partitioned log
↓
deduplication + event-time minute buckets
↓
partial counts → shuffle by stable item ID
↓
item owners: complete per-minute and hourly counts
↓
owner top-100 for the same window/version
↓
coordinator merge → immutable ranking snapshot
↓
cached read APIUse the exact design as the baseline. Events carry event ID, item ID, event time and ingestion time. Deduplication and count updates need a recovery contract: an atomic state/checkpoint boundary or an idempotent sink keyed by the source batch and version. Route every copy of an event ID to the same deduplication authority, including copies delivered on different input partitions. A client retry must preserve the original event ID. A sketch or counter cannot detect a new ID that represents the same real-world action.
Each owner retains minute buckets and maintains the rolling sum by adding the newest bucket and expiring the oldest. Keep buckets long enough for the lateness policy and recovery. Late corrections update affected provisional windows. A coordinator requests the same logical snapshot from all owners; mixing one owner's new hour with another owner's old hour invalidates the result.
For a very hot item, first aggregate salted subkeys in short batches, then combine all partials at the item's final owner before ranking. Carry cumulative batch revisions or immutable batch identities so retries do not double count. Ownership migrations use fenced epochs and a snapshot barrier to avoid missing or double-counting an item. Salting distributes updates, but does not make partial top-K truncation correct.
4. Work through capacity and query costs
At 200,000 events/second, one hour contains 720 million events. With an illustrative 100-byte encoded event, ingress is 20 MB/second and 72 GB/hour before replicas, indexes and protocol overhead. Three stored copies require 216 GB/hour. A 62-minute deduplication horizon contains up to 744 million event IDs; even an assumed 24 bytes per entry requires 17.856 GB before data-structure and replication overhead. Deduplication state is a first-class cost. A 62-minute horizon is an illustrative sizing assumption, not a universal correctness rule: replay beyond it must be rejected by the closed-window policy or handled using longer-lived replay identities.
With 100 item owners, the ranking coordinator receives at most 10,000 rows per minute. At an assumed 32 bytes per row, that is 320 KB per refresh before transport overhead. This is inexpensive because aggregation has already done the difficult work. Balanced ownership would average 2,000 updates/second per owner before local batching, but item popularity can make that average misleading.
If ten million items are active in every minute, 60 buckets of eight-byte counts alone consume 4.8 GB. Keys, timestamps, sorted indexes, late-event retention, checkpoints and replicas add to that. Sparse buckets can reduce this baseline when activity is intermittent. Do not use event throughput alone to estimate state: distinct item cardinality and retention also matter.
5. Make approximate mode auditable
When exact item state is too expensive, keep mergeable frequent-item summaries for nonoverlapping minute buckets. Merge the 60 required buckets for an aligned window, using compatible implementations and parameters. Do not subtract an expired summary from a merged summary unless the selected algorithm explicitly supports that operation. Rebuild the window from retained buckets or use a merge tree with versioned leaves. Replacing a corrected bucket also replaces its contribution; merging both versions double counts it.
Apache DataSketches provides frequency bounds, a global error measure and frequent-item queries with different inclusion guarantees. Its error table gives the sizing expression T = 3.5N/M outside the small-stream exact case. The overview notes a rare randomized-purge qualification to the worst-case proof. Validate the selected library version, merge behavior and reported bounds instead of presenting a sizing formula as an unconditional application guarantee.
For an original sizing example, N = 720,000,000 and M = 65,536 give T ≈ 38,452.15 events, about 0.00534% of total volume. This can look small while exceeding the gap between the 100th and 101st items. A heavy-hitter threshold is not a promise that the top 100 will all be distinguishable, or even all returned.
The application should reason from verified intervals: for each retained candidate, L(item) ≤ true count ≤ U(item), plus a bound B for every omitted item. A chosen set S of K candidates has certified membership if its smallest lower bound strictly exceeds both B and every nonselected candidate's upper bound. Membership certification does not establish the internal order of S. Overlapping intervals mean unresolved ordering, not an actual tie in the underlying counts.
For example, suppose A is in [120,000, 130,000], B in [115,000, 125,000], C in [110,000, 122,000], and all omitted items are at most 40,000. Using interval midpoints as illustrative point estimates selects A and B, but does not certify top-two membership: B's lower bound is below C's upper bound. An exact recount over the same snapshot gives A = 126,000, B = 116,000, C = 121,000, so A and C are the correct top two. Their exact counts also exceed the omitted bound, completing the membership proof.
Exact recounting requires retained data or an exact count store. If candidate coverage cannot be bounded, recounting a few candidates only improves their counts; it does not prove the ranking. Fall back to a complete exact aggregation, enlarge the summary, or publish an explicitly approximate result. Do not manufacture confidence by reporting more decimal places.
6. Handle windows, replay and unavailable partitions
- Boundary error: the minute-aligned contract permits exactly 60 complete buckets. An arbitrary request at 12:34:45 needs partial edge buckets or a clearly disclosed rounded window. A burst inside the omitted 45 seconds can dominate count error even when sketch error is small.
- Missing shard: a complete ranking cannot be claimed while contributions are missing. Serve the last complete snapshot with its timestamp, or label the new result partial. Small traffic share does not imply the missing shard cannot contain the winner.
- Replay: checkpoint offsets and state consistently. Merging a retried sketch again counts its entire contribution twice. Keep immutable partition/window/version identifiers and replace superseded contributions.
- Negative corrections: abuse removal or deletion may require rebuilding retained buckets. An insertion-only summary does not automatically support decrementing counts.
- Flat popularity: many nearly equal items make exact top-K identification expensive. Agree whether stable approximate membership is acceptable; hysteresis changes the displayed ranking contract.
- Unbounded dimensions: country, category and tenant filters multiply state. Precompute a bounded set of approved slices and route unusual queries to slower aggregation. Never filter a global top 100 and call the result a slice's top 100.
7. Verify accuracy independently from freshness
Compare with exact offline aggregation on the same accepted, deduplicated events and snapshot. Test the split-winner example, equal-count tie ordering, a single hot item, uniform popularity, boundary bursts, late events, duplicate batches, failed owners and rebalanced ownership. Check counts as well as membership; high top-K overlap can hide systematic double counting.
Track publication delay, source lag, missing partitions, late-event rate, duplicate suppression, summary error bounds and fraction of rankings that can be certified. For approximate results, report recall@K against an exact reference and count error separately. A good average does not excuse an incorrect completeness flag.
8. Interview follow-ups
- What if views must be distinct by viewer? Counting events is no longer sufficient; define the viewer identity and deduplication window, then account for the cost and error of per-item distinct counting.
- What if ranking uses growth? Retain a baseline interval, handle tiny denominators and define uncertainty for the new score. Frequency bounds do not transfer unchanged to ratios.
- Could each shard return 1,000 instead of 100? It may help empirically, but without an omitted-item bound or ownership proof it remains a heuristic.
- Must every result be exact? Prefer exact owner aggregation when affordable. Approximate summaries trade state for uncertainty; they should change the API contract explicitly.
Self-review rubric
A strong answer gives a concrete counterexample, proves the item-owner exception, defines aligned event-time windows and snapshot consistency, calculates state and transport costs, and separates candidate coverage from count accuracy. It handles replay, late data and missing partitions without claiming false completeness. An excellent answer can state a top-K membership certificate and explain why that certificate does not necessarily order the winners.
Sources and attribution
- Apache DataSketches: Frequent Items overview — summary capabilities, bounds, merging and implementation qualifications.
- Apache DataSketches: frequency error table — threshold sizing and inclusion semantics.
Documentation publication dates were not stated; retrieved September 27, 2026. The prompt, architecture, counterexample, capacity estimates and interval certification example are original practice material. There is no claimed interview date or company attribution.
Continue your preparation
Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.