YouTube Top K
Find the most viewed videos over a time range, such as the top 100 during the last hour.
Clarify this prompt before choosing components
Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.
| Ask the interviewer | Why the answer changes the design |
|---|---|
| Top by views, watch time or another metric? | Define event identity and aggregation value. |
| Exact top K or approximate, and over which windows? | State/compute needs and correction policy change. |
| Late events, duplicates and regional merging? | Watermarks, deduplication and deterministic merge govern accuracy. |
Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.
YouTube Top K: Understand the building blocks
Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.
YouTube Top K: Quick vocabulary
| Term | Meaning and role in this exercise |
|---|---|
| API: Application Programming Interface | The contract for requests, responses and errors between components. An API route does not itself enforce every business invariant. |
YouTube Top K: Event time, watermark and windows
What it means: Event time is when an event happened; arrival time is when it reached this processor. A window defines the interval grouped for computation, and a watermark expresses progress under a lateness policy.
Why this problem needs it: Popularity needs a defined interval and late-correction policy.
How to use it: Bind each event to its window identity, deduplicate under a declared horizon, and emit allowed revisions or reject/quarantine events past the finality boundary.
Example in this design: Bind every accepted view to the selected window rather than whichever minute processes it.
When it fits: Useful when delayed delivery should not silently move activity into the wrong reporting period.
Alternative and limits: Processing-time windows are simpler if arrival time is the intended business meaning. A watermark is not proof no older event can ever arrive.
YouTube Top K: Top K, heap and approximate sketch
What it means: Top K means the K largest values under a specified score/window. A heap tracks selected candidates; an approximate sketch trades memory for bounded error under its algorithm.
Why this problem needs it: Combining shard winners can omit the real global winner.
How to use it: Keep exact counts when feasible or state an explicit approximation/error policy. Define merge and late-correction behavior across partitions.
Example in this design: A totals 900+850+20=1770 while B totals 600+600+600=1800.
When it fits: Useful for popular-item rankings over high event volume.
Alternative and limits: A database sort is simpler for a small candidate set. Taking only local winners can discard the global winner; approximation is not exact ranking.
YouTube Top K: Deduplication identity and business qualification
What it means: Deduplication distinguishes repeated delivery of one event from genuinely separate events. Qualification decides whether a real event is eligible to count.
Why this problem needs it: Replay must not inflate a title’s qualified count.
How to use it: Use a stable event identity and atomic replay-safe sink, then evaluate the business rule with its own revision/window policy.
Example in this design: The same accepted view event increments the window once under the declared horizon.
When it fits: Needed when delivery may repeat and reports/billing must not count the same event twice.
Alternative and limits: An append-only raw log preserves evidence but needs a later qualified projection. Transport deduplication alone cannot detect fraud or define billable behavior.
YouTube Top K: Kafka partitioned event log
What it means: Kafka retains ordered records within partitions; consumers track offsets and can replay retained history. Partitioning distributes work.
Why this problem needs it: Retained partitioned history can support replaying a ranking computation.
How to use it: Pick the business ordering key, replication/acknowledgement policy and consumer checkpoint boundary. Coordinate replay with the output sink’s actual commit protocol.
Example in this design: Partition by an explicit key and checkpoint the result sink with its supported protocol.
When it fits: Useful when multiple consumers need retained event history or ordered stream processing.
Alternative and limits: A task queue fits job claiming without general history replay. Kafka transactions do not automatically make an external email/payment side effect exactly once.
Interview scope and guarantees
Return the most-viewed videos over explicit windows such as the last hour and day. Decide whether the answer must be exact or approximate and how late events change published results. A view definition must distinguish retries, bots, and legitimate repeat watching.
Capacity worksheet
Assume 1 billion view events/day: 11,574/s average and 57,870/s at 5× peak. At 100 bytes/event the raw stream is 100 GB/day. A count for each of 100 million videos at 16 logical bytes is 1.6 GB before window buckets and storage overhead; a heap alone does not store all counts.
Concrete API contract
POST /view-events {eventId,videoId,eventTime,sessionId}
GET /trending?window=1h®ion=...&k=100
Response includes asOf, windowStart, completeness and algorithmVersion.Data model and access paths
events(event_id,video_id,event_time,region)
counts(window_bucket,video_id,region,count)
topk(window,region,generation,rank,video_id,count)
watermarks(partition,event_time)Evolve a solution and explain each change
Read the diagram
Count exact events / Aggregate validated views per video and time window. / A full scan for every leaderboard is expensive.; Maintain partition summaries / Partition counting and periodically emit local top-K candidates. / Pruning too early can miss globally popular videos.; Merge with error policy / Merge sufficiently rich summaries or exact counts with watermark and revision rules. / Late events, skew, and approximation change the meaning of rank.
Step 1: Count exact events
Aggregate validated views per video and time window. A full scan for every leaderboard is expensive.
Step 2: Maintain partition summaries
Partition counting and periodically emit local top-K candidates. Pruning too early can miss globally popular videos.
Step 3: Merge with error policy
Merge sufficiently rich summaries or exact counts with watermark and revision rules. Late events, skew, and approximation change the meaning of rank.
Responsibility overview
Read the diagram
Viewer events to Ingest API: eligible view event; Ingest API to Event log: append event identity; Event log to Aggregator: consume partition; Aggregator to Rank store: window rank revision; Leaderboard reader to Rank store: read leaderboard; Aggregator to Event log: checkpoint input progress
Worked end-to-end scenario
Video X receives 100 views on each of ten partitions but is not in any partition top-10 because ten local videos each have 101. Globally X has 1,000 views while those local videos may have only 101 each. Taking only local top-10 lists misses X. Hashing all events for one video to its owner avoids that particular split-count problem; otherwise retain enough candidate information or use an approximation with stated error. Publish a leaderboard for a defined closed window and revise or discard late events according to policy. A client must know whether it sees provisional or finalized results.
Why these access paths matter
Deduplicate event IDs within a defined retention window; aggregate by video and window. Store leaderboard versions by window start, duration, and revision. Sliding windows need bucket expiry or another explicit rolling computation, not a forever counter. A view eligibility definition should exclude known fraud before ranking, with correction events if classification changes.
Build the baseline first
Read the diagram
View stream → per-video counters → window totals; Counter snapshot → top-K heap → result table; Trending API → cached published generation
- View stream → per-video counters → window totals.
- Counter snapshot → top-K heap → result table.
- Trending API → cached published generation.
Evolve the design under load
Read the diagram
Video-key partitions → local exact top K; Coordinator → union of shard winners → global top K; Late-event corrections → revised versioned results
- Video-key partitions → local exact top K.
- Coordinator → union of shard winners → global top K.
- Late-event corrections → revised versioned results.
Defend the hardest decision
If every video belongs to exactly one shard and each shard computes exact scores for the same window, the union of each shard’s local K contains the global K. That statement is false when one video’s count is split across shards before aggregation. A Count-Min Sketch estimates frequencies with collision overestimation and still needs a candidate strategy. Time windows require expiring old contributions, not simply incrementing an all-time counter.
Failure and recovery analysis
A mobile client uploads yesterday’s views after reconnecting. Event-time windows use watermarks and an allowed lateness policy; arrivals beyond the policy go to correction or audit processing. An at-least-once source can inflate counts unless event IDs or source-offset transactions protect updates. Deduplication retention must match the replay horizon.
Security and privacy boundary
Protect event ingestion from fabricated views and avoid storing unnecessary user identifiers in ranking state.
Interview follow-ups with reasoning
Question: What if K changes from 100 to 10,000?
Show answer and explanation
Answer: Store enough candidates or recompute from full counts.
Question: How do sliding windows work?
Show answer and explanation
Answer: Combine short buckets and state the boundary approximation.
Question: How do you test a sketch?
Show answer and explanation
Answer: Compare measured ranking error with an exact sample, including skewed distributions.
Operate and verify the design
Watermark lag, duplicate-event rate, correction count and ranking error versus exact samples.
Replay a window with duplicated and late events and compare the resulting published generation.
A second scenario to test transfer
Three workers each see partial counts. Video A has 900, 850, and 20 views; video B has 600, 600, and 600. A local top-one from only one worker can favor A, but merged totals are 1,770 versus 1,800. Merge candidate identities and counts before selecting global winners, or choose a summary algorithm with a stated recall/error property.
How can a video absent from every partition’s local top 10 still enter the global top 10 after merge?
Show answer and explanation
Answer: An item can be globally top-K while absent from every local list when its total is split across partitions. For example X has 100 on each of ten shards, while each shard has ten different local videos at 101. X totals 1,000 and the local winners each total 101. A merge of only the pruned lists cannot recover X. Aggregate each video to one owner before pruning, retain exact counts, or use a candidate algorithm with an explicit recall guarantee.
Compare alternatives
| Approach | Strength | Failure mode |
|---|---|---|
| Exact bucket counts | Clear corrections and expiry | Storage and key hot spots |
| Local top K merge | Less cross-worker data | Candidate omission |
| Frequency sketch | Bounded memory estimate | Collision overcount |
| Offline reconciliation | Quality reference | Delayed and expensive |
A design-changing exercise
Can the union of local top-K lists always produce the global top-K?
Show answer and explanation
Answer: No when an item total is split across partitions. Provide a proof for the chosen partition/aggregation plan or disclose approximation and candidate-loss risk.
Design workshop: exact windows before candidate pruning
Core requirement is top videos by eligible views over chosen windows, with ties by video ID and explicit provisional/final status. Fraud classification is upstream; ranking consumes its eligible/correction events. Choose one-minute refresh and two-minute allowed lateness as interview assumptions. A view event has eventId, videoId, eventTime and eligibilityVersion.
For an exact rolling hour, keep 60 minute buckets per video, a rolling sum and a per-owner ordered ranking structure. An admitted event increments its event-time bucket once. As minute M leaves the window, subtract that bucket and remove it. A heap with stale entries needs version checks and bounded cleanup; an ordered tree or rebuilt heap gives clearer memory bounds. Late events within policy update the historical bucket and publish a new leaderboard revision; events outside policy enter reconciliation or are rejected explicitly.
on_event(e):
if not durable_dedup(e.event_id): return
minute = floor(e.event_time / 60)
if minute not in accepted_window: return late_policy(e)
buckets[e.video_id][minute] += e.delta
totals[e.video_id] += e.delta
ranking.update(e.video_id, totals[e.video_id])
on_tick(new_minute):
for video, count in expired_bucket(new_minute - 60):
totals[video] -= count
ranking.update(video, totals[video])Deduplication, state changes and input checkpoint must recover consistently; the sketch is logical behavior, not a claim that separate dictionary writes and a log commit are atomic. Use a stateful streaming engine with checkpointed state or transactional aggregate revisions. Corrections can have negative deltas, but counts must remain consistent with the authoritative eligibility history.
Read the diagram
Placement / X count / Other local videos; Shard 1 / 100 / Ten distinct videos each have 101; Shards 2..10 / 100 each / Their own ten distinct videos each have 101; Global totals / X = 1,000 / Every competing local video = 101; Pruned candidate merge / X is absent / Cannot discover the actual global winner
If every video's entire window total belongs to one owner, union of owners' local K contains the global K: an omitted video has at least K videos ahead of it on its own owner, so cannot be globally top K under the same tie ordering. With split counts this proof fails. A hot video can be salted upstream only if its partial counts merge to one logical video total before candidate pruning. Salted local top lists are not enough.
Read the diagram
Merge all salts into video/window revision; Local K with closed watermark W and revision R; Wait for every required owner or declare partial; Publish window W/R, completeness and tie policy; Late valid correction updates bucket; Emit replacement revision; never mix old/new totals silently
At ten million active videos, 60 buckets of an illustrative eight bytes are 4.8 GB for counters alone; sparse event-time buckets reduce waste but add map/index overhead. Count-Min Sketch uses width about e/epsilon and depth ln(1/delta) for its usual nonnegative-frequency guarantee. For epsilon=0.001 and delta=0.01, choose width 2,719, depth 5; about 13,595 counters. It estimates frequencies with overcount and still needs candidate enumeration. Signed corrections require an algorithm supporting that update model; do not reuse insertion-only guarantees blindly.
Owner snapshots carry input watermarks. A coordinator that lacks an owner returns stale-but-complete last publication or explicit partial results; it does not silently treat a missing shard as zero. Store revisioned immutable leaderboards for comparison and replay validation.
Exercise: X has [100,100], A has [101,0], B has [0,101]. What is global top one and what does local-top-one pruning produce?
Show answer and explanation
Answer: X totals 200 and wins. Pruning emits A/B and loses X. Repartition by video before aggregation, or retain enough exact/certified candidate information; merging only those two candidates cannot recover the winner.
Requirement trace and verification
| Requirement | Implementing design block | Verification link |
|---|---|---|
| R1 — Complete the primary user journey within the stated scope. | P01–P04; P09–P10. | V1 — Exercise the successful journey and the excluded/boundary case stated in the scope. |
| R2 — Preserve the problem's authoritative data invariant under concurrency. | P05–P06; P11–P12; DD1. | V2 — Run the race/replay case below and assert the invariant at the durable authority. |
| R3 — Meet the declared scale and API behavior without unbounded work. | P05–P08; P13–P14; relevant overload deep dives. | V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity. |
| R4 — Recover from the named failure without losing or duplicating the user-visible outcome. | P15–P16; deep dives; Operations contract. | V4 — Replay a known event set with duplicates and lateness, and compare to exact batch results; test a globally popular video split across input partitions. |
Operational contract
| Area | Decision and signals |
|---|---|
| SLIs | Event watermark lag; duplicate/correction rate; snapshot age; exact-versus-published ranking error. |
| Overload limits | Cap event admission, per-video hot-key work, window-state retention, and snapshot rebuild concurrency. |
| Recovery | Replay checkpointed windows and publish a new revision; reconcile late corrections without mutating old snapshots. |
| Access controls | Accept events only from trusted producers and enforce metric eligibility before ranking. |
| Dominant cost | Windowed state, cross-partition merge traffic, and retained ranking revisions. |
Senior-level interviewer follow-ups
Question: A late event changes the winning video after a bucket was emitted. Can you correct it?
Show answer and explanation
Answer: Keep bucket state or durable deltas through the lateness horizon, then issue a versioned correction. Once data is discarded, exact correction is impossible without replaying the source.
Question: Why can local top-K lists fail to produce the exact global top K?
Show answer and explanation
Answer: A candidate omitted by every locally pruned list cannot be recovered. Merge compatible counts before pruning, or retain a proven superset; document the error if using approximate sketches.
A 60-second design answer
I would define the event-time window, lateness, and exactness requirement first. Events are deduplicated, assigned to time buckets, and merged into a global ranking. Expired buckets are subtracted at the exact boundary, while late arrivals trigger versioned corrections within retention. I would estimate counter memory and merge traffic, then choose exact aggregation or a stated approximation with error bounds.
Related concepts to revisit
Data Structures for Big Data Flink
Technical references
Kafka processing and external-sink boundaries.
PostgreSQL transaction isolation and concurrent updates.
Keep event identities and window identities separate
Window W contains events e1:A, e2:A, e3:B. A replay of e2 leaves counts A=2,B=1. A late valid e4:B may correct the declared window to A=2,B=2 if policy permits it. Write a window revision or idempotent aggregate replacement, rather than adding the entire recomputed result again.
W revision 1: A=2; B=1
duplicate e2: unchanged
late e4 accepted: W revision 2 -> A=2; B=2Read the diagram
W revision 1: A=2; B=1; duplicate e2: unchanged; late e4 accepted: W revision 2 -> A=2; B=2
All-time counts, tumbling windows and sliding windows have different state/retention costs. Salt hot updates and merge under a declared watermark. Taking only each shard's local top-1 can miss the global winner: shard 1 has A=100,X=99 and shard 2 B=100,X=99; X=198 wins globally but is absent from both local top-1 lists. Use adequate candidates/exact aggregation or explicitly accept approximation.
Show answer and explanation
Answer: A generic heap or “merge top-k” label does not prove exact global results for arbitrary distributed contributions. Specify whether each item's contributions are colocated or fragmented and how ties/late corrections work.
Decision review: YouTube Top K
YouTube Top K: What it is
A Top-K stream exercise ranks entities over an explicitly defined time window and counting policy.
YouTube Top K: Why it is needed
Local leaders need not contain the global winner; duplicates and late corrections can also corrupt rolling counts.
YouTube Top K: When to use it
Choose exact aggregation when the ranking must be exact. Approximate candidates require a measured recall/error contract and a completeness argument.
YouTube Top K: How to use it
Keep event identity, window identity and aggregate revision separate. Partition counts, merge the applicable contributions and select K only under the declared completeness and late-event rules.
YouTube Top K: Compare an alternative
Exact counts cost state and merge work. Approximate sketches or candidates may bound resources but cannot be presented as exact without additional proof.
YouTube Top K: Worked decision exercise
The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.
Workers see A counts 900,850,20 and B counts 600,600,600. Totals are A=1,770 and B=1,800. Selecting only an arbitrary worker’s top one can miss B, even though B wins globally.
Read the diagram
A partial counts 900,850,20: total 1770; B partial counts 600,600,600: total 1800; Global winner B need not be an arbitrary local top one; Window identity and event identity stay separate
Can rolling-window expiration race a replay that adds the same bucket again?
Show answer and explanation
Answer: Yes without versioned bucket lifecycle and a consistent replay boundary. Define which revision is included, how correction replaces it and what happens after the lateness horizon. Event deduplication alone does not decide which window a valid view belongs to.
YouTube Top K: Check the design
Check results against exact small fixtures, expiry/correction races and ties. Monitor lateness, retained buckets and candidate coverage rather than just fast ranking latency.
Extension: Eligibility corrections and complete ranking cuts
Start with exact owner counts, event-time buckets and local/global candidate reasoning. This workshop adds absolute eligibility revisions, zero retention, current versus historical corrections and complete compatible publication evidence.
Deep dive: corrections and finality belong to a named ranking generation
The baseline already explains exact owner-local Top K, split-count counterexamples and bucket expiry. This workshop adds absolute eligibility revisions, half-open event-time cuts, complete owner evidence and safe correction/rebuild publication. It is an original ranking exercise, not a description of YouTube's internals. Rank eligible view events under a stated upstream qualification policy; raw playback requests are not automatically unique people or qualified views.
Pin the event, window and eligibility decision identities
A logical view has a stable source-scoped ID, immutable video ID and event time. Qualification has a monotonically increasing decision revision and absolute contribution 0 or 1 for that same view. A corrected timestamp/video requires an explicit audited replacement/retraction protocol; it cannot silently reuse an existing event ID with different immutable fields. Transport delivery IDs and rebuilding generations do not replace the logical view identity.
view(source_scope, view_id, video_id, event_time, eligibility_rev, eligible_unit)
minute_total(video_id, minute, owner_epoch, aggregate_revision, absolute_count)
ranking(window_start, window_end, region, policy_version, routing_generation, revision)
owner_cut(ranking_generation, owner, complete_input_positions, watermark, state_hash)
publication(ranking_generation, required_owner_set, cohort_cut, complete, result_hash)For an aligned rolling hour ending at E=3,600 seconds, use [0,3,600): an event at 3,599 belongs; one at 3,600 does not. The next minute's window shifts both boundaries. Minute buckets support exact aligned-minute windows under this exercise; arbitrary second-level ends need finer buckets or boundary handling. The query key includes region/qualification policy, window endpoints, routing and algorithm generation, not merely top100.
Deduplicate/update a view's absolute eligibility and adjust its event-time bucket atomically with the recoverable input checkpoint under the chosen streaming/state authority. Revision 1 eligible=1, revision 2 eligible=0, revision 3 eligible=1 produces net one qualified view. Replaying revision 1 or receiving revision 2 after 3 does not change it. A revision-2 zero arriving before revision 1 must retain its zero/version state, so late revision 1 cannot resurrect the view. Blind signed deltas, repeated retractions or clamping negative counts can conceal missing/conflicting history.
Expire a bucket without adding it back to the live window
A view from minute 0 contributed to [0,60 minutes). At the next aligned tick it leaves [1,61 minutes), so subtract its bucket once. A duplicate tick cannot subtract twice. A later accepted eligibility correction to minute 0 may change a retained historical window's new revision, but cannot add minute 0 back to the current live hour. State mutation and inclusion in a particular window are separate decisions.
Retain enough event/eligibility and bucket evidence for the advertised lateness, correction and replay horizons. Two-minute allowed lateness is not permission to forget a longer declared replay contract. Beyond retained evidence, route to an explicit historical recomputation/audit process or return an honest inability to correct; do not mint a new view identity and count it again. Physical state retirement needs a barrier proving old input/decision replay can no longer affect the promised generation.
Choose this exercise's window finality rule explicitly: a window ending E is final for the ordinary two-minute late-arrival path only after required input watermark progress reaches E+120 and required retained contributions are applied. A watermark is an operational progress assertion, not proof no older event can ever appear. Beyond-policy arrivals follow a separately named historical correction generation rather than silently mutating a previously advertised immutable final result. The Flink watermark documentation explains progress and idle-input mechanisms; this finality/correction contract is an application choice.
An idle or disconnected partition is not automatically evidence of zero views. Declaring it idle changes progress assumptions and must still give returning old events a defined late path. A max event timestamp or largest broker offset cannot establish complete input decisions across missing partitions. Keep event-time watermark, complete input positions and aggregate version distinct.
Read the diagram
Eligibility revision 2 records zero → Delayed revision 1 proposes a positive → Retained zero version rejects resurrection → Expired bucket stays outside current window → Complete owner cuts gate named publication
Select candidates only after the required count merge
With disjoint complete video ownership, each owner computes exact totals for the same window, qualification policy and deterministic tie order (descending count, then ascending video ID). The union of owner-local K contains the global K: an omitted local candidate already has K videos ahead of it on that owner. Merge the candidates and sort under that same comparator. This proof requires complete scores and the same ownership/cut; it is not true for split partial counts.
For salted inputs X has 100 on each of two shards, while A has [101,0] and B [0,101]. Each local top-one omits X, but the merged total X=200 wins over A=101 and B=101. Merge all partial contributions into one logical video/window total before exact candidate pruning, or declare an approximation with demonstrated recall/error. Repartitioning needs a routing-generation handoff preserving ownership and complete state; duplicate old/new owner summaries are not two independent contributions.
Maintain access to nonwinning totals as well. If A=10 and B=9, then A's ten views expire or are retracted, B becomes the winner. Keeping only yesterday's winner cannot recover B. An insertion-only frequency sketch's guarantees do not automatically cover arbitrary signed corrections and expiry; candidate enumeration and its error model remain separate requirements. Exact sample fixtures should include ties, disappearing leaders and a previously unreported winner.
Publish a complete cut and keep current suppression outside rollback
Each required owner reports a snapshot for the same window/policy/routing generation and compatible input cut, including complete per-partition positions and watermark evidence. The coordinator validates the required owner set and unresolved gaps before activating a publication. Missing owner B cannot be treated as count zero. Serve a clearly stale last complete publication or an explicitly partial/provisional response while recovering; neither is a fresh exact board.
A rebuild restores compatible event/eligibility state and replays original logical identities. It must not add a whole recomputed count as another delta. Use absolute versioned bucket/score replacement and reject lower revisions, including after the latest value became zero. Validate counts/candidates and the required owner cut before atomic publication switch. A lost switch response resolves its stable operation result without creating another semantic generation.
Current content/account suppression still gates ranking responses, historical boards, snippets and exports. Rolling algorithm/count generation backward cannot restore a currently hidden video. Removing the top result at serve time can leave fewer than K eligible entries; a small backup list does not prove exact replacement recall. Return a truthful underfilled result with declared freshness/completeness and recompute a compatible eligible ranking, or use an independently proven retrieval strategy. Never disclose the hidden ID/count simply to explain the gap.
Budget identities as well as counters
At two million input events/s and 120 bytes/event, raw input is 240 MB/s or 20.736 TB/day before replication/indices. One million active videos with 62 illustrative eight-byte minute counters use 496 MB for counter payload alone: sixty aligned-minute buckets plus two retained for lateness. That is not the total state budget, nor sufficient retention for an arbitrary longer replay horizon.
At this same event rate, retaining an individual 24-byte identity/decision record for 3,720 seconds creates 7.44 billion records and at least 178.56 GB before indexes, allocator overhead, eligibility versions and checkpoints. A narrow counter-memory estimate can therefore miss the dominant correctness state. Where source-offset transactional processing replaces some per-event dedupe, define the identity/replay limitations and retain whatever eligibility corrections still require.
A six-million-event recovery backlog with 50,000/s capacity and 20,000/s fresh arrivals needs at least 200 seconds to drain. If serving requires 200 owners' top 100, a full merge handles up to 20,000 candidates per published cut, excluding owner ranking maintenance. Bound merge work, retained generations, recomputation and late-correction queues. Observe watermark lag, incomplete owner cuts, stale eligibility revisions, expired-window corrections, candidate recall against exact fixtures and currently suppressed output.
Canary a new qualification/routing/algorithm bundle on matching retained data, compare results at compatible cuts, then activate a complete generation. Fast query latency alone does not certify accurate counting, finality or eligibility. The executable fixture recomputes a tiny exact view set to test inclusion and correction semantics; it does not establish production incremental-bucket/checkpoint atomicity or performance. These teaching models are not a streaming engine, fraud classifier, broker checkpoint transaction or production distributed ranking service.
Top-K assessment: defend the named window and contribution set
Question: Eligibility revision 2 says zero before old revision 1 says one. Can the zero state be discarded because it contributes no count?
Show answer and explanation
Answer: No. Retain its decision revision for the promised replay horizon. Otherwise the delayed positive can resurrect a disqualified view. Apply absolute eligibility changes under the original immutable view identity and event-time bucket.
Question: A minute-0 correction arrives after minute 0 left the current hour. Does it increment today's live rolling total?
Show answer and explanation
Answer: Only if the original event time belongs to the queried window. It can update a retained historical correction generation under policy, while leaving the current [1,61-minute) cut unchanged. Expiry, historical correction and final publication are different transitions.
Question: One required owner is missing and a currently suppressed winner was removed. Can the coordinator label the remaining K entries exact and final?
Show answer and explanation
Answer: No. Missing-owner and filtered-candidate evidence are unresolved. Serve an honestly stale/partial/underfilled result or rebuild a complete compatible eligible cut; do not invent zero input or bypass current suppression to fill the list.
Score one point each for immutable view/absolute eligibility identity; half-open window/expiry/late-finality semantics; exact candidate-merge and nonwinner recovery proof; complete owner/rebuild/current-policy publication; finite dedupe/counter/merge/recovery budgets. Resurrecting a retained zero decision or finalizing with a missing owner is a critical failure. Repair the counting model, then retest with an idle returning partition, leader expiry, routing handoff and a stale pre-correction snapshot.