AlgoViz

Design a Top K / Trending Topics System

hard 45 min

Count billions of mentions a day and show the ten topics that are rising right now, in each country and city.

API and data

The contract first, then the data that serves it.

API

One way in, two ways out

HTTP
POST /v1/events                        (internal){ "batch_id": "b-91",  "events": [ { "id": "e1", "topic": "#superbowl", "account": "u7",                "city": "c12", "country": "US",                "at": "2026-02-08T19:45:32Z" } ] }-> 202 { "accepted": 497, "rejected": { "bad_format": 3 } }GET /v1/trends?place=US&window=1h&limit=10&category=sports-> 200  Cache-Control: public, max-age=0, s-maxage=30   ETag: "v8812"{ "place": "US", "window": "1h", "made_at": "...", "next_at": "...",  "stale": false,  "topics": [ { "rank": 1, "topic": "#superbowl", "people": 284700,                "usual": 1900, "change": 2, "since": "..." } ] }GET /v1/topics/superbowl/history?from=...&to=...&step=hour&after=c1GET /v1/trends/stream?place=US         server-sent events, every 30 s
Events come from our own services in batches. Lists are finished documents that caches may keep.

Decisions

DecisionReason
Batches of 100 to 1,000 eventsOne request for each event would cost more than the event
202 after the log has itThe caller is safe, counting is later
Batch id and event idA retry of a batch is recognised, and repeats are dropped
Whole list, one versionNo half-updated list, easy to cache
50 at mostThe list is stored once and cut per request
429 for noisy callersOne broken service must not fill the log

How do open pages learn about changes?

BreaksWebSocket for every reader
How
Push each change on its own socket.
Limit
Millions of sockets for one short message every 30 seconds.
Choose when
The page already has a socket for something else.
WorksAsk again every 30 to 60 seconds
How
Plain requests, answered by the edge.
Limit
Some requests return nothing new. An ETag makes those tiny.
Choose when
Almost always. Our default.
StrongServer-sent events through the edge, with polling as a fallback
How
The edge holds one line to us and copies a whole list every 30 seconds. Pages animate the difference.
Limit
Open connections at the edge, and not every CDN supports it.
Choose when
A live dashboard where movement is the point.

Data

What lives where

DataStorePattern
Raw eventsKafka, 7 daysAppend, read in order, replay
Seen accounts, sketches, bucketsWorker memory with checkpointsMillions of small updates
Finished listsRedis, replicatedRead whole by key
Topic display name, category, picturePostgreSQL, cachedLooked up once when listed
Blocked topics, review decisionsPostgreSQLFew writes, must be right
Hourly historyClickHouseScan by topic and time
No relational database is on the counting path. Writing 417,000 increments a second there would need many shards and would give nothing back.
Text
SET trends:US:1h   {"version": 8812, "topics": [...]}   EX 300SET trends:US:24h  {"version": 391,  "topics": [...]}   EX 7200GET trends:US:1h
A list is one value. Adding members to a sorted set would leave yesterday's topics behind and show half of an update.
SQL
CREATE TABLE trend_history (  topic  String,  place  LowCardinality(String),  hour   DateTime,  people UInt64,  usual  UInt64,  rank   UInt16) ENGINE = MergeTreePARTITION BY toYYYYMM(hour)ORDER BY (topic, place, hour);
ClickHouse: one row for each listed topic, place and hour. Asking for one topic's story reads a narrow range.

State held by one counter