Skip to content
SD-22 · Back to the write-up

Design a Top K Rankings

Count every event in a log partitioned by item, rank each list once a minute, and serve charts from a cache and the edge.

Follow a request

Clients
Edge + ingest
Counting
Ranking + data
Purchase serviceSends events
ReaderApp or web
CDNPages, 30 s
API serversStateless
Dedupe filterSeen today?
Event log16 partitions
Counter workersOne per partition
Count storeRollups by item
Top-K builderEvery minute
Rankings cacheVersioned lists
1store → api · POST /v1/eventsThe purchase service checks a receipt and sends a batch of up to 500 events, each with an event_id.1 / 5

The numbers, at a glance

For every chart view that reaches us……the CDN answers 19 more
1 miss ≈ 700/s at peak19 edge hits
Writes, before and afterAt 200,000 events a second
The lists are tiny81,000 lists × 200 entries × 16 bytes
So every cache node keeps every list, and none is hot.

An event, in order

Ingest returns at step 4. Steps 5 to 9 happen off the request path, within a minute.

Purchase service
API server
Dedupe filter
Event log
Counter worker
Top-K builder
Rankings cache
1 POST /v1/events
2 seen (user, item) today?
3 no
4 append by item_id
5 202
6 event stream
7 changed keys, via store
8 write v8813
9 flip :current
RequestResponseAsync, does not block

How to count and rank

The decision this question is really about.

Sort on every read
Too slow
event
UPDATE n = n + 1
ORDER BY per view
+ Exact and live.− A big sort per view, a hot row per viral app.
Hourly batch
Too stale
raw log
batch job / hour
81,000 lists
+ Exact and simple.− Charts an hour old.
Stream + top-K build
Our pick
log by item_id
count in memoryflush / 10 s
rank / minutecache + CDN
+ Exact, a minute fresh, cheap reads.− A log, workers and a builder to run.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ≈ 1,000 events/sMake it work
Clients
API server
SQL counts
One server, increments and sorts in SQL.
Stage 2 · ≈ 14,000 views/sPrecompute the charts
Clients
Load balancer
API × N
Count DBTop-K builderRankings cache
Rank each list once a minute; reads hit a cache.
Stage 3 · ≈ 200,000 events/sCount off the path
Clients
Load balancer
API × NEvent log
Counter workers × 16
Count storeTop-K builderRankings cache
Append to a log by item id; workers combine and flush.
Stage 4 · 200,000 events/s + botsKeep it fair
ClientsCDN
Load balancer
API × NDedupe + fraud filterEvent log
Counter workers × 16
Count storeTop-K builderRankings cache
Dedupe per user and day, fraud rules, and edge-cached charts.
Was this walkthrough useful?Your vote tells us what to improve next.