Ask most candidates to build “trending hashtags” and they write SELECT hashtag, COUNT(*) FROM events WHERE ts > now() - interval '1 hour' GROUP BY hashtag ORDER BY count DESC LIMIT 50. Then the interviewer turns the dial: the firehose is 5 billion events a day, the number of distinct hashtags and queries in a day is in the hundreds of millions, most of them seen once, and “trending” does not mean “most frequent” - a hashtag that has been popular for a year is not trending, a hashtag that went from 40 mentions an hour to 40,000 in ten minutes is. And you must refresh every few seconds. Now the GROUP BY is dead three times over: you cannot keep an exact per-key counter for hundreds of millions of keys, you cannot scan an hour of raw events on every refresh, and COUNT(*) measures volume, not the thing you actually want, which is velocity.
So the real problem is: approximate the heavy hitters over a sliding time window from a firehose of billions of events, measuring which keys are rising fastest, in near-real time, without storing the raw events and without an exact counter per key. That last clause is the entire design. The key space is effectively unbounded and dominated by singletons (hashtags nobody repeats, typo queries), so the exact-counter approaches that work when you have 5 million apps simply do not fit here. This is where sketches earn their keep: Count-Min Sketch for sublinear frequency estimation, Lossy Counting / Space-Saving to prune the long tail of one-offs, and a decayed or windowed structure to make “rising” mean something. Let me build it properly.
Functional Requirements (FR)
In scope:
- Ingest the firehose. Every post, hashtag use, and search query is an event. Billions a day. A single event is
{key, type, ts, geo, lang}wherekeyis a hashtag like#worldcupor a normalized search string. - Trending list, refreshed every few seconds. Return the top K (say K=50) rising keys - the ones whose rate of mention is accelerating fastest right now - updated at least every 5-10 seconds so a breakout shows up almost immediately.
- Sliding window of recent activity. “Trending” is measured over a recent window (say the trailing 5-60 minutes), not all of history. Events older than the window stop contributing.
- Per-geo and per-language boards. Trending in India is not trending in Brazil. Same machinery, partitioned by
geoandlang, plus a global board. - Rising, not just frequent. The score must reward acceleration. A steadily huge evergreen tag (
#love) must not pin the board; a new spike must surface even at lower absolute volume. - Approximate is acceptable. We return a ranked list of trending topics; being off on the exact count of rank 43 changes nothing a user perceives. The product is the list, not an audited ledger.
Explicitly out of scope (naming it means I own the boundary):
- Exact counts per key. We never promise “
#worldcupwas used exactly 1,482,331 times.” We promise it is trending and roughly how hot. Exact analytics counts are an offline warehouse query, not this system. - Arbitrary historical windows. “What was trending at 3pm last Tuesday” is a warehouse/OLAP question. We serve the live trailing window only.
- Spam, bot, and manipulation filtering. A botnet pushing a fake tag is a separate abuse pipeline that scrubs the stream before it reaches us. I note where that gate sits; I do not build it here.
- Semantic clustering / topic modeling. Grouping
#worldcup,#fifa, andworld cup finalinto one “topic” is an NLP layer on top. We trend normalized keys; clustering consumes our output. - Full-text search or the query backend. We count query strings as events; we do not serve search results.
- Editorial overrides and safety filtering. Human curation and blocklists are a policy layer layered on the ranked output, not part of the counting engine.
The one decision that drives everything: the key space is unbounded and singleton-dominated, so we cannot afford an exact counter per key, and “trending” is velocity not volume. Every hard choice below follows from “estimate heavy-hitter frequencies in sublinear space over a sliding window, and rank by acceleration.”
Non-Functional Requirements (NFR)
- Scale: ~5B events/day. Average ingest ≈ 58K events/sec, but news breaks in bursts (a goal, a verdict, an earthquake), so size for a peak of about 250K events/sec. Distinct keys per day: hundreds of millions, the vast majority seen once or twice.
- Latency: trending-board read p99 under ~20ms (served from cache; the answer is identical for everyone in a geo/lang). Event-ingest ack p99 under ~10ms - fire-and-forget. Freshness: an event influences the board within ~5-10 seconds.
- Availability: 99.9%+. The trending panel is front-and-center. It must degrade to slightly stale rather than error. Losing a few seconds of counts during a failover is fine.
- Consistency: eventual and approximate by design. Two nodes may briefly disagree on whether a tag is rank 44 or 47, or on its exact estimated count. That is acceptable. What is not acceptable is a dead tag stuck at #1 because the window never expired, or a genuine breakout taking minutes to appear.
- Durability: low for raw events, medium for the sketches. Individual events need no per-event durability on the counting path - dropping 50ms of mentions shifts a tag’s estimate by a rounding error. The sketch state is rebuildable by replaying the trailing window from a cheap durable log, so no structure is a precious ledger.
- Memory: the binding constraint. We refuse to let counting memory grow with the number of distinct keys. It must be bounded by the sketch dimensions, not by how many hashtags the internet invented today.
Back-of-the-Envelope Estimation (BoE)
The memory number is the whole argument, so let me do the arithmetic that kills the naive design and sizes the sketch.
Traffic:
Events per day: 5,000,000,000 (5B: hashtag uses + search queries)
Average ingest QPS = 5B / 86,400 ≈ 57,870 events/sec
Breaking-news bursts (say 4-5x average):
Peak ingest QPS ≈ 250,000 events/sec
Reads (people viewing trending): very high, BUT one answer per
(geo, lang, window). Everyone in "India, Hindi" sees the SAME list
-> collapses to ~1 recompute per board per few seconds, served from cache.
Why an exact counter per key does not fit:
Distinct keys in a day: ~300,000,000 (300M) - heavy singleton tail
(hashtags, typo'd queries, one-off strings nobody repeats)
Exact hash map: key string (~avg 20 bytes) + 8-byte count + map overhead
(pointers, load factor) -> realistically ~60-80 bytes per entry.
300M * ~70 bytes ≈ 21 GB ... per window ... per (geo, lang) board.
With ~50 geos * ~40 langs partitions this explodes, and 90% of those
20 GB is singletons that will NEVER trend. We are paying to store noise.
That is the trap. The exact map is dominated by the long tail of keys that occur once and can never be heavy hitters, yet cost the same memory as the winners. The whole point of this problem (unlike a bounded 5M-app key space) is that we must not pay per distinct key.
Count-Min Sketch instead - memory bounded by accuracy, not key count:
CMS error bound: estimate overshoots true count by at most eps * N with
probability >= 1 - delta, where N = total events in the window.
Pick width w = ceil(e / eps), depth d = ceil(ln(1/delta)).
eps = 0.0001 (0.01% of stream total), delta = 0.001 (99.9% confidence):
w = ceil(2.718 / 0.0001) ≈ 27,183 (round to 2^15 = 32,768)
d = ceil(ln(1000)) = ceil(6.9) = 7
One sketch = w * d * 4-byte counters = 32,768 * 7 * 4 ≈ 917 KB.
That is under 1 MB to estimate frequencies over the WHOLE key space,
regardless of whether there are 300M distinct keys or 3B. Memory is
decoupled from key count entirely. That is the point.
Sliding window = a ring of sketches, not one:
Window = trailing 60 min, resolution = 1 min -> 60 time-bucketed sketches.
60 sketches * ~1 MB = ~60 MB per (geo, lang) board.
Even 50 geos * 40 langs (and most are sparse/merged) -> a few GB total,
sharded across nodes. Compare to 20 GB PER board for the exact map.
Candidate set (the keys that might trend) - Lossy Counting bounds it:
We only need the *heavy* keys, not all 300M. Lossy Counting / Space-Saving
keeps at most ~1/eps monitored keys:
1/eps = 1/0.0001 = 10,000 monitored keys per board.
10K entries * ~40 bytes (key string + counters) = ~400 KB per board.
This is the structure that holds the actual candidate strings; the CMS
holds the counts. Together: sublinear in the key space.
Storage / bandwidth:
Board response: 50 entries * ~80 bytes ≈ 4 KB, served from cache.
Raw event: ~60-80 bytes on the wire.
Ingest bandwidth at 250K/sec * 80 B ≈ 20 MB/sec. Modest.
Durable replay log (rebuild only, OFF hot path): 5B/day * 60 B = 300 GB/day
-> cheap object storage, retained ~2x the max window, then dropped.
The scarce resources are ingest throughput (fold 250K events/sec into sketches) and counting memory (which we have just bounded with sketches instead of letting it grow with distinct keys). Bandwidth and read load are non-events. Size for ingest and memory.
High-Level Design (HLD)
Three planes. A write path that takes the firehose, shards by key, and folds each event into time-bucketed Count-Min Sketches plus a Lossy-Counting candidate set per shard. An aggregation/scoring layer that, every few seconds, rolls up per-shard candidates, estimates their current-window and baseline frequencies from the sketches, computes a rising score, and takes the top K. A read path serving the precomputed board from cache. A cheap durable log tees off for rebuild only.
WRITE PATH (event firehose, ~250K/sec peak)
┌────────────────────────────────────────────────────────────────────┐
│ Clients / post + search svc --event--> API GW / LB --> Ingest │
│ (stateless) │
│ 202 Accepted (fire-and-forget) │
└──────────────────────────────────┬─────────────────────────────────┘
│ produce {key, type, geo, lang, ts}
┌──────────▼───────────────┐
│ Kafka (partitioned by │ <- same key
│ hash(key), N partitions) │ same shard
└──────────┬───────────────┘
┌─────────────────────────────┼─────────────────────────────┐
▼ ▼ ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Count Shard 0 │ │ Count Shard 1 │ ... │ Count Shard M │
│ -------------- │ │ │ │ │
│ ring of CMS │ │ ring of CMS │ │ ring of CMS │
│ (1 per minute) │ │ per (geo,lang) │ │ per (geo,lang) │
│ + Lossy Counting │ │ candidate set │ │ candidate set │
│ candidate set │ │ (heavy keys only)│ │ (heavy keys only)│
└────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘
│ every few sec: emit local candidate keys + their │
│ window-sum and baseline estimates from the sketches │
└─────────────────────────────┬────────────────────────┘
▼ AGGREGATE + SCORE
┌─────────────────────────┐
│ Trending Aggregator │ every ~5-10s:
│ - union shard candidates│ per (geo,lang):
│ - estimate f_now, f_base│ merge, score,
│ - rising score + rank │ top K
└───────────┬─────────────┘
┌────────▼─────────┐
│ Board Cache │ key = geo:lang:window
│ (Redis / CDN) │
└──────────────────┘
(side path) Kafka --tee--> Durable Replay Log (object store)
retained ~2x window, for shard REBUILD only
Request flow - an event (write hot path):
- A client or the post/search backend sends
POST /v1/eventswithkey,type,geo,lang. The Ingest service is stateless: normalize the key (lowercase, strip punctuation, canonicalize the hashtag/query), stamp a server-sidets, produce to Kafka, return202 Accepted. No durable write blocks the ack. - Kafka partitions by
hash(key)so every event for a given key lands on the same partition and therefore the same count shard. A key’s estimate stays whole on one node - the routing decision that makes the later merge correct and keeps the sketch per-shard. - The Count Shard consumer folds the event into the current minute’s Count-Min Sketch for the relevant
(geo, lang)(and the global board), and feeds the key into that board’s Lossy Counting candidate structure so heavy keys get promoted to the monitored set. Folding isdhash-and-increment operations - a handful of memory writes, no per-key allocation. - Within a few seconds the sketches and candidate set reflect the event, so the next aggregation sees it.
Request flow - a trending read:
- A user opens the trending panel for “India / Hindi.” The client calls
GET /v1/trending?geo=in&lang=hi&k=50. The Read Service returns the cached board for that key - one precomputed list for everyone. Sub-millisecond. - The cache is kept warm by the Trending Aggregator, which every 5-10 seconds, per hot board: pulls each shard’s local candidate keys, queries the sketch ring for each candidate’s current-window sum
f_nowand its baselinef_base, computes the rising score, takes the top K, and overwrites the cache. Cold (rarely-viewed) boards are materialized lazily on read with a short TTL.
The key architectural insight: counting is approximate and sketch-based (memory bounded by accuracy, not key count), sharded by key so each estimate stays whole, the long tail of singletons is pruned by Lossy Counting, the window slides by rotating a ring of sketches, and the score is acceleration not volume. We never store raw events on the hot path and never keep a counter per distinct key.
Component Deep Dive
Four hard parts, each naive-first then evolved: (1) counting frequencies over an unbounded key space in bounded memory; (2) pruning the singleton tail to a candidate set; (3) sliding the window and expiring old counts; and (4) scoring rising rather than frequent, then merging across shards.
1. Frequency estimation over an unbounded key space: Hash Map -> Count-Min Sketch
This is the heart of the design. Everything else assumes we can ask “roughly how often has key X appeared” cheaply.
Approach A: An exact hash map of counts (the naive instinct)
Map<key, count>; increment on each event; read the count directly.
Where it breaks: the key space is unbounded and singleton-dominated. As shown in the BoE, 300M distinct keys a day at ~70 bytes each is ~20 GB per board, and 90% of that is one-off keys that can never trend. Memory grows with the number of distinct strings the internet produces, which is exactly the quantity we do not control. At 250K events/sec you also allocate and hash a new map entry for every novel key - a steady stream of GC pressure and cache misses for data you will throw away. The map scales with the tail, and the tail is noise.
Approach B: Count-Min Sketch - trade exactness for fixed memory
A Count-Min Sketch (CMS) is a 2D array of counters, d rows (“depth”) by w columns (“width”), with d independent hash functions. It estimates frequencies in O(w*d) memory regardless of how many distinct keys exist.
Structure: counter[d][w] (d rows, w columns), d independent hashes h_1..h_d
INCREMENT(key): # on each event
for i in 0..d-1:
counter[i][ h_i(key) % w ] += 1
ESTIMATE(key): # frequency query
return min over i of counter[i][ h_i(key) % w ]
Why MIN: every real count lands in each row's cell for the key, but OTHER
keys hashing to the same cell only ADD to it. So each cell is an
OVER-estimate; the smallest across the d rows has the fewest collisions
and is the tightest upper bound. CMS never under-counts, only over-counts.
The accuracy guarantee is the thing to recite: with w = e/eps and d = ln(1/delta), the estimate exceeds the true count by at most eps * N (N = total events in the sketch) with probability >= 1 - delta. From the BoE: eps = 0.0001, delta = 0.001 gives w ≈ 32,768, d = 7, under 1 MB - to estimate any key’s frequency across the whole stream.
+-------------------------------------------------------------+
| row 0: h_0 -> [ . . 17 . . . 5 . . 231 . . . . . . 4 . . ] |
| row 1: h_1 -> [ . 42 . . . . . 9 . . . . 18 . . . . . 7 . ]|
| row 2: h_2 -> [ . . . 3 . . 88 . . . . . . 12 . . . . . . ]|
| ... (d=7 rows) |
+-------------------------------------------------------------+
ESTIMATE("#worldcup") = min(row0[h0], row1[h1], ... row6[h6])
Why CMS fits this problem exactly: memory is w*d, a constant, so 300M distinct keys cost the same as 300. The error is proportional to eps * N - additive in the stream total - which matters because the error is tiny relative to a true heavy hitter (a tag with millions of mentions) and only noticeable for the rare keys, which we do not care about anyway. CMS over-counts, never under-counts, so a genuine heavy hitter can never be hidden by the sketch; at worst a mid-tier key looks slightly hotter than it is. For trending, where we want the big risers, a structure that cannot hide the big ones and only fuzzes the small ones is precisely the right bias.
One subtlety: CMS gives you a count for a key you name. It does not enumerate the heavy keys. So the sketch answers “how hot is #worldcup,” but something else must tell us #worldcup is worth asking about. That is the candidate-set problem, next.
2. Finding the heavy hitters without listing every key: Lossy Counting / Space-Saving
CMS estimates a named key. We still need the set of candidate keys to score, and we must get it without keeping all 300M strings.
Approach A: Scan the CMS / keep every key you ever saw (naive)
You cannot read “the top keys” out of a Count-Min Sketch - it is lossy and keyless; the cells do not know which strings mapped to them. The naive fix is to keep a side set of every key seen so you can query each one. That reintroduces the exact 20 GB map we just eliminated. Dead end.
Approach B: Lossy Counting - bounded monitored set, drop the tail
Lossy Counting (Manku-Motwani) keeps a small table of (key, estimated_count, error) and periodically evicts keys that cannot be heavy hitters. The stream is cut into buckets of width 1/eps; after each bucket, any monitored key whose count plus error is below the current bucket boundary is dropped.
Parameters: eps (error), support s (we want keys with freq > s*N).
Keep a table D of (key -> (f, delta)). bucket_width = ceil(1/eps).
ON event(key):
if key in D: D[key].f += 1
else: D[key] = (f=1, delta=current_bucket - 1)
AT each bucket boundary b:
for (key, (f, delta)) in D:
if f + delta <= b: # cannot reach the support threshold
remove key from D # drop the tail, reclaim the slot
OUTPUT (heavy hitters): keys with f >= (s - eps) * N.
- Bounded size. Lossy Counting provably keeps at most
(1/eps) * log(eps*N)entries, and in practice ~1/eps= 10,000 monitored keys per board. That is the candidate set: a few hundred KB, not 20 GB. - The tail evaporates. A hashtag seen once gets
f=1and is dropped at the next bucket boundary. Singletons never accumulate. We pay only for keys that keep showing up - exactly the ones that might trend. - No false negatives for true heavy hitters. The guarantee is that any key with true frequency above
s*Nis retained (its count can be underestimated by at mosteps*N). We may keep a few extra borderline keys (false positives), which is fine - they get filtered by the score.
Space-Saving is the close cousin and often preferred: it keeps a fixed m counters, and when a new key arrives and the table is full, it evicts the minimum counter and hands its count (as the new key’s error bound) to the incomer. Fixed memory, strong top-K guarantees. The two are interchangeable here; the point is a bounded monitored set that holds only candidates.
The division of labor is the elegant part: Lossy Counting / Space-Saving decides which keys to watch (bounded set of candidate strings); Count-Min Sketch decides how hot each one is (bounded-memory frequency, including the per-minute buckets needed for the window and the baseline). Neither alone suffices - LC alone lacks the fine-grained windowed counts, CMS alone cannot enumerate candidates - together they give heavy-hitter detection in sublinear space.
| Structure | Answers | Memory | Role here |
|---|---|---|---|
| Exact hash map | exact count, full enumeration | O(distinct keys) ~20 GB | rejected - scales with the singleton tail |
| Count-Min Sketch | estimate for a named key | O(w*d) ~1 MB | the frequency oracle, per time bucket |
| Lossy Counting / Space-Saving | the set of heavy candidates | O(1/eps) ~0.4 MB | the candidate enumerator |
| CMS + LC together | which keys, and how hot | sublinear | the counting substrate |
3. Sliding the window: one sketch -> a ring of time-bucketed sketches
“Trending” is over a recent window. A single cumulative CMS counts since the dawn of time and never forgets, so an evergreen tag dominates forever. We must expire old counts.
Approach A: One CMS and “just subtract old events” (naive)
Keep one lifetime sketch and try to remove events as they age out of the window.
Where it breaks: you cannot subtract from a CMS without the raw events, and we deliberately do not store them. Even if you kept them, a conservative CMS does not support reliable decrement (the min-estimate semantics break under subtraction - you can drive counters negative via collisions and corrupt estimates for unrelated keys). A single cumulative sketch has no notion of “recent.” It answers “ever,” which is the wrong question.
Approach B: A ring of sketches, one per time bucket (the sliding window)
Keep one CMS per time bucket (say one per minute) in a circular buffer sized to the window. The window estimate for a key is the sum of its estimates across the live buckets. Expiry is dropping the oldest bucket - no subtraction, no raw events.
Ring of B sketches (B = window_minutes), one CMS per minute, per (geo,lang):
[ CMS_t-59 ][ CMS_t-58 ] ... [ CMS_t-1 ][ CMS_t (current) ]
INCREMENT(key, ts): fold into the sketch for ts's minute bucket.
WINDOW_ESTIMATE(key, W minutes):
sum over the last W buckets of CMS_bucket.ESTIMATE(key)
ADVANCE (every minute):
head = (head + 1) % B
ZERO the sketch now at head # the bucket 60 min old is reused -> expired
# the window slides for FREE: an old bucket is simply no longer summed.
- Expiry by rotation. Advancing the ring head and zeroing the reclaimed sketch is the entire expiry mechanism. The bucket that is now 60 minutes old is overwritten and stops being summed. No delete job, no scan, no stored events.
- Arbitrary sub-windows for free. Because buckets are per-minute, we can compute a 5-minute
f_nowand a 60-minutef_basefrom the same ring just by summing different numbers of buckets. This is exactly what the rising score needs (below). - Error adds across buckets but stays bounded. Summing W sketch estimates sums their error terms, but each is
eps * N_bucketand the sum iseps * N_window- the same relative bound as a single window-wide sketch. Accuracy holds. - Memory is B sketches, ~60 MB per board. Bounded, independent of key count, and the candidate set (Lossy Counting) runs over the window too so it only monitors keys hot recently.
The candidate set also needs windowing: run Lossy Counting over a sliding window (or keep a per-bucket candidate list and union the live buckets) so a key that was hot yesterday but silent now ages out of the candidate set and stops being scored.
4. Scoring “rising” and merging across shards: volume -> acceleration -> distributed top-K
We can now estimate any candidate’s frequency over any recent sub-window, per shard. Two things remain: define rising correctly, and get a correct global top-K from M shards.
Approach A: Rank by window count (naive - this is “popular,” not “trending”)
Take each candidate’s 60-minute estimate, sort, top K.
Where it breaks: this is the evergreen problem. #love, #followback, and the platform’s own branded tags have enormous steady volume and would permanently occupy the board. The breakout event - a tag going from 40/min to 40,000/min - has lower absolute volume than #love for a while and never surfaces. Raw volume measures popularity, and the product is change.
Approach B: Rank by the ratio of recent rate to baseline rate
Compute a short-window rate f_now (last 5 min) and a long-window baseline f_base (trailing 60 min), score by f_now / f_base.
This is the right idea - trending is acceleration - but the naive ratio has two failures. It explodes for tiny keys (a tag going from 2 to 20 is “10x” but trends nothing), and it is noisy minute to minute. We need to reward genuine breakouts while damping small-count nonsense and jitter.
Approach C: Normalized rate-ratio with a floor, over sketch sub-windows
Use the sketch ring to get a recent per-minute rate and a baseline per-minute rate, and score by how far the recent rate exceeds the baseline, normalized so tiny keys cannot blow up.
For each candidate key, from the sketch ring:
f_recent = WINDOW_ESTIMATE(key, 5 min) / 5 # mentions/min, now
f_base = WINDOW_ESTIMATE(key, 60 min) / 60 # mentions/min, baseline
rising_score = (f_recent - f_base) / sqrt(f_base + C)
- (f_recent - f_base): absolute acceleration. A brand-new tag has
f_base ~ 0, so its whole recent rate counts as acceleration -
exactly what we want to surface.
- divide by sqrt(f_base + C): normalize so a giant evergreen tag needs
a HUGE absolute jump to score, while small tags do not explode.
C is a floor constant (a minimum baseline) that kills tiny-count noise:
a tag going 2 -> 20/min has a trivial numerator against sqrt(C).
- optionally weight by sqrt(f_recent) so a breakout with real volume
outranks a proportionally-similar micro-spike.
The score is intentionally not a count. A tag with a lower absolute volume but a steeper climb outranks a bigger, flatter one - because the board ranks momentum. We expose the estimated recent count alongside for display context, not for ranking. (This is the same shape of decayed-velocity idea used for other trending boards; here it rides on top of sketch estimates rather than exact counters, because the key space forbids exact counts.)
An EWMA variant works too: keep a fast and a slow exponentially-decayed rate per candidate and score their gap. The ring-of-sketches sub-window form is easier to reason about with sketches (you already have the buckets), so I default to it, and note the EWMA as the lower-state alternative if the candidate set is large.
The distributed merge: over-fetch per shard, estimate on whole counts
One node cannot ingest 250K events/sec and hold every board’s sketch ring, so we shard by hash(key) across M nodes. Each shard owns a disjoint set of keys and holds their sketch rings and candidate set. Getting a correct global top-K from M shards has the classic trap:
Naive: ask each shard for its local top-K, union, re-rank. Wrong: a key that is globally #40 might be only #80 on its own shard (that shard happens to hold several hotter keys) and never appears in that shard’s local top-K, so it is silently dropped. Taking exactly top-K per shard loses global winners that rank below K locally.
Fix - over-fetch top-m and estimate on whole counts:
Because we shard by hash(key), a key lives ENTIRELY on one shard, so its
shard-local sketch estimate IS its global estimate - no cross-shard summing.
Aggregator (per geo/lang, every ~5-10s; on-read for cold boards):
candidates = {}
for shard in shards:
# each shard returns its Lossy-Counting candidates (top-m, m >> K),
# each with its f_recent and f_base from that shard's sketch ring:
for (key, f_recent, f_base) in shard.candidates(geo, lang, m):
candidates[key] = score(f_recent, f_base) # local = global estimate
board = topK(candidates by score)
cache.set(key(geo, lang, window), board, ttl=~10s)
- Over-fetch
m >> K(say m=1000 for K=50). A key globally in the top 50 easily makes its own shard’s top 1000, so nothing is dropped. Each shard runs Lossy Counting independently, so m candidates is cheap. - Estimates stay whole.
hash(key)sharding means a key’s entire stream hits one shard; its sketch estimate is complete, with no partial counts summed across shards and no compounded error. Contrast with sharding bygeo(one hot geo overloads a node) or round-robin (a key’s counts fragment across all shards, forcing error-compounding partial sums).
The residual approximation is the CMS over-count, the Lossy-Counting support cutoff, and the top-m truncation - all bounded, and all invisible for the heavy risers that actually trend. We serve a trending list, not an audited ledger, which is exactly the product.
API Design & Data Schema
Ingestion API (the write plane)
POST /v1/events
{
"key": "#worldcup", # hashtag or normalized query string
"type": "hashtag", # hashtag | query
"geo": "in", # ISO country / region
"lang": "hi",
"ts": 1795267200 # server stamps if absent
}
202 Accepted -> counted asynchronously (~5s), fire-and-forget
Notes:
- Server-side normalization: lowercase, strip punctuation, collapse
whitespace, canonicalize the hashtag/query BEFORE hashing to a shard,
so "#WorldCup" and "#worldcup" are one key.
- Batched ingest: POST /v1/events:batch with an array, to amortize
request overhead from high-volume producers.
- No durable write blocks the ack; the replay log is teed async.
Serving / read API (the data plane)
GET /v1/trending?geo=in&lang=hi&window=now&k=50
geo string region, or "global"
lang string language, or "all"
window enum now (5m rising) | hour (60m) ; default now
k int capped at ~50
200 OK (served from the board cache, identical for all callers)
{
"geo": "in", "lang": "hi", "generated_at": 1795267205,
"trending": [
{ "rank": 1, "key": "#worldcup", "score": 918.4,
"est_recent": 41200, "est_baseline": 380, "approx": true },
{ "rank": 2, "key": "election results", "score": 744.1,
"est_recent": 20100, "est_baseline": 260, "approx": true }
]
}
- "score" is the normalized rising score (acceleration), the ranking key.
- "est_recent"/"est_baseline" are CMS estimates shown for context only;
"approx": true makes the inexactness explicit to consumers.
Data model: RAM sketches, a bounded candidate table, a replay log
The counting lives in RAM - the access pattern is “increment 250K/sec and read aggregated estimates,” which no disk store serves at this latency - and is deliberately approximate and rebuildable, not a store of record. The only durable thing is a cheap replay log, kept just long enough to rebuild a shard.
In-memory per Count Shard (approximate, derived, per owned key range):
Per (geo, lang) board this shard participates in:
sketch_ring: CMS[B] # B per-minute Count-Min Sketches
# each CMS = uint32[d][w], d=7, w=32768 (~1MB)
ring_head: int # current bucket index, advanced each minute
candidates: LossyCounting # bounded ~10K (key -> f, delta), windowed
# holds the actual candidate STRINGS
Sizing: ~B(60) sketches * ~1 MB = ~60 MB per board, + ~0.4 MB candidates.
Boards are sharded by hash(key); a shard holds the key-range slice of
many boards. A few GB RAM per shard with M ~ 16-32 shards.
Board cache (one answer per board, served to everyone):
key: trend:{geo}:{lang}:{window} e.g. trend:in:hi:now
value: serialized top-K rising list
TTL: ~10s for eager hot boards (overwritten each cycle),
~30-60s for lazily-materialized cold boards.
Store: Redis cluster / CDN edge. Reads collapse to one entry per board.
Durable replay log (off hot path, rebuild only):
event (append-only, Kafka -> object store)
key TEXT
type TEXT
geo TEXT
lang TEXT
ts TIMESTAMP
-- partitioned by minute; ~300 GB/day; NEVER read by the serving path.
-- retained ~2x the max window (e.g. 2 hours), then dropped.
-- used ONLY to rebuild a shard's sketch ring + candidate set after a
-- crash by replaying the trailing window. No long-term retention.
SQL vs NoSQL: there is no relational hot path and, unusually, no durable primary store for the counts at all - the sketches are the data structure, and they are RAM-resident and disposable. The serving tier is a KV cache (Redis/CDN): point-key reads of a precomputed list, no joins, no scans. The replay log is append-only columnar files in object storage, read only by a rebuilding shard. A relational database fits nothing here: there is no entity to join, no transaction, and the dominant operation (fold 250K events/sec into probabilistic counters, read aggregated estimates in microseconds) is exactly what a B-tree or a document store is bad at. The schema is the sketch dimensions. That is the honest answer to “SQL or NoSQL”: neither - a probabilistic in-RAM structure, with a KV cache in front and a throwaway log behind.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Exact per-key counting blows memory (breaks before anything else). 300M distinct, singleton-dominated keys at ~70 bytes is ~20 GB per board, 90% of it noise.
Fix: Count-Min Sketch - memory O(w*d) (~1 MB) independent of key count; estimates any named key’s frequency with a bounded additive error, over-counting (never hiding a heavy hitter) and only fuzzing the rare keys we ignore.
2. The sketch cannot enumerate heavy keys. CMS answers a named key; it does not list the hot ones, and keeping every key to query reintroduces the 20 GB map.
Fix: Lossy Counting / Space-Saving - a bounded monitored set (~10K entries, 1/eps) that holds only recurring candidate strings and drops singletons at each bucket boundary. LC picks which keys, CMS says how hot.
3. Ranking by volume surfaces evergreens, not breakouts (correctness bug). #love pins the board; the real spike never appears.
Fix: normalized rising score (f_recent - f_base)/sqrt(f_base + C) over sketch sub-windows - ranks acceleration, with a floor that kills tiny-count ratios and damps jitter. New tags (baseline ~0) surface on their full recent rate.
4. A single cumulative sketch never forgets. It answers “ever,” not “recently,” and CMS cannot be decremented safely. Fix: a ring of per-minute sketches; the window estimate sums the live buckets, and expiry is advancing the ring head and zeroing the reclaimed sketch. The window slides for free with no stored events and no subtraction.
5. Ingest throughput at breaking-news bursts (~250K/sec). Synchronous, durable-per-event counting blows the ack budget.
Fix: fire-and-forget ingest (ack after enqueue) plus Kafka as a shock absorber - a burst drains at consumer rate, trading a few seconds of freshness for never blocking. Sharding spreads the fold across M nodes; each fold is d increments, no allocation.
6. Distributed merge drops winners. Exact top-K per shard misses a globally-hot-but-locally-#K+1 key.
Fix: over-fetch top-m per shard (m » K), union, re-rank. hash(key) sharding keeps each key’s sketch estimate whole on one node, so the merge is a plain union-and-sort with no partial-count summing.
7. Hot key / hot partition. A viral tag is a huge fraction of all events, hammering one Kafka partition and one shard.
Fix: the per-event work is a cheap d-cell increment, so one hot key is tolerable. If a single tag truly saturates a partition, split its counting with a random suffix (hash(key + rand[0..s)) into s sub-sketches, summed at read) and reconcile at the aggregator - a trivial merge since estimates add.
8. Hot geo/lang skew. A giant locale dwarfs small ones; sharding by geo would overload one node. Fix: shard by key, not geo, so load spreads across all shards; the aggregator groups by geo/lang at merge time from evenly-loaded shards. Each shard holds the key-range slice of every board.
9. Sketch accuracy degrades as the stream total N grows. CMS error is eps * N; a huge window inflates the absolute error for mid-tier keys.
Fix: keep the window bounded (the ring caps N per window), size eps for the required separation between rank K and rank K+1, and, if a geo’s N is enormous, use a wider sketch (larger w) for that board only - memory is cheap per board, so spend width where the stream is hot.
10. Shard loss drops in-flight sketches. The sketch ring is RAM-resident; a crash loses recent counts. Fix: the durable replay log lets a restarting shard replay the trailing window (minutes, not history) to rebuild its sketch ring and candidate set; during the gap, reads degrade to slightly stale from cache. We accept losing a few seconds of un-replayed counts because the board is an approximate aggregate.
11. Aggregator and cache as single points of failure. One aggregator refreshing the cache, or one cache node, is a SPOF. Fix: run multiple stateless aggregators (each pulls shard candidates and refreshes independently - they compute the same list, last writer wins) and a replicated cache (Redis cluster / CDN). Count shards run replicas fed by the same Kafka partitions (or rebuilt from the replay log) for HA.
12. Clock skew across nodes. Bucketing by wall clock across machines misplaces events near minute boundaries.
Fix: bucket by the event ts stamped at ingest (one clock domain per ingest node, NTP-synced), with a small grace overlap so a slightly-late event folds into the correct minute sketch. Sub-second skew is invisible against minute buckets and 5-60 minute windows.
Wrap-Up
The trade-offs that define this design:
- Approximate counting over exact, by necessity. The key space is unbounded and singleton-dominated, so we refuse to pay per distinct key. Count-Min Sketch estimates any key’s frequency in ~1 MB regardless of key count, over-counting (never hiding a heavy hitter) and only fuzzing the rare keys we ignore. Memory is bounded by accuracy, not by how many hashtags the internet invents.
- Two structures, split by role. Lossy Counting / Space-Saving keeps a bounded set of candidate strings (which keys to watch, singletons pruned); Count-Min Sketch gives each candidate’s windowed count (how hot). Neither alone is heavy-hitter detection; together they are, in sublinear space.
- The window slides by rotating a ring of sketches. One sketch per minute; the window estimate sums the live buckets; expiry is advancing the head and zeroing the reclaimed sketch - no stored events, no CMS subtraction, and free sub-windows for the rising score.
- Rising is acceleration, not volume. The board ranks
(f_recent - f_base)/sqrt(f_base + C), so a steep breakout beats a flat evergreen, with a floor that kills tiny-count ratios. Volume would pin#loveat the top forever. - Shard by key, over-fetch at merge.
hash(key)keeps each sketch estimate whole on one node and spreads hot geos across shards; over-fetching top-m per shard keeps a globally-hot-but-locally-#K+1 key from being dropped. Ingest is fire-and-forget; the sketches are disposable and rebuilt from a short replay log.
One-line summary: a key-sharded firehose folded into a ring of per-minute Count-Min Sketches with a Lossy-Counting candidate set per geo/lang board - approximating heavy-hitter frequencies in sublinear memory, sliding the window by rotating sketches, and ranking by normalized acceleration rather than volume - so the trending list surfaces rapidly rising hashtags and queries from billions of daily events within seconds, without ever storing a raw event or a counter per key.
Comments