Skip to content

Top-K & Heavy Hitters ​

"We introduce a new sublinear space data structure—the Count-Min Sketch— for summarizing data streams." — Graham Cormode and S. Muthukrishnan, An Improved Data Stream Summary: The Count-Min Sketch and its Applications (Journal of Algorithms, 2005)

Summary: The most frequent items of a stream (trending hashtags, best-selling products, hot cache keys, the IP addresses behind a DDoS) can be counted exactly with a hash map and a heap while the number of distinct keys fits in memory, and approximately in a few kilobytes with Misra-Gries, Space-Saving, a Count-Min Sketch plus a heap, or HeavyKeeper when it does not; time windows, decay and a merge step across shards turn the counter into a real system. Focus: exact counting (hash map, min-heap, Redis sorted sets with ZINCRBY, ZUNIONSTORE, ZREVRANGE), the approximate family and its error bounds (epsilon, delta, width, depth, N/m), Redis Stack TOPK.* and CMS.*, windows and decay (tumbling, sliding, exponential), distributed top-k with local top-k and k-prime, hot key detection, freshness versus accuracy, and the serving path. Learning goal: Given a stream rate, a key cardinality and a freshness target, choose between exact and approximate counting, size the structure from its error formula, window and merge it across shards without lying about the answer, and serve the leaderboard from a cache.

This chapter sits in the Distributed Systems Primitives group, after Geospatial Indexing and before Strangler Fig. It owns the system-level decision: which structure, how big, how fresh, how merged. Mechanics live with the owners: the Bloom filter and the HyperLogLog internals are in Bloom Filters & Probabilistic Structures, Redis data types in Redis, window semantics and watermarks in Stream Processing, batch versus stream layers in Big Data Architectures, the consistent-hash ring in Consistent Hashing. Related system-level chapters: Caching (hot keys, serving the leaderboard), Sharding at System Level (hot partitions), Write Buffering & Sharded Counters (the write path that feeds the counters), Rate Limiting and DDoS Protection (acting on heavy hitters), and the worked example in Case Study: YouTube.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why a plain GROUP BY stops workingWhy it exists
Papers and sourcesWhere it comes from
Hash map plus heapExact counting
ZINCRBY, ZUNIONSTORE, ZREVRANGERedis sorted sets
Misra-Gries, Space-Saving, Lossy CountingCounter-based algorithms, Space-Saving, Lossy Counting
Count-Min Sketch, Count SketchCount-Min Sketch, Count Sketch
HeavyKeeper and TOPK.ADDHeavyKeeper and Redis TopK
Bloom filter, HyperLogLog, PFADDNeighbours: membership and distinct counts
Sliding window, tumbling window, decayTime: windows and decay
Local top-k, k-prime, merge, Kafka Streams, FlinkDistributed top-k
Hot keys in caches and shardsHot key detection
Freshness, cache, storing results per windowServing and freshness
Knobs, sizing, Redis defaultsMechanics
CodeGo, Laravel
Trending, top products, DDoS, YouTube top 10Solving the classic problems
Which structure for which workloadChoosing
Monolith to distributed systemIn architecture
Numbers and experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The approaches. All of them answer "which items are the most frequent" (top-k, heavy hitters, frequent items); they differ in what they remember.

ApproachWhat it remembersMemoryAnswerTypical home
Exact: hash map + min-heapOne counter per distinct keyO(distinct keys)ExactA process with a bounded key set, a batch job
Exact: Redis sorted setOne score per distinct memberO(distinct members)ExactLeaderboards, trending with ZINCRBY
Misra-Gries (Frequent)k-1 countersO(k)Every key above N/k is kept; counts are underestimatesSmall streams, teaching, the base of many sketches
Space-Saving + stream summarym counters in sorted bucketsO(m)Counts never under, error known per keyTop-k with guarantees in one process
Lossy CountingEntries with (count, max error) in bucketsO((1/epsilon) log(epsilon N))Frequencies off by at most epsilon NFrequent itemsets, network monitoring
Count-Min Sketch + heapA d x w grid of counters and k candidatesO(w d + k)Never under, over by at most epsilon N with probability 1-deltaMergeable counting across shards
Count Sketch + heapSame grid with signed updatesO(w d + k)Unbiased, error scales with the L2 normSkewed streams where the L1 bound is loose
HeavyKeeper(fingerprint, count) buckets with decayO(w d + k)Elephant flows kept, mice decayed awayRedis TOPK.*, network flows

The window and the merge. The counter is the easy half.

QuestionAnswer in one lineSection
"Top 10 in the last hour"One counter set per minute, union the last 60Time
"Recent counts matter more"Weight old buckets by 0.5^(age/half-life)Time
"Many shards"Each sends local top-k', the merger sums per keyDistributed
"Is the merged answer right?"Only if each key lives on one shard, or k' is large enough, or the bounds say soDistributed
"Do I read it per request?"No: compute every few seconds, cache, store per windowServing

Numbers to keep in your head. Cited, or marked as an estimate.

FactValueSource
Count-Min sizingwidth w = ceil(e / epsilon), depth d = ceil(ln(1 / delta))Cormode and Muthukrishnan 2005
Count-Min guaranteeestimate is never below the true count, and at most epsilon N above it with probability at least 1-deltasame paper, Theorem 1
Redis CMS.INITBYPROBtakes an error and a probability; counters are 4 bytes by default (CELL_SIZE 1, 2, 4 or 8)Redis docs
Redis TOPK.RESERVEwidth 8, depth 7, decay 0.9 are the listed defaults; the overview suggests width = k log k, depth = log k with a minimum of 5Redis docs
HyperLogLog in Redisup to 12 KB, standard error 0.81%Redis docs
ZUNIONSTORE costO(N) + O(M log M), N total input size, M result sizeRedis docs
ZINCRBY costO(log N)Redis docs
Space-Saving guaranteeany key with frequency above N/m is monitoredMetwally et al. 2005
Measured here (one run, Go, 2 million Zipf events, 180,304 distinct keys, k = 10)exact map about 11 MB (estimate); Count-Min 212 KB; Space-Saving 1000 counters about 62 KB (estimate); HeavyKeeper 46 KB; all four found all tenLab
eventsview, click,requestworker 1sketch + heapkeys hash to 1worker 2sketch + heaplocal top k'worker 3sketch + heapevery few secondsmergesum per key,global top kresult storeone row set perwindow (hour, day)cacheTTL 10-30 shistorySQL snapshotsfreshness = flush interval + merge interval + cache TTL; accuracy = sketch size and k'

The picture is the whole chapter: events are partitioned by key to workers that keep a small structure, every few seconds each worker publishes its local top k', a merger sums per key, the result is stored per window and a cache serves it. The line under the picture is the contract: freshness is the sum of the flush interval, the merge interval and the cache TTL; accuracy is the structure size and k'.

Why it exists ​

The first answer is always SELECT item, count(*) ... GROUP BY item ORDER BY 2 DESC LIMIT 10. It is exact, and it works until it does not: the query reads every row of the window (millions per hour for a busy site), the result is stale the moment it returns, and running it per request multiplies the cost by the traffic. The next answer is a hash map in memory, which is exact and fast until the number of distinct keys (every hashtag ever typed, every URL with a query string, every source IP in a flood) outgrows the machine, or the stream is spread over many machines that each see part of it.

The key observation of the stream-summary literature is that you almost never need the count of every key. You need the few keys that are large, and large keys are the ones that are hard to hide: in a stream of N events, at most k keys can each have more than N/k occurrences. A structure that spends its memory only on candidates for those few keys, and tolerates being wrong about the long tail, answers the question in kilobytes.

Exact countingApproximate counting
Memory grows with distinct keysMemory fixed by the error you choose
Merging shards is trivial for key-partitioned data, exact for all data if you ship everythingMerging is cheap and lossless for Count-Min, bounded for counter-based summaries
Answer is the truthAnswer carries an error bound, sometimes a per-key interval
Fails with high cardinalityFails when the error budget is smaller than the gap you need to see
Easy to explain and auditNeeds the bound written next to the number

The everyday picture. A bouncer at a club door who has a notebook with only ten lines. Each arriving guest is either already in the notebook (add a tick) or new. When the notebook is full and a stranger arrives, the bouncer crosses out the guest with the fewest ticks and gives the stranger that guest's tick count plus one. Regulars end up with the most ticks and never get crossed out; one-off visitors churn through the bottom line. That is Space-Saving, and the "plus the inherited count" is exactly where its error comes from.

Three common misunderstandings, up front ​

  1. "Approximate means unreliable." Count-Min never undercounts and its overcount is bounded with a stated probability; Space-Saving never undercounts and reports the maximum error per key. Approximate with a written bound is more honest than exact on a window that is already stale.
  2. "Top-k of the whole is the union of the top-k of the parts." It is not. A key that is second on every shard can be first globally and absent from every shard's top-1. That is why shards report k' larger than k and why the merge carries bounds (Distributed top-k).
  3. "Trending is just the biggest counts." A count over all time is a hall of fame. Trending is a rate of change over a window, so time (buckets, decay) is half of the design (Time).

Where it comes from ​

YearWorkWhat it gave the fieldRead
1982Misra and Gries, Finding Repeated ElementsThe "Frequent" algorithm: k-1 counters find every item above N/k in one passScanned paper, algorithm described by the later papers below
2002Manku and Motwani, Approximate Frequency Counts over Data Streams (VLDB)Sticky Sampling (probabilistic) and Lossy Counting (deterministic) with user-chosen support and errorRead
2005Cormode and Muthukrishnan, An Improved Data Stream Summary: The Count-Min Sketch and its Applications (J. Algorithms 55)The Count-Min Sketch, point/range/inner-product queries, heavy hitters from a sketch plus a heapRead (Wayback copy of the author's PDF)
2005Metwally, Agrawal and El Abbadi, Efficient Computation of Frequent and Top-k Elements in Data Streams (ICDT)Space-Saving and the Stream-Summary structure, guarantees per keyRead
2018Gong et al., HeavyKeeper: An Accurate Algorithm for Finding Top-k Elephant Flows (USENIX ATC)Count-with-exponential-decay, the basis of Redis TOPK.*Read

The abstract of the Space-Saving paper states the aim in one sentence: "We propose an approximate integrated approach for solving both problems of finding the most popular k elements, and finding frequent elements in a data stream coming from a large domain." The HeavyKeeper abstract names its strategy: "count-with-exponential-decay ... by actively removing small flows through decaying, while minimizing the impact on large flows". Redis documents that its Top-K "is based on the HeavyKeepers algorithm presented by Junzhi Gong et al." and that it uses "a hash table that holds the probabilistic counts (much like the Count-Min Sketch), and a min heap that holds the K items with the highest counts".

A note on reading: the Misra-Gries paper is a scan without a text layer, so this page describes the algorithm as the Manku-Motwani and Metwally papers present it. The Kafka Streams documentation page is rendered by JavaScript and could not be saved as text; statements about its windowed aggregation API are marked where they rest on general knowledge.

The concept catalogue ​

Every block has the same parts: in plain words, a misunderstanding, a definition, a timeline, real scenarios, the products involved, and where the code is.

Exact counting: hash map and min-heap Must-know ​

In plain words: Keep a counter per key in a hash map; to get the top k, walk the map once and keep a heap of the k largest.

Common misunderstanding: "Sort the map and take the first k." Sorting is O(n log n) over all keys; a size-k min-heap is O(n log k) and never holds more than k entries. For k = 10 over a million keys that is the difference between sorting a million items and doing about 3.3 comparisons per key.

Definition: a hash map from key to count (O(1) update), and a bounded min-heap whose root is the smallest of the current top k. A key replaces the root only if it beats it. Memory is O(distinct keys); that is the only cost, and it is the reason the rest of this chapter exists.

event stream            hash map                 min-heap (k = 2), root = smallest
1  a                    a=1                      -
2  b                    a=1 b=1                  -
3  a                    a=2 b=1                  -
4  c                    a=2 b=1 c=1              scan at query time
5  a                    a=3 b=1 c=1
6  b                    a=3 b=2 c=1
query top-2 -> walk map: offer a=3 -> [a]; offer b=2 -> [b a]; offer c=1 -> c < root(b=2), skip
result: a=3, b=2

Real scenario: top products of the day for a shop with 200,000 SKUs (a map of 200,000 entries is a few MB: fine); a nightly batch job over yesterday's log; a per-process view of "which route is hottest" inside one service. It is also the oracle you test every approximate structure against.

WhereExact structureLimit
One Go processmap[string]int64 + container/heapProcess memory, one machine
PostgreSQLGROUP BY + ORDER BY ... LIMIT kReads the whole window; index helps only if pre-aggregated
RedisSorted set, ZINCRBYMemory of one key; one node per key in Redis Cluster
Kafka Streams / FlinkKeyed state store per partitionState size, rebalance cost

Fix / how to use it: the Go package exact plus topheap (Go); the SQL fallback is in Serving and the schema file.

Redis sorted sets: ZINCRBY, ZUNIONSTORE, ZREVRANGE Must-know ​

In plain words: A Redis sorted set is a leaderboard that keeps itself sorted: add one to an item's score, and ask for the top ten.

Common misunderstanding: "A sorted set is a big structure, so it cannot be the exact top-k for a busy stream." It can be, as long as the number of distinct members is bounded, because ZINCRBY is O(log N) and a top-k read is O(log N + k). The real limit is memory per member and the single key living on one node.

Definition: ZINCRBY key increment member adds to the score (creating the member), ZRANGE key 0 k-1 REV WITHSCORES returns the k largest (the older ZREVRANGE does the same and is marked deprecated since Redis 6.2 in the command reference), ZRANGE key min max BYSCORE returns members in a score range (for example everything above a heavy-hitter threshold), ZREMRANGEBYRANK key 0 -(k+1) trims to the k largest, and ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS ...] [AGGREGATE SUM|MIN|MAX] merges sets with optional weights.

1  ZINCRBY trending:1700000040 "#go" 1            -> "1"
2  ZINCRBY trending:1700000040 "#redis" 1         -> "1"
3  ZINCRBY trending:1700000040 "#go" 1            -> "2"
4  ZINCRBY trending:1700000100 "#go" 1            -> "1"      (next minute, new key)
5  ZUNIONSTORE tmp 2 trending:1700000040 trending:1700000100
                                                  -> 2        (members in the union)
6  ZRANGE tmp 0 1 REV WITHSCORES                  -> "#go" "3" "#redis" "1"
7  DEL tmp

Real scenario: "most viewed articles in the last 15 minutes" for a news site, the live leaderboard of a game, trending tags with per-minute buckets and a weighted union for decay (Time).

ProductSorted-set top-kNote
Redis (open source)ZINCRBY, ZRANGE ... REV, ZUNIONSTORESingle-threaded command execution; a large ZUNIONSTORE blocks other clients
Redis ClusterThe union needs all input keys in one slotUse a hash tag such as {trending}:1700000040 so bucket keys share a slot
Valkey, KeyDB, DragonflySame commandsBehaviour as the Redis reference; check the vendor docs for limits
Amazon ElastiCache / MemoryDBSame commandsA managed Redis; the single-slot rule still applies in cluster mode

Fix / how to use it: trending.Store in Go and TrendingService in Laravel, both below.

Misra-Gries (the Frequent algorithm) Important ​

In plain words: Hold at most k-1 counters. When a new key arrives and there is no free counter, subtract one from every counter instead: the newcomer cancels out against k-1 others.

Common misunderstanding: "It returns the top k." It returns a set of candidates that contains every key with more than N/k occurrences, and counts that are too low by at most N/k. It can also contain keys that are not heavy, so a second pass (or a bound check) is needed if you must be sure.

Definition: with k-1 counters, every key whose true frequency exceeds N/k is guaranteed to be present at the end; each reported count underestimates by at most N/k. The "subtract from all" step happens at most N/k times, which is where the bound comes from.

k = 3 (2 counters), stream: a a b c a b b a
1  a   {a:1}
2  a   {a:2}
3  b   {a:2, b:1}
4  c   no room -> decrement all: {a:1}         (b reached 0, dropped; c is cancelled)
5  a   {a:2}
6  b   {a:2, b:1}
7  b   {a:2, b:2}
8  a   {a:3, b:2}
true counts: a=4, b=3, c=1;  estimates: a=3, b=2 (each low by at most N/k = 8/3)

Real scenario: an embedded or per-connection monitor that must hold a few dozen counters; the "find a majority element" interview problem (k = 2); the building block under merge-friendly summaries (two Misra-Gries summaries can be added and re-trimmed).

PropertyValue
Memoryk-1 counters
UpdateO(1) amortised with a hash map and lazy decrement tricks, O(k) for the plain decrement-all
ErrorUnderestimate by at most N/k
GuaranteeEvery key above N/k is in the output

Fix / how to use it: Go package misragries.

Space-Saving and the stream summary Must-know ​

In plain words: Like Misra-Gries, but when a newcomer arrives you take over the smallest counter and keep its number, instead of subtracting from everyone.

Common misunderstanding: "The counts of monitored keys are exact." They are upper bounds. Every monitored key also carries an error: the count of the counter it replaced. The truth lies between count minus error and count.

Definition: Metwally, Agrawal and El Abbadi monitor m keys. If the key is monitored, increment it. Otherwise replace the key with the smallest count min, set the new key's error to min, and set its count to min + 1, "since we designed the algorithm to err only on the overestimation side". The Stream-Summary structure keeps counters in buckets of equal count, in a sorted doubly linked list, so an increment moves one element to the next bucket in O(1) and the minimum is always the head. Any key with frequency above N/m is guaranteed to be monitored; for Zipfian data the paper shows the top-k can be reported in the right order with much less space.

head: minimum bucketcount = 3tag-m (err 0)tag-n (err 2)bucketcount = 7tag-q (err 0)bucketcount = 12tag-b (err 1)tail: largestcount = 40tag-a (err 0)m counters in total, buckets sorted by count; top-k = read from the tailhit on a monitored key: unlink, move to bucket count+1 (O(1))new key, summary full: take any element of the head bucket, overwrite its key, err = old count, count + 1true count is in [count - err, count]; any key above N/m is always monitored
m = 2, stream: X X Y Z
1  X   {X:1 err0}
2  X   {X:2 err0}
3  Y   {X:2 err0, Y:1 err0}
4  Z   not monitored, full: min is Y (1). Replace Y by Z, err = 1, count = 2
       {X:2 err0, Z:2 err1}            true count of Z is 1, bound says [1, 2]

Real scenario: "top 20 search queries" in one aggregator process with a fixed 64 KB budget; ad impression top campaigns; the algorithm behind many "top-k with guarantees" libraries (the Stream-Summary buckets are why updates are O(1)).

PropertyValue
Memorym counters plus bucket list
UpdateO(1) with Stream-Summary
ErrorCount never below truth; per-key error is stored
MergePossible, but the combined error is the sum of both, so shards of unequal size need care
WeaknessIn the HeavyKeeper paper's network traces it scored far below sketches (precision 0.27 in its Table 1), so test it on your distribution

Fix / how to use it: Go package spacesaving (a full Stream-Summary with the paper's two-step example as a test).

Lossy Counting Good to know ​

In plain words: Cut the stream into buckets of width 1/epsilon. Count what you see; at the end of each bucket, drop the entries that cannot possibly be heavy.

Common misunderstanding: "Lossy" means it drops events at random. It drops entries, not events, and deterministically: an entry is removed only when its count plus its maximum possible error is below the current bucket number.

Definition: Manku and Motwani take a support s and an error epsilon. Each entry is (item, f, delta) where delta is the largest possible undercount when it was inserted (the current bucket id minus one). After each bucket boundary entries with f + delta at most the current bucket id are deleted. The output for support s contains all items with true frequency at least sN and no item below (s - epsilon)N; frequencies are underestimated by at most epsilon N. The paper reports it performs better in practice than the probabilistic Sticky Sampling even though its worst-case space bound is worse.

epsilon = 0.25, bucket width w = 4, stream: a b a c | a d a e | ...
1  bucket 1: a:1 b:1 a:2 c:1                  entries (item, f, delta=0)
2  boundary 1: drop f + delta <= 1 -> drop b, c;  keep a:2
3  bucket 2: a:3 (d,1,delta=1)  a:4  (e,1,delta=1)
4  boundary 2: drop f + delta <= 2 -> drop d, e;  keep a:4

Real scenario: frequent itemsets in market-basket data (the paper's second use), IP monitoring on an appliance that must bound memory without a probability.

PropertyValue
MemoryAt most about (1/epsilon) log(epsilon N) entries (the paper's bound)
ErrorUndercount by at most epsilon N
Compared with Space-SavingSpace bound is not fixed in advance, grows slowly with N

Fix / how to use it: no snippet; the shape is Misra-Gries with a per-entry delta.

Count-Min Sketch plus a heap Must-know ​

In plain words: A small grid of counters. To count an item, bump one counter in every row (each row picks its cell with its own hash). To read an item, take the smallest of its cells: the other items that collided only made the cells bigger.

Common misunderstanding: "A sketch stores the items, so I can list the top-k from it." It stores no keys. You must keep the candidate keys yourself, which is why a Count-Min top-k is always sketch plus heap: on every event, update the sketch, take the new estimate, and offer (key, estimate) to a size-k min-heap.

Definition: with parameters (epsilon, delta), set width w = ceil(e / epsilon) and depth d = ceil(ln(1/delta)); choose d hash functions from a pairwise-independent family. update(i, c) adds c to count[j][h_j(i)] for every row j; the point estimate is min_j count[j][h_j(i)]. Theorem 1 of the paper: the estimate never undercounts, and with probability at least 1-delta it is at most the true count plus epsilon times the L1 norm (the total count N). Two sketches with identical parameters and hash functions add cell by cell, so sketches from shards merge exactly.

item"video-42"d rows x w columns of countersh1h2h3h41712914estimate = min(17, 12, 9, 14) = 9: other items collided in the larger cellsw = ceil(e / epsilon), d = ceil(ln(1 / delta)); never undercountsmin-heap of koffer(item, estimate)smallest count at rootevict root if beaten
w = 8, d = 3; items: "a" x 5, "b" x 2, "c" x 1
1  add a (5 times): row1[3]+=5, row2[6]+=5, row3[1]+=5
2  add b (2 times): row1[3]+=2 (collides with a), row2[0]+=2, row3[4]+=2
3  add c (once):    row1[7]+=1, row2[6]+=1 (collides with a), row3[2]+=1
4  query b: min(row1[3]=7, row2[0]=2, row3[4]=2) = 2   correct, two rows were clean
5  query c: min(row1[7]=1, row2[6]=6, row3[2]=1) = 1   correct, the collision is outvoted
6  query a: min(7, 6, 5) = 5                           correct

Real scenario: counting every URL in a CDN log shard and merging per minute; frequency estimation of "has this key been seen more than 1,000 times" for hot-key detection; the sketch per hour or per day in Redis Stack (CMS.INITBYPROB, CMS.INCRBY, CMS.QUERY, CMS.MERGE).

ParameterEffectExample
epsilon (error)Width w = ceil(e / epsilon): halve epsilon, double the memoryepsilon 0.001 gives w = 2719
delta (failure probability)Depth d = ceil(ln(1/delta)): grows slowlydelta 0.01 gives d = 5
Memoryw x d x cell size2719 x 5 x 4 bytes = about 54 KB
Error scaleepsilon N: for N = 100 million, epsilon 0.001 is up to 100,000 extra counts on any keyItems below that are noise
Conservative updateRaise only the minimal cells; lower overestimate, keeps no-undercountNot mergeable by addition without loss of tightness

Fix / how to use it: Go package cms (sizing, conservative update, merge, Tracker), Redis Stack commands in Mechanics.

Count Sketch Good to know ​

In plain words: Count-Min's cousin that uses plus and minus signs so collisions cancel on average instead of always adding.

Common misunderstanding: "Count Sketch is just a better Count-Min." It is unbiased (it can underestimate), its error scales with the L2 norm rather than L1, and it needs a median instead of a minimum. On heavily skewed data that bound is tighter; on flat data Count-Min with conservative update is often simpler and never undercounts.

Definition: each row has a bucket hash h_j and a sign hash s_j in {-1, +1}. An update adds s_j(i) c to the bucket; the estimate is the median over rows of s_j(i) times the bucket. The HeavyKeeper paper groups both under the "count-all" strategy that records the size of every flow and keeps a heap of the leaders.

Real scenario: tensor sketching, heavy-hitter detection in networks where a few flows are enormous; a library that supports deletions (decrements) as well as increments.

Count-MinCount Sketch
EstimateMinimum of cellsMedian of signed cells
BiasOverestimate onlyUnbiased
Error scaleepsilon x L1epsilon x L2 (smaller on skewed data)
Supports negative updatesOnly with care (the guarantee needs non-negative values)Yes

HeavyKeeper and Redis TopK Important ​

In plain words: A sketch that forgets small things on purpose: when a different key lands in an occupied bucket, the resident's counter is shaved down with a probability that is high for small counters and tiny for big ones.

Common misunderstanding: "HeavyKeeper is a Count-Min with a heap." It differs in the part that matters: buckets hold a fingerprint and one counter, a collision decays the owner instead of adding to a shared cell, so mice destroy each other and elephants survive.

Definition: Gong et al. call it count-with-exponential-decay. Each of d arrays has w buckets holding (fingerprint, count). For an arriving flow: if the bucket is empty, take it with count 1; if the fingerprint matches, increment (with two optimisations that avoid fingerprint collisions inflating a mouse); otherwise decay the owner's count by one with probability b^(-C), and when it reaches zero, take the bucket over. A min-heap tracks the k largest. Redis exposes the decay as the decay argument of TOPK.RESERVE (default 0.9) and documents the implementation as "count-with-exponential-decay" that "is biased against mouse (small) flows and has a limited impact on elephant (large) flows".

base b = 1.08 (illustrative; the paper leaves b a parameter). Bucket holds (fp=A, C=40). A different key M arrives:
1  decay probability = 1.08^-40 = 0.046            -> almost always the elephant stays
2  Bucket holds (fp=B, C=2). M arrives:
3  decay probability = 1.08^-2  = 0.857            -> the mouse is shaved quickly
4  C reaches 0 -> bucket becomes (fp=M, C=1)

Real scenario: the Redis Stack TOPK.ADD / TOPK.LIST use case in the docs is "Trending hashtags (social media platforms, news distribution networks)"; DDoS source detection and elephant-flow detection in switches (the paper's domain).

PropertyValue
Memoryd x w buckets plus k heap entries; Redis says a fraction of what a sorted set needs
AccuracyPaper: precision 0.9999 and average relative error 0.0011 on its main test (Table 1) against 0.93 and 0.2951 for Count-Min plus heap, 0.27 for Space-Saving
Redis defaults (TOPK.RESERVE)width 8, depth 7, decay 0.9
TOPK.ADDReturns the items expelled from the top-k as it adds; complexity listed as O(n x k)
TOPK.LISTLists the k items; complexity O(k log k)
TOPK.QUERY, TOPK.COUNT, TOPK.INFOMembership, estimated counts, parameters
Not availableTime windows (you create one key per period yourself) and merging two TopK keys (the command set has no merge)

Fix / how to use it: Go package heavykeeper (a lite version with a test that elephants survive 20,000 distinct mice), redis-cli commands in Mechanics.

Neighbours: Bloom filter, HyperLogLog Good to know ​

In plain words: A Bloom filter answers "have I seen this key?" and HyperLogLog answers "how many different keys have I seen?" Neither tells you which key is the most frequent, but both sit next to a top-k.

Common misunderstanding: "A Bloom filter can count." A plain Bloom filter stores bits, so it cannot say how often. It is used in front of a top-k to filter out one-hit wonders: admit a key to the candidate set only on its second sighting.

Definition: a Bloom filter has false positives and no false negatives (Bloom Filters & Probabilistic Structures owns the sizing). HyperLogLog estimates distinct count: Redis PFADD key element ... adds, PFCOUNT key reads, PFMERGE unions, "up to 12 KB of memory and ... a standard error rate of 0.81%". The ratio top-key count to distinct count tells you how skewed the stream is, which decides how small a sketch can be.

event "u42" -> BF.EXISTS seen u42?   no  -> BF.ADD seen u42               (first sighting, ignore)
event "u42" -> BF.EXISTS seen u42?   yes -> CMS.INCRBY counts u42 1       (second sighting, count it)
every event -> PFADD distinct:2026-11-26 u42                              (how many users today)

Real scenario: unique viewers per video per day (PFADD) next to views per video (the counter); suppressing the long tail of single-hit URLs before they reach the candidate set.

StructureQuestionRedis Stack commandError
Bloom filterSeen before?BF.ADD, BF.EXISTSFalse positives only
HyperLogLogHow many distinct?PFADD, PFCOUNT, PFMERGEStandard error 0.81%
Count-MinHow often?CMS.INCRBY, CMS.QUERYOvercount up to epsilon N
Top-KWhich are most frequent?TOPK.ADD, TOPK.LISTMice may be missed

Time: tumbling windows, sliding windows, exponential decay Must-know ​

In plain words: "Top 10 right now" needs a definition of "now". Cut time into slices, keep one counter set per slice, and answer by combining the recent slices; older slices count for less or expire.

Common misunderstanding: "A sliding window means keeping every event of the last hour." You keep one small aggregate per slice (a minute), and slide by dropping the oldest slice and adding the newest; you never need the events again.

Definition: a tumbling window is a fixed-size, non-overlapping slice ("a tumbling window with a size of 5 minutes" is evaluated and restarted every five minutes, in the Apache Flink documentation). A sliding window is built from tumbling buckets: the answer at time t is the merge of the last n buckets, advancing one bucket at a time. Exponential decay weights bucket i by 0.5^(age/half-life), so an item's score fades unless it keeps being hit. Time buckets merge exactly for exact counters (sum) and for Count-Min sketches (cell-wise sum); for top-k lists they merge with the bounds of the next section.

minute -5expiredminute -4w = 0.25minute -3w = 0.35minute -2w = 0.5minute -1w = 0.71currentw = 1window: last 5 buckets (one sorted set each)writes: ZINCRBY trending:T item 1, then EXPIRE trending:T 7200ZUNIONSTOREWEIGHTS, SUMZREVRANGE0 k-1 WITHSCORESweights halve every 2 buckets (half life 2 minutes): recent activity outranks old, with no separate decay jobcost per query: O(N) + O(M log M) over the union, so cache the answer for seconds
half-life = 2 minutes, bucket = 1 minute; now = 10:05
1  10:05  bucket age 0  weight 1.00     "#goal"  200 hits   -> 200.0
2  10:04  bucket age 1  weight 0.71     "#goal"  180 hits   -> 127.3
3  10:03  bucket age 2  weight 0.50     "#goal"  100 hits   ->  50.0
4  10:02  bucket age 3  weight 0.35     "#vote"  900 hits   -> 318.2   (one huge bucket, now fading)
5  10:05  score(#goal) = 200.0 + 127.3 + 50.0 = 377.3  vs  score(#vote) = 318.2

Real scenario: "top 10 videos in the last hour" (60 one-minute buckets), "top 10 today" (24 one-hour buckets rolled up from minutes), "trending now" with a 30-minute half life, an hourly tumbling snapshot per hour stored for charts.

Window typeHow it is builtProduct
TumblingOne key per slice, ZINCRBY into the current oneRedis sorted set per minute; Flink TumblingEventTimeWindows; Kafka Streams TimeWindows
Sliding / hoppingUnion of the last n slices at query time, or a window operator that advances by a hopZUNIONSTORE over n keys; Flink SlidingEventTimeWindows
Exponential decayWeighted union, or decay counters on writeZUNIONSTORE ... WEIGHTS; HeavyKeeper decays by itself, but by collisions, not by time
Event time versus arrival timeLate events land in the bucket of their event time while it is still openFlink watermarks and Kafka Streams grace period, owned by Stream Processing

Fix / how to use it: Go trending.Store.Top (window and half-life arguments), Laravel TrendingService::top.

Distributed top-k: local top-k, k-prime, merge Must-know ​

In plain words: Each shard finds its own leaders; one place combines the reports. The catch is that a key which is only second on every shard may be first overall, so each shard must report more than k.

Common misunderstanding: "Merge the shards' top-k lists and re-sort." That is exact only if every key lives on exactly one shard (a key-partitioned stream), or if the lists are long enough. With data partitioned by anything else (round robin, arrival time, source IP), the global top-1 can be missing from every local top-1.

Definition: each shard sends its local top-k' (k' at least k). For every key the merger computes a lower bound (sum of reported counts) and an upper bound (lower bound plus, for each shard that did not report the key, that shard's smallest reported count, because the key could have been just below the cutoff). The top-k by lower bound is provably correct when its k-th lower bound is at least every other key's upper bound and at least the sum of the shards' tails (the threshold for a key nobody reported). This is the idea of the classic threshold algorithms, specialised to counts. A Count-Min sketch is simpler: sketches add cell by cell, so the merger can merge the full sketches and then re-query the union of the candidate keys.

3 shards, k = 1, partitioned by arrival time. Local lists (top-1):
shard 1: u1=10 (t=9 beyond the cutoff)     shard 2: u2=10 (t=9)     shard 3: u3=10 (t=9)
1  k' = 1 -> merger sees u1=10, u2=10, u3=10 -> reports u1; certain? no: tails sum to 30 > 10
2  k' = 2 -> every shard holds only u_i and t, so its list is complete (tail 0) -> merger sums t=27 -> reports t, certain: yes

Real scenario: a global top-10 videos computed from per-region counters; DDoS source detection from many edge nodes; Kafka Streams or Flink where the stream is keyed (so each key is on exactly one task) and a final single-partition step merges per-task top-k lists. Flink and Kafka Streams both give the windowed aggregation (count per key per window); the top-k over the aggregated table is an extra step you write yourself (a keyed state with a bounded priority queue, then a global reduce with parallelism 1). Late corrections: a Lambda-style design runs the exact batch count over the same window later and replaces the approximate result (Big Data Architectures).

PartitioningLocal top-k then merge isWhy
By key (hash of the item)Exact for the heads, with k' = kA key has all its events on one shard
By source, region or arrivalApproximate unless k' is large or bounds certify itA key's count is split
Sketch-based (Count-Min)Exact merge of the counters; candidates from union of local heapsCounters add; candidates must be gathered

Fix / how to use it: Go package merge (lower and upper bounds, certainty flag, three tests including the k' = 1 failure and the k' = 2 fix).

Hot key detection Important ​

In plain words: The most frequent keys in the request stream are the keys that overload one cache node or one shard; top-k on the access stream tells you who they are.

Common misunderstanding: "Hot keys are found by looking at the biggest values." The hot key is the most requested one, not the largest. A tiny feature-flag key read on every request can saturate a Redis node before any big key does.

Definition: run a heavy-hitter structure (Count-Min with a threshold, or Space-Saving) on the key access log of each cache client or proxy, a few seconds at a time; a key above a fraction of the node's request budget is hot. The reaction belongs to other chapters: replicate the key or add a local in-process copy (Caching), salt the key into n sub-keys (Write Buffering & Sharded Counters), or split the partition (Sharding at System Level).

client-side sampling, window = 10 s, node budget = 20,000 req/s
1  every GET key -> cms.Add(key)           (about 1 hash per row, no network)
2  every 10 s: for each candidate in heap with estimate > 5,000 -> mark hot
3  hot "flag:checkout" at 9,100 req/s -> add an in-process cache with TTL 1 s
4  reset the sketch for the next window

Real scenario: a celebrity's profile in a sharded store; one product during a flash sale; a single tenant sending 40% of API traffic. Redis itself offers redis-cli --hotkeys (requires an LFU eviction policy) and MONITOR for a sampled look; both are for diagnosis, not for production loops.

Where to measureCostSees
Inside the client libraryOne hash per request, no networkOnly this client's view; merge across clients
In the proxy (Envoy, NGINX, twemproxy-style)Per-proxy sketchAll traffic through that proxy
From the server (MONITOR, access logs)Heavy, can slow the serverEverything, but sample it

Freshness versus accuracy, and the serving path Important ​

In plain words: A leaderboard that is exactly right but one minute old, or fresh but off by a few ranks: choose the pair you can afford, then store the answer instead of recomputing it.

Common misunderstanding: "The top-k should be computed when the user asks." Computing it per request multiplies cost by traffic and by window size. The answer changes slowly; compute it on a schedule, store it keyed by window, and serve it from a cache.

Definition: freshness is how old the served answer can be (flush interval plus merge interval plus cache TTL). Accuracy is the error bound of the structure and the certainty of the merge. They trade: a shorter flush gives fresher data and more load on the merger; a bigger k' or sketch gives better accuracy and more memory and network. Results are stored per window (a table of window end, rank, item, score) so history, charts and recovery after a Redis flush do not depend on the live structure.

1  workers flush local top-k' every 5 s            -> merger
2  merger writes global top-10 to Redis string "top10:1h" (TTL 30 s) and to SQL once per 5 min
3  GET /trending -> Cache::remember("top10:1h", 15 s) -> JSON
4  Redis restarts -> live counters gone; SQL snapshot still answers "top 10 for 10:00-11:00"

Real scenario: the YouTube "most viewed this hour/day" shelf (Case Study: YouTube); a shop's "best sellers" refreshed every minute; an operations dashboard of the top talkers.

LayerHoldsRefreshLost on crash
Worker structureLive counts or sketchEvery eventYes, within the flush window
Redis sorted set or TopK keyMerged counts per bucketEvery flushYes, unless persistence is configured
Result row per window (SQL)Final ranks and scoresEvery rollupNo
HTTP cacheThe rendered JSONTTL 10-30 sIrrelevant

Mechanics ​

Sizing a Count-Min sketch from the error you can accept ​

Pick epsilon from the gap you need to see, then derive memory. The error is relative to the total N, not to the key, so what matters is how large the k-th item is compared with epsilon N.

Stream N (events per window)epsilondeltaw = ceil(e/epsilon)d = ceil(ln(1/delta))Memory at 4-byte cellsLargest overcount
10 million0.0010.012,7195about 54 KB10,000
10 million0.00010.0127,1835about 544 KB1,000
1 billion0.00010.00127,1837about 761 KB100,000
1 billion0.000010.001271,8287about 7.6 MB10,000

A sketch is sensible when the k-th largest count is several times epsilon N. For a Zipf stream the 10th key may hold 3 to 5% of N, so epsilon 0.001 is generous; for a flat stream the sketch gives no useful answer and exact counting or a larger structure is the only honest choice. Compare Redis, which asks for the same two numbers: CMS.INITBYPROB key error probability (error is a fraction of the total count) or CMS.INITBYDIM key width depth.

Knobs and defaults, per product ​

ProductCommandParametersDefault or note
Redis Stack (Top-K)TOPK.RESERVE key k [width depth decay]k items kept; width counters per array; depth arrays; decay probability basewidth 8, depth 7, decay 0.9 on the command page; the Top-K overview recommends width = k log k and depth = log k with a minimum of 5, so set all three explicitly
Redis Stack (Top-K)TOPK.ADD key item [item ...]Returns, per item, the element it expelled from the top-k (or nil)O(n x k) listed
Redis Stack (Top-K)TOPK.LIST key [WITHCOUNT]Lists the current itemsO(k log k) listed
Redis Stack (Count-Min)CMS.INITBYPROB key error probability [CELL_SIZE bytes]Error as a fraction of N; probability of an inflated countCELL_SIZE 1, 2, 4 or 8; default 4
Redis Stack (Count-Min)CMS.INCRBY key item increment [item increment ...], CMS.QUERY, CMS.MERGEIncrement, estimate, merge sketches of the same dimensionsThe docs advise ignoring low counts as noise
Redis (HyperLogLog)PFADD key element ..., PFCOUNT key, PFMERGEDistinct countUp to 12 KB, standard error 0.81%
Redis (sorted set)ZINCRBY, ZRANGE key 0 k-1 REV WITHSCORES, ZUNIONSTORE ... WEIGHTS ... AGGREGATE SUMExact counters, weights for decayZREVRANGE is deprecated in favour of ZRANGE ... REV
Kafka StreamsgroupByKey().windowedBy(TimeWindows...).count()Window size, grace, a state store per taskWindowed count is built in; the top-k step is application code (general knowledge, docs page not saved)
Apache FlinkTumblingEventTimeWindows, SlidingEventTimeWindows, keyed stateSize, slide, allowed latenessA top-k over the window result needs a second operator

What goes wrong, verbatim ​

SymptomMessage or behaviourCauseFix
Union across keys in Redis ClusterCROSSSLOT Keys in request don't hash to the same slotBucket keys hash to different slotsUse a hash tag in every bucket key
Wrong command on a keyWRONGTYPE Operation against a key holding the wrong kind of valueA counter key reused for another typeNamespace keys by type and bucket
Memory fullOOM command not allowed when used memory > 'maxmemory'Buckets without a TTL, unbounded member setSet EXPIRE on every bucket; trim with ZREMRANGEBYRANK
Module missingAn unknown command error for TOPK.ADD or CMS.INCRBY (exact wording varies by version)Plain Redis without the probabilistic moduleRun Redis Stack or the Redis Open Source build that includes it
Sketch merge refusedThe Go Merge returns false; Redis CMS.MERGE needs equal dimensionsDifferent width or depthCreate every shard's sketch with the same parameters
Too many results shiftedRanks 9 to 12 flicker between refreshesDifferences smaller than the error boundShow only the confident top, or add hysteresis

The update loop of a sketch plus heap, step by step ​

for each event (key, delta):
1  est = sketch.Add(key, delta)            d row updates, then min of d cells      O(d)
2  if key is in the heap:  update its count, sift                                     O(log k)
3  else if heap has room:  push (key, est)                                            O(log k)
4  else if est > heap root: replace the root with (key, est), sift down              O(log k)
5  periodically: snapshot heap.List() -> publish local top-k'                         O(k log k)

The heap is allowed to hold stale estimates: a key's estimate only grows, so a key that is already in the heap is refreshed when it is seen again, and a key that was evicted can return the next time its estimate beats the root. The failure mode is a one-time spike that fills the heap with keys whose estimates were inflated by collisions; conservative update and a bigger width reduce that.

Go ​

Example: the structures, with tests that compare them with exact counting ​

One Go module, academy/top-k-heavy-hitters, standard library only for the algorithms; go-redis and the in-process miniredis for the Redis-backed store, so the tests need no server. Eight packages, each with tests:

  • topheap: a bounded min-heap of the k best (key, count) pairs, with the Offer call that returns the evicted key (the shape of Redis TOPK.ADD).
  • exact: hash map plus heap, the oracle.
  • cms: Count-Min Sketch with sizing from epsilon and delta, conservative update, Merge, and a Tracker (sketch plus heap).
  • spacesaving: Space-Saving on a Stream-Summary (buckets in a linked list).
  • misragries: the Frequent algorithm with the N/k guarantees as a test.
  • heavykeeper: a lite HeavyKeeper (fingerprints, decay with probability b^-C, fingerprint-collision checks).
  • trending: exact time-bucketed counters in Redis (ZINCRBY plus EXPIRE, ZUNIONSTORE with weights, ZRevRangeWithScores).
  • merge: global top-k from local top-k' lists with lower and upper bounds.

The heap shared by all of them:

go
// Package topheap keeps the k largest (key, count) pairs seen so far using a
// min-heap, so the smallest of the k is always at the root and can be
// evicted in O(log k).
package topheap

import (
	"container/heap"
	"sort"
)

// Item is a key with its (estimated or exact) count.
type Item struct {
	Key   string
	Count int64
}

// Less orders items by descending count, then ascending key, so results are
// deterministic when counts tie.
func Less(a, b Item) bool {
	if a.Count != b.Count {
		return a.Count > b.Count
	}
	return a.Key < b.Key
}

type minHeap struct {
	items []Item
	pos   map[string]int
}

func (h *minHeap) Len() int { return len(h.items) }

// The heap root is the "worst" of the kept items.
func (h *minHeap) Less(i, j int) bool { return Less(h.items[j], h.items[i]) }

func (h *minHeap) Swap(i, j int) {
	h.items[i], h.items[j] = h.items[j], h.items[i]
	h.pos[h.items[i].Key] = i
	h.pos[h.items[j].Key] = j
}

func (h *minHeap) Push(x any) {
	it := x.(Item)
	h.pos[it.Key] = len(h.items)
	h.items = append(h.items, it)
}

func (h *minHeap) Pop() any {
	n := len(h.items)
	it := h.items[n-1]
	h.items = h.items[:n-1]
	delete(h.pos, it.Key)
	return it
}

// TopK tracks the k best items. Offer is O(log k).
type TopK struct {
	k int
	h *minHeap
}

// New returns a tracker for the k largest items.
func New(k int) *TopK {
	return &TopK{k: k, h: &minHeap{pos: make(map[string]int, k+1)}}
}

// Offer reports the latest count for key. It returns the key that was
// evicted from the top k, if any (the "dropped item" of Redis TOPK.ADD).
func (t *TopK) Offer(key string, count int64) (evicted string, ok bool) {
	if i, in := t.h.pos[key]; in {
		t.h.items[i].Count = count
		heap.Fix(t.h, i)
		return "", false
	}
	it := Item{Key: key, Count: count}
	if t.h.Len() < t.k {
		heap.Push(t.h, it)
		return "", false
	}
	if !Less(it, t.h.items[0]) {
		return "", false
	}
	old := t.h.items[0]
	t.h.items[0] = it
	delete(t.h.pos, old.Key)
	t.h.pos[key] = 0
	heap.Fix(t.h, 0)
	return old.Key, true
}

// Contains reports whether key is currently in the top k.
func (t *TopK) Contains(key string) bool { _, ok := t.h.pos[key]; return ok }

// Count returns the stored count for key.
func (t *TopK) Count(key string) (int64, bool) {
	i, ok := t.h.pos[key]
	if !ok {
		return 0, false
	}
	return t.h.items[i].Count, true
}

// Full reports whether k items are tracked.
func (t *TopK) Full() bool { return t.h.Len() >= t.k }

// Min returns the smallest count among the kept items, or 0 when not full.
func (t *TopK) Min() int64 {
	if t.h.Len() < t.k {
		return 0
	}
	return t.h.items[0].Count
}

// List returns the kept items, best first.
func (t *TopK) List() []Item {
	out := make([]Item, len(t.h.items))
	copy(out, t.h.items)
	sort.Slice(out, func(i, j int) bool { return Less(out[i], out[j]) })
	return out
}
go
package topheap

import "testing"

func TestKeepsLargestAndEvicts(t *testing.T) {
	tk := New(2)
	tk.Offer("a", 5)
	tk.Offer("b", 3)
	if ev, ok := tk.Offer("c", 4); !ok || ev != "b" {
		t.Fatalf("want b evicted, got %q %v", ev, ok)
	}
	if _, ok := tk.Offer("d", 1); ok {
		t.Fatal("d is too small and must not evict anything")
	}
	got := tk.List()
	if len(got) != 2 || got[0].Key != "a" || got[1].Key != "c" {
		t.Fatalf("unexpected list %+v", got)
	}
	if tk.Min() != 4 {
		t.Fatalf("min = %d, want 4", tk.Min())
	}
}

func TestOfferUpdatesExistingKey(t *testing.T) {
	tk := New(2)
	tk.Offer("a", 1)
	tk.Offer("b", 2)
	tk.Offer("a", 10)
	got := tk.List()
	if got[0].Key != "a" || got[0].Count != 10 {
		t.Fatalf("a should lead with 10: %+v", got)
	}
}

func TestTieBreakIsDeterministic(t *testing.T) {
	tk := New(2)
	for _, k := range []string{"z", "y", "x"} {
		tk.Offer(k, 7)
	}
	got := tk.List()
	if got[0].Key != "x" || got[1].Key != "y" {
		t.Fatalf("ties must favour the smaller key: %+v", got)
	}
}

The exact baseline:

go
// Package exact is the baseline: a hash map of every key plus a bounded
// min-heap. Memory grows with the number of distinct keys.
package exact

import (
	"sync"

	"academy/top-k-heavy-hitters/topheap"
)

// Counter counts every key exactly. Safe for concurrent use.
type Counter struct {
	mu sync.Mutex
	m  map[string]int64
	n  int64
}

// New returns an empty exact counter.
func New() *Counter { return &Counter{m: make(map[string]int64)} }

// Add adds delta occurrences of key.
func (c *Counter) Add(key string, delta int64) {
	c.mu.Lock()
	c.m[key] += delta
	c.n += delta
	c.mu.Unlock()
}

// Count returns the exact count of key.
func (c *Counter) Count(key string) int64 {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.m[key]
}

// Total returns the stream length (sum of all deltas).
func (c *Counter) Total() int64 {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.n
}

// Distinct returns the number of keys held in memory.
func (c *Counter) Distinct() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return len(c.m)
}

// TopK scans the map once with a size-k heap: O(n log k) time, O(k) extra space.
func (c *Counter) TopK(k int) []topheap.Item {
	c.mu.Lock()
	defer c.mu.Unlock()
	t := topheap.New(k)
	for key, v := range c.m {
		t.Offer(key, v)
	}
	return t.List()
}
go
package exact

import "testing"

func TestTopKExact(t *testing.T) {
	c := New()
	for i := 0; i < 5; i++ {
		c.Add("a", 1)
	}
	c.Add("b", 3)
	c.Add("c", 1)
	top := c.TopK(2)
	if len(top) != 2 || top[0].Key != "a" || top[0].Count != 5 || top[1].Key != "b" {
		t.Fatalf("unexpected top %+v", top)
	}
	if c.Total() != 9 || c.Distinct() != 3 || c.Count("c") != 1 {
		t.Fatalf("bad totals: %d %d", c.Total(), c.Distinct())
	}
}

Count-Min Sketch with the Tracker, and its tests (sizing formula, never undercounts, error within epsilon N for at least 1-delta of keys, conservative update tighter, merge equals one sketch):

go
// Package cms implements a Count-Min sketch (Cormode and Muthukrishnan) and
// a top-k tracker built from a sketch plus a min-heap.
//
// Sizing from the paper: width w = ceil(e / epsilon), depth d = ceil(ln(1/delta)).
// A point estimate never undercounts, and with probability at least 1-delta it
// overcounts by at most epsilon * N, where N is the sum of all increments.
package cms

import (
	"hash/fnv"
	"math"

	"academy/top-k-heavy-hitters/topheap"
)

// Sketch is a depth x width array of counters.
type Sketch struct {
	w, d  uint64
	cells []uint64
	n     uint64
	cons  bool
}

// NewWithError sizes a sketch for the given error and failure probability.
func NewWithError(epsilon, delta float64) *Sketch {
	w := uint64(math.Ceil(math.E / epsilon))
	d := uint64(math.Ceil(math.Log(1 / delta)))
	return New(w, d)
}

// New returns a sketch with explicit width and depth.
func New(w, d uint64) *Sketch {
	return &Sketch{w: w, d: d, cells: make([]uint64, w*d)}
}

// Conservative switches on conservative update: only the smallest counters
// of a key are raised. It lowers overestimation and keeps the no-undercount
// guarantee, but sketches built this way cannot be merged by addition
// without losing that tightness.
func (s *Sketch) Conservative(on bool) { s.cons = on }

// Width and Depth report the dimensions.
func (s *Sketch) Width() uint64 { return s.w }
func (s *Sketch) Depth() uint64 { return s.d }

// Total returns N, the sum of all increments.
func (s *Sketch) Total() uint64 { return s.n }

// Bytes is the counter memory in bytes (8 bytes per cell).
func (s *Sketch) Bytes() int { return len(s.cells) * 8 }

// col derives the column index for one row from one 64-bit FNV hash with double
// hashing (h1 + i*h2). The paper assumes pairwise-independent functions;
// double hashing is the usual practical stand-in.
func (s *Sketch) col(key string, row uint64) uint64 {
	h := fnv.New64a()
	_, _ = h.Write([]byte(key))
	sum := h.Sum64()
	h1, h2 := sum&0xffffffff, sum>>32|1
	return (h1 + row*h2) % s.w
}

// Add increments key by delta and returns the new estimate.
func (s *Sketch) Add(key string, delta uint64) uint64 {
	s.n += delta
	if s.cons {
		est := s.Estimate(key) + delta
		for r := uint64(0); r < s.d; r++ {
			c := &s.cells[r*s.w+s.col(key, r)]
			if *c < est {
				*c = est
			}
		}
		return est
	}
	est := uint64(math.MaxUint64)
	for r := uint64(0); r < s.d; r++ {
		c := &s.cells[r*s.w+s.col(key, r)]
		*c += delta
		if *c < est {
			est = *c
		}
	}
	return est
}

// Estimate returns the minimum counter over all rows.
func (s *Sketch) Estimate(key string) uint64 {
	est := uint64(math.MaxUint64)
	for r := uint64(0); r < s.d; r++ {
		if v := s.cells[r*s.w+s.col(key, r)]; v < est {
			est = v
		}
	}
	return est
}

// Merge adds other into s. Both sketches must have identical dimensions
// (and therefore identical hash functions), which is why every shard of a
// distributed deployment must be created with the same parameters.
func (s *Sketch) Merge(other *Sketch) bool {
	if s.w != other.w || s.d != other.d {
		return false
	}
	for i := range s.cells {
		s.cells[i] += other.cells[i]
	}
	s.n += other.n
	return true
}

// Tracker is the classic "sketch plus heap" top-k: every event updates the
// sketch, and the key is offered to a size-k heap with its new estimate.
type Tracker struct {
	sk   *Sketch
	topk *topheap.TopK
}

// NewTracker builds a tracker for the k largest keys.
func NewTracker(sk *Sketch, k int) *Tracker {
	return &Tracker{sk: sk, topk: topheap.New(k)}
}

// Add records one occurrence batch of key.
func (t *Tracker) Add(key string, delta uint64) {
	est := t.sk.Add(key, delta)
	t.topk.Offer(key, int64(est))
}

// TopK returns the current candidates, best first.
func (t *Tracker) TopK() []topheap.Item { return t.topk.List() }

// Sketch exposes the underlying sketch.
func (t *Tracker) Sketch() *Sketch { return t.sk }
go
package cms

import (
	"fmt"
	"math/rand"
	"testing"
)

func TestSizingFormula(t *testing.T) {
	s := NewWithError(0.001, 0.01)
	// w = ceil(e/0.001) = 2719, d = ceil(ln 100) = 5
	if s.Width() != 2719 || s.Depth() != 5 {
		t.Fatalf("got w=%d d=%d", s.Width(), s.Depth())
	}
}

func TestNeverUndercountsAndStaysInBound(t *testing.T) {
	const eps, delta = 0.002, 0.01
	s := NewWithError(eps, delta)
	truth := map[string]uint64{}
	r := rand.New(rand.NewSource(1))
	z := rand.NewZipf(r, 1.2, 1, 20000)
	for i := 0; i < 200000; i++ {
		k := fmt.Sprintf("k%d", z.Uint64())
		truth[k]++
		s.Add(k, 1)
	}
	bad := 0
	bound := uint64(eps * float64(s.Total()))
	for k, v := range truth {
		est := s.Estimate(k)
		if est < v {
			t.Fatalf("undercount for %s: %d < %d", k, est, v)
		}
		if est-v > bound {
			bad++
		}
	}
	if frac := float64(bad) / float64(len(truth)); frac > delta*2 {
		t.Fatalf("%.4f of keys exceed epsilon*N, want about <= %.2f", frac, delta)
	}
}

func TestConservativeUpdateIsTighter(t *testing.T) {
	plain, cons := New(64, 3), New(64, 3)
	cons.Conservative(true)
	truth := map[string]uint64{}
	r := rand.New(rand.NewSource(2))
	for i := 0; i < 5000; i++ {
		k := fmt.Sprintf("k%d", r.Intn(500))
		truth[k]++
		plain.Add(k, 1)
		cons.Add(k, 1)
	}
	var ep, ec uint64
	for k, v := range truth {
		ep += plain.Estimate(k) - v
		ec += cons.Estimate(k) - v
		if cons.Estimate(k) < v {
			t.Fatal("conservative update undercounted")
		}
	}
	if ec >= ep {
		t.Fatalf("conservative error %d should be below plain %d", ec, ep)
	}
}

func TestMergeEqualsSingleSketch(t *testing.T) {
	a, b, all := New(128, 4), New(128, 4), New(128, 4)
	for i := 0; i < 1000; i++ {
		k := fmt.Sprintf("k%d", i%37)
		all.Add(k, 1)
		if i%2 == 0 {
			a.Add(k, 1)
		} else {
			b.Add(k, 1)
		}
	}
	if !a.Merge(b) {
		t.Fatal("merge refused")
	}
	for i := 0; i < 37; i++ {
		k := fmt.Sprintf("k%d", i)
		if a.Estimate(k) != all.Estimate(k) {
			t.Fatalf("merged estimate differs for %s", k)
		}
	}
	if New(64, 4).Merge(b) {
		t.Fatal("different width must be refused")
	}
}

func TestTrackerFindsHeavyKeys(t *testing.T) {
	tr := NewTracker(NewWithError(0.001, 0.01), 3)
	for i := 0; i < 1000; i++ {
		tr.Add("hot", 1)
		if i%2 == 0 {
			tr.Add("warm", 1)
		}
		if i%5 == 0 {
			tr.Add("mild", 1)
		}
		tr.Add(fmt.Sprintf("noise%d", i), 1)
	}
	top := tr.TopK()
	if top[0].Key != "hot" || top[1].Key != "warm" || top[2].Key != "mild" {
		t.Fatalf("unexpected top %+v", top)
	}
}

Space-Saving with Stream-Summary, tested against the two-step example, against the guarantees on a Zipf stream, and for bucket-list order:

go
// Package spacesaving implements the Space-Saving algorithm of Metwally,
// Agrawal and El Abbadi (2005) on top of their Stream-Summary structure:
// buckets of equal count in a sorted doubly linked list, so a counter moves
// up by one in O(1) and the minimum is always the head bucket.
package spacesaving

import "academy/top-k-heavy-hitters/topheap"

type element struct {
	key    string
	count  int64
	err    int64 // upper bound on how much count overestimates the true frequency
	bucket *bucket
}

type bucket struct {
	count      int64
	elems      map[*element]struct{}
	prev, next *bucket
}

// Summary monitors at most m keys.
type Summary struct {
	m          int
	index      map[string]*element
	head, tail *bucket // head has the smallest count
	n          int64
}

// New returns a summary with m counters. Any key whose true frequency is
// above N/m is guaranteed to be monitored.
func New(m int) *Summary {
	return &Summary{m: m, index: make(map[string]*element, m)}
}

// Total is the number of events seen.
func (s *Summary) Total() int64 { return s.n }

// Add processes one occurrence of key.
func (s *Summary) Add(key string) {
	s.n++
	if e, ok := s.index[key]; ok {
		s.increment(e)
		return
	}
	if len(s.index) < s.m {
		e := &element{key: key}
		s.index[key] = e
		s.increment(e)
		return
	}
	// Replacement step: the victim is any element of the minimum bucket.
	var victim *element
	for v := range s.head.elems {
		victim = v
		break
	}
	min := victim.count
	delete(s.index, victim.key)
	victim.key = key
	victim.err = min
	s.index[key] = victim
	s.increment(victim) // count becomes min+1
}

// increment moves e from its bucket to the bucket with count+1.
func (s *Summary) increment(e *element) {
	old := e.bucket
	target := e.count + 1
	var after *bucket
	if old != nil {
		after = old.next
	} else {
		after = s.head
	}
	if old != nil {
		delete(old.elems, e)
	}
	e.count = target
	if after != nil && after.count == target {
		e.bucket = after
		after.elems[e] = struct{}{}
	} else {
		nb := &bucket{count: target, elems: map[*element]struct{}{e: {}}}
		e.bucket = nb
		s.link(nb, old, after)
	}
	if old != nil && len(old.elems) == 0 {
		s.unlink(old)
	}
}

func (s *Summary) link(nb, prev, next *bucket) {
	nb.prev, nb.next = prev, next
	if prev != nil {
		prev.next = nb
	} else {
		s.head = nb
	}
	if next != nil {
		next.prev = nb
	} else {
		s.tail = nb
	}
}

func (s *Summary) unlink(b *bucket) {
	if b.prev != nil {
		b.prev.next = b.next
	} else {
		s.head = b.next
	}
	if b.next != nil {
		b.next.prev = b.prev
	} else {
		s.tail = b.prev
	}
}

// Entry is one monitored key with its guarantee interval.
type Entry struct {
	Key   string
	Count int64 // never below the true frequency
	Error int64 // Count-Error is never above the true frequency
}

// TopK walks the buckets from the largest count down.
func (s *Summary) TopK(k int) []Entry {
	var out []Entry
	for b := s.tail; b != nil && len(out) < k; b = b.prev {
		batch := make([]Entry, 0, len(b.elems))
		for e := range b.elems {
			batch = append(batch, Entry{e.key, e.count, e.err})
		}
		// Equal counts: order by key for determinism.
		for i := 1; i < len(batch); i++ {
			for j := i; j > 0 && batch[j].Key < batch[j-1].Key; j-- {
				batch[j], batch[j-1] = batch[j-1], batch[j]
			}
		}
		out = append(out, batch...)
	}
	if len(out) > k {
		out = out[:k]
	}
	return out
}

// Items converts entries to the common item type.
func Items(es []Entry) []topheap.Item {
	out := make([]topheap.Item, len(es))
	for i, e := range es {
		out[i] = topheap.Item{Key: e.Key, Count: e.Count}
	}
	return out
}
go
package spacesaving

import (
	"fmt"
	"math/rand"
	"testing"
)

func TestPaperExample(t *testing.T) {
	// Two counters, stream X Y Z: Z replaces the minimum and inherits its count.
	s := New(2)
	for _, k := range []string{"X", "X", "Y", "Z"} {
		s.Add(k)
	}
	top := s.TopK(2)
	if top[0].Key != "X" || top[0].Count != 2 {
		t.Fatalf("X must lead with 2: %+v", top)
	}
	if top[1].Key != "Z" || top[1].Count != 2 || top[1].Error != 1 {
		t.Fatalf("Z must hold count 2 with error 1: %+v", top)
	}
}

func TestGuaranteesOnZipf(t *testing.T) {
	const m = 200
	s := New(m)
	truth := map[string]int64{}
	r := rand.New(rand.NewSource(3))
	z := rand.NewZipf(r, 1.1, 1, 50000)
	for i := 0; i < 300000; i++ {
		k := fmt.Sprintf("k%d", z.Uint64())
		truth[k]++
		s.Add(k)
	}
	for _, e := range s.TopK(m) {
		if e.Count < truth[e.Key] {
			t.Fatalf("%s undercounted: %d < %d", e.Key, e.Count, truth[e.Key])
		}
		if e.Count-e.Error > truth[e.Key] {
			t.Fatalf("%s lower bound too high", e.Key)
		}
	}
	// Anything above N/m must be monitored.
	limit := s.Total() / m
	monitored := map[string]bool{}
	for _, e := range s.TopK(m) {
		monitored[e.Key] = true
	}
	for k, v := range truth {
		if v > limit && !monitored[k] {
			t.Fatalf("%s has %d > N/m=%d but is not monitored", k, v, limit)
		}
	}
}

func TestBucketListStaysSorted(t *testing.T) {
	s := New(5)
	r := rand.New(rand.NewSource(4))
	for i := 0; i < 2000; i++ {
		s.Add(fmt.Sprintf("k%d", r.Intn(12)))
	}
	prev := int64(-1)
	for b := s.head; b != nil; b = b.next {
		if b.count <= prev || len(b.elems) == 0 {
			t.Fatalf("bucket list corrupted at count %d", b.count)
		}
		prev = b.count
	}
}

Misra-Gries:

go
// Package misragries implements the Misra-Gries "Frequent" algorithm (1982).
// With k-1 counters it finds every item that occurs more than N/k times
// in one pass; counts are underestimates by at most N/k.
package misragries

// Summary holds at most k-1 counters.
type Summary struct {
	k        int
	counters map[string]int64
	n        int64
}

// New returns a summary for threshold N/k (k >= 2).
func New(k int) *Summary {
	return &Summary{k: k, counters: make(map[string]int64, k)}
}

// Add processes one occurrence of key.
func (s *Summary) Add(key string) {
	s.n++
	if _, ok := s.counters[key]; ok {
		s.counters[key]++
		return
	}
	if len(s.counters) < s.k-1 {
		s.counters[key] = 1
		return
	}
	// No room: decrement every counter and drop the ones that reach zero.
	// The new key is "cancelled" against k-1 others.
	for c := range s.counters {
		s.counters[c]--
		if s.counters[c] == 0 {
			delete(s.counters, c)
		}
	}
}

// Estimate is a lower bound on the true count; the true count is at most
// Estimate + N/k.
func (s *Summary) Estimate(key string) int64 { return s.counters[key] }

// Candidates returns the monitored keys (a superset of all keys above N/k).
func (s *Summary) Candidates() map[string]int64 {
	out := make(map[string]int64, len(s.counters))
	for k, v := range s.counters {
		out[k] = v
	}
	return out
}

// Total returns the stream length.
func (s *Summary) Total() int64 { return s.n }
go
package misragries

import (
	"fmt"
	"math/rand"
	"testing"
)

func TestMajorityStyleGuarantee(t *testing.T) {
	const k = 10
	s := New(k)
	truth := map[string]int64{}
	r := rand.New(rand.NewSource(5))
	z := rand.NewZipf(r, 1.1, 1, 10000)
	for i := 0; i < 100000; i++ {
		key := fmt.Sprintf("k%d", z.Uint64())
		truth[key]++
		s.Add(key)
	}
	n := s.Total()
	cand := s.Candidates()
	for key, v := range truth {
		if v > n/k {
			if _, ok := cand[key]; !ok {
				t.Fatalf("%s occurs %d > N/k=%d but was dropped", key, v, n/k)
			}
		}
		if est := s.Estimate(key); est > v || v-est > n/k {
			t.Fatalf("%s: estimate %d outside [%d-N/k, %d]", key, est, v, v)
		}
	}
	if len(cand) > k-1 {
		t.Fatalf("too many counters: %d", len(cand))
	}
}

HeavyKeeper-lite:

go
// Package heavykeeper is a small HeavyKeeper (Gong et al., USENIX ATC 2018):
// d arrays of (fingerprint, counter) buckets, "count-with-exponential-decay",
// and a min-heap of the k largest flows. It follows the paper's Algorithm 1
// (fingerprint collision detection and selective increment included) but not
// the accelerated array variant.
package heavykeeper

import (
	"hash/fnv"
	"math"
	"math/rand"

	"academy/top-k-heavy-hitters/topheap"
)

type bucket struct {
	fp uint32
	c  uint32
}

// Sketch is the HeavyKeeper structure plus its top-k heap.
type Sketch struct {
	d, w  int
	arr   [][]bucket
	decay []float64 // decay[c] = b^-c, precomputed
	heap  *topheap.TopK
	rnd   *rand.Rand
}

// New creates a sketch with d arrays of w buckets, base b > 1 for the decay
// probability b^-C, and a heap of k flows. Redis TOPK.RESERVE exposes the
// same knobs as width, depth and decay (its default decay is 0.9).
func New(k, w, d int, b float64, seed int64) *Sketch {
	s := &Sketch{d: d, w: w, rnd: rand.New(rand.NewSource(seed)), heap: topheap.New(k)}
	s.arr = make([][]bucket, d)
	for i := range s.arr {
		s.arr[i] = make([]bucket, w)
	}
	s.decay = make([]float64, 256)
	for c := range s.decay {
		s.decay[c] = math.Pow(b, -float64(c))
	}
	return s
}

func (s *Sketch) hash(key string, row int) (fp uint32, col int) {
	h := fnv.New64a()
	_, _ = h.Write([]byte(key))
	sum := h.Sum64()
	fp = uint32(sum>>32) | 1 // never zero, zero marks an empty bucket
	h1, h2 := sum&0xffffffff, sum>>32|1
	return fp, int((h1 + uint64(row)*h2) % uint64(s.w))
}

func (s *Sketch) decayProb(c uint32) float64 {
	if int(c) < len(s.decay) {
		return s.decay[c]
	}
	return 0
}

// Add processes one occurrence of key.
func (s *Sketch) Add(key string) {
	inHeap := s.heap.Contains(key)
	nmin := s.heap.Min()
	full := s.heap.Full()
	var maxv uint32
	for j := 0; j < s.d; j++ {
		fp, col := s.hash(key, j)
		b := &s.arr[j][col]
		switch {
		case b.c == 0:
			b.fp, b.c = fp, 1
			maxv = max(maxv, 1)
		case b.fp == fp:
			// Selective increment: an already-heavy bucket that is not in the
			// heap and exceeds nmin is a fingerprint collision; leave it alone.
			if inHeap || int64(b.c) <= nmin || !full {
				b.c++
				maxv = max(maxv, b.c)
			}
		default:
			// Different flow owns the bucket: decay its counter with
			// probability b^-C and take the bucket over when it hits zero.
			if s.rnd.Float64() < s.decayProb(b.c) {
				b.c--
				if b.c == 0 {
					b.fp, b.c = fp, 1
					maxv = max(maxv, 1)
				}
			}
		}
	}
	est := int64(maxv)
	switch {
	case inHeap:
		old, _ := s.heap.Count(key)
		s.heap.Offer(key, max(est, old))
	case !full || est-nmin == 1:
		// Fingerprint-collision check (Theorem 1): a genuine new elephant can
		// only exceed the heap minimum by exactly one.
		s.heap.Offer(key, est)
	}
}

// TopK returns the tracked flows, best first.
func (s *Sketch) TopK() []topheap.Item { return s.heap.List() }

// Bytes is the bucket memory in bytes (8 bytes per bucket).
func (s *Sketch) Bytes() int { return s.d * s.w * 8 }
go
package heavykeeper

import (
	"fmt"
	"math/rand"
	"testing"
)

func TestElephantsSurviveMice(t *testing.T) {
	s := New(3, 64, 3, 1.08, 1)
	r := rand.New(rand.NewSource(9))
	for i := 0; i < 60000; i++ {
		switch {
		case i%3 == 0:
			s.Add("elephant-1")
		case i%7 == 0:
			s.Add("elephant-2")
		case i%11 == 0:
			s.Add("elephant-3")
		default:
			s.Add(fmt.Sprintf("mouse-%d", r.Intn(20000)))
		}
	}
	got := map[string]bool{}
	for _, it := range s.TopK() {
		got[it.Key] = true
	}
	for _, k := range []string{"elephant-1", "elephant-2", "elephant-3"} {
		if !got[k] {
			t.Fatalf("%s missing from %+v", k, s.TopK())
		}
	}
}

func TestEstimateNeverAboveTruth(t *testing.T) {
	s := New(5, 128, 2, 1.08, 2)
	truth := map[string]int64{}
	r := rand.New(rand.NewSource(10))
	z := rand.NewZipf(r, 1.2, 1, 5000)
	for i := 0; i < 50000; i++ {
		k := fmt.Sprintf("k%d", z.Uint64())
		truth[k]++
		s.Add(k)
	}
	for _, it := range s.TopK() {
		if it.Count > truth[it.Key] {
			t.Fatalf("%s overestimated: %d > %d", it.Key, it.Count, truth[it.Key])
		}
	}
}

The time-bucketed Redis store, with tests for the sliding window, for decay, and for the bucket TTL (against miniredis):

go
// Package trending keeps exact top-k counts per time bucket in Redis sorted
// sets and answers "top k over the last window" with ZUNIONSTORE.
//
// Key layout: <prefix>:<bucketStartUnix>  (sorted set, member = item, score = count)
package trending

import (
	"context"
	"fmt"
	"math"
	"time"

	"github.com/redis/go-redis/v9"
)

// Store writes and reads time-bucketed counters.
type Store struct {
	rdb    redis.Cmdable
	prefix string
	bucket time.Duration
	keep   time.Duration // how long a bucket lives before Redis expires it
}

// New returns a store. bucket is the tumbling window size (for example 1
// minute); keep must exceed the longest window you will query.
func New(rdb redis.Cmdable, prefix string, bucket, keep time.Duration) *Store {
	return &Store{rdb: rdb, prefix: prefix, bucket: bucket, keep: keep}
}

func (s *Store) start(t time.Time) int64 {
	step := int64(s.bucket / time.Second)
	return t.Unix() / step * step
}

// Key returns the bucket key that contains t.
func (s *Store) Key(t time.Time) string { return fmt.Sprintf("%s:%d", s.prefix, s.start(t)) }

// Hit counts one occurrence of item at time t: ZINCRBY plus a TTL so old
// buckets disappear without a cleanup job.
func (s *Store) Hit(ctx context.Context, item string, t time.Time) error {
	key := s.Key(t)
	pipe := s.rdb.Pipeline()
	pipe.ZIncrBy(ctx, key, 1, item)
	pipe.Expire(ctx, key, s.keep)
	_, err := pipe.Exec(ctx)
	return err
}

// Entry is one ranked item.
type Entry struct {
	Item  string
	Score float64
}

// keysFor lists the bucket keys of the window ending at now (oldest first)
// and the age of each in whole buckets (0 = current).
func (s *Store) keysFor(now time.Time, window time.Duration) (keys []string, ages []int) {
	n := int(window / s.bucket)
	cur := s.start(now)
	step := int64(s.bucket / time.Second)
	for i := n - 1; i >= 0; i-- {
		keys = append(keys, fmt.Sprintf("%s:%d", s.prefix, cur-int64(i)*step))
		ages = append(ages, i)
	}
	return keys, ages
}

// Top returns the k highest items over the last window: a sliding window
// built from tumbling buckets. halfLife > 0 weights older buckets with
// 0.5^(age/halfLife), an exponential decay done by ZUNIONSTORE WEIGHTS.
// The union is written to a scratch key with a short TTL and then read.
func (s *Store) Top(ctx context.Context, now time.Time, window time.Duration, k int, halfLife time.Duration) ([]Entry, error) {
	keys, ages := s.keysFor(now, window)
	weights := make([]float64, len(keys))
	for i, age := range ages {
		weights[i] = 1
		if halfLife > 0 {
			weights[i] = math.Pow(0.5, float64(age)*float64(s.bucket)/float64(halfLife))
		}
	}
	dest := fmt.Sprintf("%s:union:%d", s.prefix, now.UnixNano())
	if err := s.rdb.ZUnionStore(ctx, dest, &redis.ZStore{Keys: keys, Weights: weights, Aggregate: "SUM"}).Err(); err != nil {
		return nil, err
	}
	defer s.rdb.Del(ctx, dest)
	zs, err := s.rdb.ZRevRangeWithScores(ctx, dest, 0, int64(k-1)).Result()
	if err != nil {
		return nil, err
	}
	out := make([]Entry, len(zs))
	for i, z := range zs {
		out[i] = Entry{Item: fmt.Sprint(z.Member), Score: z.Score}
	}
	return out, nil
}
go
package trending

import (
	"context"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"
)

func newStore(t *testing.T) (*Store, *miniredis.Miniredis) {
	t.Helper()
	mr := miniredis.RunT(t)
	rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
	t.Cleanup(func() { _ = rdb.Close() })
	return New(rdb, "trend", time.Minute, 2*time.Hour), mr
}

func TestSlidingWindowFromBuckets(t *testing.T) {
	ctx := context.Background()
	st, _ := newStore(t)
	base := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
	hit := func(item string, minutes int, n int) {
		for i := 0; i < n; i++ {
			if err := st.Hit(ctx, item, base.Add(time.Duration(minutes)*time.Minute)); err != nil {
				t.Fatal(err)
			}
		}
	}
	hit("old-hit", 0, 50) // outside a 5-minute window ending at minute 9
	hit("steady", 6, 10)
	hit("steady", 8, 10)
	hit("spike", 9, 15)
	top, err := st.Top(ctx, base.Add(9*time.Minute), 5*time.Minute, 2, 0)
	if err != nil {
		t.Fatal(err)
	}
	if len(top) != 2 || top[0].Item != "steady" || top[0].Score != 20 || top[1].Item != "spike" {
		t.Fatalf("unexpected %+v", top)
	}
}

func TestDecayPrefersRecent(t *testing.T) {
	ctx := context.Background()
	st, _ := newStore(t)
	base := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
	for i := 0; i < 40; i++ {
		_ = st.Hit(ctx, "yesterdays-news", base) // age 4 buckets
	}
	for i := 0; i < 30; i++ {
		_ = st.Hit(ctx, "breaking", base.Add(4*time.Minute)) // age 0
	}
	now := base.Add(4 * time.Minute)
	flat, _ := st.Top(ctx, now, 5*time.Minute, 1, 0)
	decayed, _ := st.Top(ctx, now, 5*time.Minute, 1, time.Minute)
	if flat[0].Item != "yesterdays-news" || decayed[0].Item != "breaking" {
		t.Fatalf("flat=%+v decayed=%+v", flat, decayed)
	}
}

func TestBucketsExpire(t *testing.T) {
	ctx := context.Background()
	st, mr := newStore(t)
	now := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
	_ = st.Hit(ctx, "x", now)
	if ttl := mr.TTL(st.Key(now)); ttl != 2*time.Hour {
		t.Fatalf("ttl = %v", ttl)
	}
}

The merge with bounds:

go
// Package merge combines local top-k' lists from shards into a global top-k
// and says which answers are guaranteed.
//
// Each shard sends its k' largest (key, count) pairs. A key missing from a
// shard's list may still have occurred there, but at most as often as that
// shard's smallest reported count (the shard's "tail"). So every key has an
// interval: Lower = sum of reported counts, Upper = Lower + the tails of the
// shards that did not report it.
package merge

import (
	"sort"

	"academy/top-k-heavy-hitters/topheap"
)

// Local is one shard's report: its top-k' list (best first). If the shard
// holds fewer than k' keys, Complete is true and the tail is zero.
type Local struct {
	Items    []topheap.Item
	Complete bool
}

func (l Local) tail() int64 {
	if l.Complete || len(l.Items) == 0 {
		return 0
	}
	return l.Items[len(l.Items)-1].Count
}

// Result is one merged key with its guarantee interval.
type Result struct {
	Key   string
	Lower int64
	Upper int64
}

// Global merges shard reports and returns the k best by Lower bound, plus a
// flag that is true only when the order and membership of the answer are
// provably correct: the k-th Lower bound is at least the Upper bound of
// every key outside the answer (including keys no shard reported at all).
func Global(locals []Local, k int) (top []Result, certain bool) {
	lower := map[string]int64{}
	seen := map[string]map[int]bool{}
	var sumTails int64
	for i, l := range locals {
		sumTails += l.tail()
		for _, it := range l.Items {
			lower[it.Key] += it.Count
			if seen[it.Key] == nil {
				seen[it.Key] = map[int]bool{}
			}
			seen[it.Key][i] = true
		}
	}
	all := make([]Result, 0, len(lower))
	for key, lo := range lower {
		up := lo
		for i, l := range locals {
			if !seen[key][i] {
				up += l.tail()
			}
		}
		all = append(all, Result{Key: key, Lower: lo, Upper: up})
	}
	sort.Slice(all, func(i, j int) bool {
		if all[i].Lower != all[j].Lower {
			return all[i].Lower > all[j].Lower
		}
		return all[i].Key < all[j].Key
	})
	if len(all) > k {
		top = all[:k]
	} else {
		top = all
	}
	certain = len(top) == k
	if !certain {
		return top, false
	}
	kth := top[k-1].Lower
	// A key nobody reported could still have sumTails occurrences.
	if sumTails > kth {
		certain = false
	}
	for _, r := range all[k:] {
		if r.Upper > kth {
			certain = false
		}
	}
	return top, certain
}
go
package merge

import (
	"fmt"
	"math/rand"
	"sort"
	"testing"

	"academy/top-k-heavy-hitters/topheap"
)

// localTop builds each shard's exact local top-k' list from raw counts.
func localTop(shard map[string]int64, kp int) Local {
	items := make([]topheap.Item, 0, len(shard))
	for k, v := range shard {
		items = append(items, topheap.Item{Key: k, Count: v})
	}
	sort.Slice(items, func(i, j int) bool { return topheap.Less(items[i], items[j]) })
	l := Local{Complete: len(items) <= kp}
	if len(items) > kp {
		items = items[:kp]
	}
	l.Items = items
	return l
}

func truthTop(all map[string]int64, k int) []string {
	items := make([]topheap.Item, 0, len(all))
	for key, v := range all {
		items = append(items, topheap.Item{Key: key, Count: v})
	}
	sort.Slice(items, func(i, j int) bool { return topheap.Less(items[i], items[j]) })
	out := make([]string, k)
	for i := range out {
		out[i] = items[i].Key
	}
	return out
}

// A key present on every shard wins even with k-prime = 1.
func TestEvenlySplitKeyStillWins(t *testing.T) {
	shards := []map[string]int64{
		{"a": 10, "b": 9, "z": 8, "c": 1},
		{"a": 10, "d": 9, "y": 8, "c": 1},
		{"a": 10, "e": 9, "x": 8, "c": 1},
	}
	// z, y, x are small everywhere; "c" sits at the bottom of every list.
	all := map[string]int64{}
	for _, s := range shards {
		for k, v := range s {
			all[k] += v
		}
	}
	want := truthTop(all, 1)[0]
	top, _ := Global([]Local{localTop(shards[0], 1), localTop(shards[1], 1), localTop(shards[2], 1)}, 1)
	if top[0].Key != want {
		t.Fatalf("a should win, got %+v", top)
	}
}

func TestKPrimeFlipsWrongAnswerToRight(t *testing.T) {
	// "t" is second on every shard (9+9+9=27); "u1..u3" are first on one shard each (10).
	shards := []map[string]int64{
		{"u1": 10, "t": 9},
		{"u2": 10, "t": 9},
		{"u3": 10, "t": 9},
	}
	small := []Local{localTop(shards[0], 1), localTop(shards[1], 1), localTop(shards[2], 1)}
	top, certain := Global(small, 1)
	if top[0].Key == "t" || certain {
		t.Fatalf("k'=1 must miss t and must not claim certainty: %+v %v", top, certain)
	}
	big := []Local{localTop(shards[0], 2), localTop(shards[1], 2), localTop(shards[2], 2)}
	top, certain = Global(big, 1)
	if top[0].Key != "t" || top[0].Lower != 27 || !certain {
		t.Fatalf("k'=2 must find t=27 with certainty: %+v %v", top, certain)
	}
}

func TestKeyPartitionedShardsAreExact(t *testing.T) {
	r := rand.New(rand.NewSource(11))
	z := rand.NewZipf(r, 1.2, 1, 3000)
	const shardsN = 4
	shards := make([]map[string]int64, shardsN)
	for i := range shards {
		shards[i] = map[string]int64{}
	}
	all := map[string]int64{}
	for i := 0; i < 100000; i++ {
		id := z.Uint64()
		key := fmt.Sprintf("k%d", id)
		all[key]++
		shards[id%shardsN][key]++ // every key lives on exactly one shard
	}
	locals := make([]Local, shardsN)
	for i := range shards {
		locals[i] = localTop(shards[i], 10)
	}
	top, _ := Global(locals, 10)
	want := truthTop(all, 10)
	for i, r := range top {
		if r.Key != want[i] {
			t.Fatalf("position %d: got %s want %s", i, r.Key, want[i])
		}
	}
}

And the program that replays one Zipf stream through all of them and prints precision and memory:

go
// Command accuracy replays one Zipf-distributed stream through the exact
// counter and four approximate structures and prints precision@k, the error
// of the reported counts and the memory each one holds.
package main

import (
	"fmt"
	"math/rand"
	"os"
	"strconv"

	"academy/top-k-heavy-hitters/cms"
	"academy/top-k-heavy-hitters/exact"
	"academy/top-k-heavy-hitters/heavykeeper"
	"academy/top-k-heavy-hitters/misragries"
	"academy/top-k-heavy-hitters/spacesaving"
	"academy/top-k-heavy-hitters/topheap"
)

func precision(truth, got []topheap.Item) float64 {
	want := map[string]bool{}
	for _, it := range truth {
		want[it.Key] = true
	}
	hit := 0
	for _, it := range got {
		if want[it.Key] {
			hit++
		}
	}
	return float64(hit) / float64(len(truth))
}

func avgRelErr(ex *exact.Counter, got []topheap.Item) float64 {
	var sum float64
	for _, it := range got {
		t := float64(ex.Count(it.Key))
		d := float64(it.Count) - t
		if d < 0 {
			d = -d
		}
		sum += d / t
	}
	return sum / float64(len(got))
}

func main() {
	n, keys, k := 2_000_000, uint64(500_000), 10
	if len(os.Args) > 1 {
		n, _ = strconv.Atoi(os.Args[1])
	}
	r := rand.New(rand.NewSource(42))
	z := rand.NewZipf(r, 1.1, 1, keys)

	ex := exact.New()
	sk := cms.NewTracker(cms.NewWithError(0.0005, 0.01), k)
	ss := spacesaving.New(1000)
	mg := misragries.New(1001)
	hk := heavykeeper.New(k, 2000, 3, 1.08, 7)
	for i := 0; i < n; i++ {
		key := "item-" + strconv.FormatUint(z.Uint64(), 10)
		ex.Add(key, 1)
		sk.Add(key, 1)
		ss.Add(key)
		mg.Add(key)
		hk.Add(key)
	}
	truth := ex.TopK(k)

	var mgItems []topheap.Item
	{
		t := topheap.New(k)
		for key, c := range mg.Candidates() {
			t.Offer(key, c)
		}
		mgItems = t.List()
	}
	fmt.Printf("stream=%d distinct=%d k=%d\n", n, ex.Distinct(), k)
	fmt.Printf("%-24s %9s %10s %12s\n", "structure", "precision", "avg.relerr", "memory")
	fmt.Printf("%-24s %9.2f %10.4f %9d KB (map, ~%d B/key est.)\n", "exact map + heap", 1.0, 0.0, ex.Distinct()*64/1024, 64)
	fmt.Printf("%-24s %9.2f %10.4f %9d KB\n", "count-min + heap", precision(truth, sk.TopK()), avgRelErr(ex, sk.TopK()), sk.Sketch().Bytes()/1024)
	fmt.Printf("%-24s %9.2f %10.4f %9d KB (est.)\n", "space-saving m=1000", precision(truth, spacesaving.Items(ss.TopK(k))), avgRelErr(ex, spacesaving.Items(ss.TopK(k))), 1000*64/1024)
	fmt.Printf("%-24s %9.2f %10.4f %9d KB (est.)\n", "misra-gries k=1001", precision(truth, mgItems), avgRelErr(ex, mgItems), 1000*48/1024)
	fmt.Printf("%-24s %9.2f %10.4f %9d KB\n", "heavykeeper 3x2000", precision(truth, hk.TopK()), avgRelErr(ex, hk.TopK()), hk.Bytes()/1024)
}

Limits of this code, stated so nobody mistakes it for a library: the hash functions are FNV-1a with double hashing, not the pairwise-independent family of the paper, so the epsilon-delta guarantee is the paper's guarantee only approximately; heavykeeper skips the accelerated array variant and its decay table stops at counts of 255 (beyond that the decay probability is treated as zero); spacesaving picks an arbitrary element of the minimum bucket (map iteration order), which the algorithm allows; trending.Top makes three round trips (ZUNIONSTORE, ZRANGE, DEL) that are not atomic together, so a crash can leave a scratch key, which is why a production version sets a short EXPIRE on it; the memory figures printed for the exact map, Space-Saving and Misra-Gries are estimates, not measurements.

The Go angle ​

Go's standard library gives the exact half for free: map[string]int64, container/heap, and sort. Three details matter. A map is not safe for concurrent writes, so the exact counter takes a mutex; for very hot paths shard it into N maps by key hash and merge at read time (the same trick as the sharded counters in Write Buffering). container/heap needs the Less to say which element sits at the root, so a min-heap of the best k means "worst of the best" at the root, and tie-breaking by key makes tests deterministic. And math/rand's rand.NewZipf generates a realistic skewed stream for tests; uniform random data hides every effect in this chapter. For Redis the client is github.com/redis/go-redis/v9; Cmdable.ZIncrBy, ZUnionStore with redis.ZStore{Keys, Weights, Aggregate}, and ZRevRangeWithScores are the calls used here.

Laravel ​

Before: a GROUP BY per request ​

The first version scans the last hour of raw events on every request.

php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

/**
 * Before: every request scans the last hour of raw events.
 * Correct, and the first thing to fall over when the events table has
 * hundreds of millions of rows.
 */
final class NaiveTrending
{
    public function index(): array
    {
        return DB::table('page_views')
            ->select('item', DB::raw('count(*) as hits'))
            ->where('viewed_at', '>', now()->subHour())
            ->groupBy('item')
            ->orderByDesc('hits')
            ->limit(10)
            ->get()
            ->all();
    }
}

After: sorted-set buckets, a rollup job and a cached endpoint ​

TrendingService writes to one Redis sorted set per minute and reads with a weighted union. The Laravel Redis facade passes any Redis command straight through, so zincrby, zunionstore and zrevrange are the real commands.

php
<?php

declare(strict_types=1);

namespace App\Trending;

use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Redis;

/**
 * Exact trending counts in time-bucketed Redis sorted sets.
 *
 * One sorted set per bucket: trending:{bucketStartUnix}, member = item, score = count.
 * The Redis facade passes unknown method names straight to Redis, and
 * zincrby/zunionstore/zrevrange are the real commands.
 */
final class TrendingService
{
    public function __construct(
        private readonly int $bucketSeconds = 60,
        private readonly int $keepSeconds = 7200,
        private readonly string $prefix = 'trending',
    ) {
    }

    public function key(CarbonImmutable $at): string
    {
        $start = intdiv($at->getTimestamp(), $this->bucketSeconds) * $this->bucketSeconds;

        return "{$this->prefix}:{$start}";
    }

    /** Count one occurrence. Two commands, one round trip. */
    public function hit(string $item, ?CarbonImmutable $at = null): void
    {
        $key = $this->key($at ?? CarbonImmutable::now());

        Redis::pipeline(function ($pipe) use ($key, $item): void {
            $pipe->zincrby($key, 1, $item);
            $pipe->expire($key, $this->keepSeconds);
        });
    }

    /**
     * Top k over the last $windowMinutes buckets. A half life (in minutes)
     * weights older buckets by 0.5^(age/halfLife): exponential decay.
     *
     * @return array<string, float> item => score, best first
     */
    public function top(int $k, int $windowMinutes, ?int $halfLifeMinutes = null, ?CarbonImmutable $now = null): array
    {
        $now ??= CarbonImmutable::now();
        $buckets = intdiv($windowMinutes * 60, $this->bucketSeconds);
        $keys = [];
        $weights = [];
        for ($age = $buckets - 1; $age >= 0; $age--) {
            $keys[] = $this->key($now->subSeconds($age * $this->bucketSeconds));
            $weights[] = $halfLifeMinutes === null
                ? 1
                : 0.5 ** (($age * $this->bucketSeconds / 60) / $halfLifeMinutes);
        }

        $dest = "{$this->prefix}:union:" . bin2hex(random_bytes(6));
        Redis::zunionstore($dest, $keys, ['weights' => $weights, 'aggregate' => 'sum']);
        Redis::expire($dest, 30); // safety net if we crash before deleting it
        $top = Redis::zrevrange($dest, 0, $k - 1, ['withscores' => true]);
        Redis::del($dest);

        return $top;
    }
}

The controller serves a cached leaderboard; the cache means the union runs at most once per 15 seconds per window, however many users ask.

php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Trending\TrendingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

final class TrendingController
{
    public function __construct(private readonly TrendingService $trending)
    {
    }

    /** GET /api/trending?window=60  - cached leaderboard, recomputed at most every 15 seconds. */
    public function index(Request $request): JsonResponse
    {
        $window = min(max((int) $request->query('window', 60), 1), 120);

        $top = Cache::remember("trending:top10:{$window}", 15, fn () => $this->trending->top(10, $window, halfLifeMinutes: (int) ($window / 2)));

        return response()->json([
            'window_minutes' => $window,
            'items' => collect($top)->map(fn ($score, $item) => ['item' => $item, 'score' => round((float) $score, 2)])->values(),
        ]);
    }

    /** POST /api/hit - the ingest side; in production this is a queue consumer, not a controller. */
    public function hit(Request $request): JsonResponse
    {
        $this->trending->hit((string) $request->input('item'));

        return response()->json(status: 202);
    }
}
php
<?php

declare(strict_types=1);

use App\Http\Controllers\TrendingController;
use Illuminate\Support\Facades\Route;

Route::get('/trending', [TrendingController::class, 'index']);
Route::post('/hit', [TrendingController::class, 'hit']);

The scheduled rollup writes the last hour's top 50 to SQL every five minutes, so history survives Redis key expiry and a restart:

php
<?php

declare(strict_types=1);

use App\Trending\TrendingService;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;

// Rollup: every five minutes persist the last hour's top 50 so history survives
// Redis key expiry. onOneServer needs a shared cache store; withoutOverlapping
// stops a slow run from stacking up.
Schedule::call(function (): void {
    $window = CarbonImmutable::now()->startOfMinute();
    $top = app(TrendingService::class)->top(50, 60, null, $window);

    $rows = [];
    $rank = 1;
    foreach ($top as $item => $score) {
        $rows[] = [
            'window_end' => $window,
            'window_minutes' => 60,
            'rank' => $rank++,
            'item' => $item,
            'score' => (int) $score,
        ];
    }

    if ($rows !== []) {
        // Same window, same rank: re-running the job overwrites instead of duplicating.
        DB::table('trending_snapshots')->upsert($rows, ['window_end', 'window_minutes', 'rank'], ['item', 'score']);
    }
})->name('trending:rollup')->everyFiveMinutes()->onOneServer()->withoutOverlapping();
php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('trending_snapshots', function (Blueprint $table): void {
            $table->timestamp('window_end');
            $table->unsignedSmallInteger('window_minutes');
            $table->unsignedSmallInteger('rank');
            $table->string('item', 190);
            $table->unsignedBigInteger('score');
            $table->primary(['window_end', 'window_minutes', 'rank']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('trending_snapshots');
    }
};

The SQL behind it (raw-events fallback and the snapshot read):

sql
-- Serve a stored result: one primary-key range scan of k rows.
SELECT rank, item, score
FROM trending_snapshots
WHERE window_end = (SELECT max(window_end) FROM trending_snapshots WHERE window_minutes = 60)
  AND window_minutes = 60
ORDER BY rank
LIMIT 10;

The Laravel angle ​

The Redis facade "supports dynamic methods, meaning you may call any Redis command on the facade and the command will be passed directly to Redis" (Laravel 13 Redis docs), and Redis::pipeline(...) sends the ZINCRBY and EXPIRE in one round trip. Two caveats are honest limits of this page: the Laravel docs show dynamic calls and command() but not the option arrays of zunionstore (weights, aggregate) or zrevrange (withscores); those option names are the ones the framework's phpredis and Predis connection classes accept, and the snippet was syntax-checked with php -l but not run against a Redis server. Cache::remember($key, $seconds, $closure) is the documented way to cache the leaderboard; Schedule::call(...)->everyFiveMinutes()->onOneServer()->withoutOverlapping() is the documented way to run the rollup once per cluster and never twice at the same time (onOneServer needs a cache driver that supports atomic locks, and the scheduled task needs a name, which ->name() provides). Redis Stack commands (TOPK.ADD, CMS.INCRBY) are not facade methods; call them with Redis::command('TOPK.ADD', [...]) after checking the module is installed.

Solving the classic problems ​

ProblemPreferred solutionHowAdvantageCost or limit
Trending hashtagsBucketed sorted sets with decay, or Redis TOPK per windowZINCRBY per minute, weighted ZUNIONSTOREExact, simple, explainableMemory for every distinct tag in the window
Top products per dayExact counts in a batch plus a stored tableGROUP BY in the warehouse, or a daily sorted setExact, auditableNot real time
Hot key detectionCount-Min with threshold in the client or proxyPer-window sketch, reset every windowNo per-key memory, near-zero costEstimate, not a count
DDoS source detectionSpace-Saving or HeavyKeeper on source IPs at the edgem = 1000 counters per edge node, report above a thresholdConstant memory under any floodNeeds tuning of the threshold to the traffic
Global top-k across regionsLocal top-k' plus merge with bounds, or merged sketchesRegions send heaps or sketches every few secondsSmall messagesCertainty flag may be false
Top-k of a huge key space with a reporting deadlineSketch plus heap, with a nightly exact batch to correct itLambda-style: stream gives fast, batch gives truthFast answer plus a correct recordTwo code paths to keep consistent

Every tweet-like event does ZINCRBY trending:{bucket} "#tag" 1 and EXPIRE to twice the longest window. The service computes the leaderboard once per few seconds with a half-life of the window divided by two, stores it in a Redis string with a short TTL, and the API returns that string. Ties and tiny counts are filtered with a minimum score, so a brand-new tag with 3 hits does not outrank a steady one. A blocklist and a moderation filter are applied to the final list, never to the counters (counters stay a faithful record).

Top products per day ​

The orders table is the truth; a nightly job computes SELECT product_id, sum(quantity) ... GROUP BY product_id ORDER BY 2 DESC LIMIT 50, and the result goes to trending_snapshots-style storage. During the day a sorted set updated by the order-created event gives the live view, and the nightly run replaces it. That is the batch-correction pattern in miniature: the live number may drift (a duplicated event, a refund), the batch number is the one that reaches reports.

Hot key detection ​

Count requests per key in a Count-Min sketch inside the cache client for ten seconds; keys over the threshold are added to a hot list shared through a small broadcast channel (or polled from a Redis key); the client serves hot keys from an in-process cache with a one-second TTL. Reset the sketch each window so the answer reflects now.

DDoS source detection ​

On each edge node run Space-Saving over source addresses (or a /24 prefix to survive spoofing churn) with 1,000 counters; every second read the entries whose count minus error is above a budget; hand the confirmed list to the rate limiter or the firewall (Rate Limiting, DDoS Protection). The lower bound (count minus error) is what makes the action safe: only block on a number that is guaranteed to be at most the truth.

YouTube: top 10 videos per hour and per day ​

A worked sketch, with every number an estimate for the exercise, not YouTube data (the architecture of the real system is in Case Study: YouTube). Assume 500 million views per day, which is about 5,800 views per second on average and, as an estimate, 3 times that at peak (17,400 per second).

StepDesignNumber
IngestView events to a log partitioned by video id17,400 events/s peak
Local aggregationEach worker counts its partitions in a map and flushes the delta every 5 sEvents per flush per worker: about 17,400 x 5 / 40 workers = about 2,200
Per-minute bucketFlush into a sorted set views:{minute}; hash tag so all buckets share a slotOne bucket holds at most the videos seen in a minute, say 1 million members
Hourly top 10When a minute closes, trim its sorted set to the 1,000 largest with ZREMRANGEBYRANK; every 10 s union the 60 trimmed buckets (decay off, a true last hour)At most 60 x 1,000 = 60,000 entries per union instead of tens of millions
Daily top 10At the hour boundary, roll the hourly top-1000 lists into a daily sorted set24 hourly lists of 1,000 = 24,000 entries
ServeCache::remember 15 s, SQL snapshot per hour for the history pageOne read per 15 s per region

The lesson of the table is the third and fourth rows: a union of all members is the exact answer and the expensive one, so the design trims each closed bucket to its top 1,000 and accepts that a video that is never in any bucket's top 1,000 cannot make the hourly top 10. The bound of the distributed section says how large that candidate list has to be: with a flat enough head it is safe, with a very flat head it is not, and a Count-Min sketch per hour covers the gap.

Choosing ​

Which structure for which workload ​

WorkloadRecommendedExtra techniqueReason
Under about 1 million distinct keys, one machineExact map + heap, or a Redis sorted setNoneSimplest, exact, cheap at this size
Trending with time decay, moderate cardinalityBucketed sorted sets, weighted ZUNIONSTOREResult cache, SQL snapshotExact, explainable decay
Hundreds of millions of distinct keys, one listSpace-Saving, or Redis TOPKBloom filter in front to drop one-hit keysMemory fixed regardless of cardinality
Counts must merge across many shardsCount-Min Sketch plus candidate heapsSame parameters on every shardCell-wise addition is exact
Need a per-key error interval for decisions (blocking)Space-SavingAct on count minus errorThe interval is the guarantee
Elephant flows in a networkHeavyKeeperFingerprint collision checkBest published accuracy on skewed flows
Distinct counts next to top-kHyperLogLog (PFADD)PFMERGE across shards12 KB for millions of uniques
Audit-grade numbers (billing, ranking contests)Exact, from the event logBatch recountAn approximation must never decide money

Trade-offs ​

ChoiceYou gainYou pay
Exact over approximateNo explanation neededMemory and merge cost grow with cardinality
Sketch plus heap over Space-SavingMergeable, deletions possible with careNo per-key interval; candidates must be tracked separately
Space-Saving over sketchPer-key error, O(m) memoryHarder to merge exactly
Bigger k'Fewer wrong answers after mergeMore bytes per flush
Shorter flush intervalFresher leaderboardMore load on the merger and Redis
Decay over a hard windowSmooth ranking, no cliffAn extra parameter to explain (half-life)
Cache TTL of 15 sFlat load on RedisUp to 15 s more staleness

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel or Go process, one PostgreSQL. Count in memory (a map, or a Redis sorted set if you already run Redis for cache), take the top k with a heap, and persist a snapshot row per window. The GROUP BY over a pre-aggregated hourly table is also fine here: a nightly or hourly job writes (item, hour, hits) and the top-k is an indexed query. Approximate structures buy nothing until the key set no longer fits in memory.

1  POST /view            -> Redis ZINCRBY views:{minute} item 1 (pipeline with EXPIRE)
2  every 5 min (cron)    -> ZUNIONSTORE of the last 60 buckets, INSERT top 50 into trending_snapshots
3  GET /trending         -> Cache::remember 15 s -> JSON

Modular monolith: boundaries without the network ​

The counting module owns the counters and the snapshot table; the product and video modules only emit a Viewed event through an in-process bus. Nobody reads another module's Redis keys: the leaderboard is an interface (TrendingService::top). That keeps the option to move the counting out later (a worker, a Kafka consumer) without touching callers. Keep the time bucket size, the key prefix and the half-life in configuration owned by the module.

Microservices: every arrow is a decision ​

Events flow through a log (Messaging Fundamentals and Ordering & Partitioning own the log): a video.viewed topic partitioned by video id means each video lives on exactly one consumer, so a local top-k per consumer merges exactly. A counting service consumes, counts in a map or sketch, and publishes trending.snapshot every few seconds. A serving service holds the latest snapshot and the cache. Duplicate deliveries inflate counts, so use the idempotent consumer pattern (Idempotent Consumers & the Inbox Pattern) when the number matters (contest, billing), and accept the small drift when it does not (a trending shelf).

1  video-service  -> publish video.viewed(video_id, ts)  key = video_id
2  counter-task 3 -> count in memory (event time bucket), flush top-k' every 5 s
3  merger         -> consume snapshots, merge with bounds, write top-10 per window
4  serving        -> read top-10, Cache 15 s, respond
5  batch job      -> nightly exact recount from the log, replace yesterday's snapshots

Distributed data: replicas, caches, regions ​

A sorted set lives on one Redis node, so one key is a hot key by construction: the leaderboard read is the hottest key in the cluster. Serve it from a replica or from the application cache (Caching) and accept replica lag in the freshness budget (Replication Topologies). Across regions, count per region and merge the top-k' lists or sketches in one place; do not replicate every increment across regions. Every shard of a sketch must share dimensions and hash seeds, or the merge is meaningless. Redis Cluster needs all bucket keys of a union in one slot (hash tag), which concentrates the load on one node: for very high write rates shard the buckets by item hash, take a local top-k per shard, and merge with bounds.

Scaling path: 1x, 10x, 100x ​

ScaleStreamDesignWhat changes next
1xHundreds of events/s, thousands of keysGROUP BY on an hourly table, or one sorted setNothing
10xThousands/s, hundreds of thousands of keysBucketed sorted sets, cached leaderboard, SQL snapshotUnion cost grows with window and member count
100xHundreds of thousands/s, millions of keysKey-partitioned log, per-task sketch or Space-Saving, merge every few secondsChoose k' and sketch size from the bound
1000xMillions/s, billions of keys, many regionsEdge sketches, regional merge, exact nightly batchAccept the approximation, publish the error bound with the number

Lab ​

Expected output, not run, for the Redis parts (no Redis server was started); the Go program in step 1 was run on the author's machine and its output is real, from one run.

1. Accuracy against exact counting (run).

$ cd docs/snippets/system-design/top-k-heavy-hitters/go && go run ./cmd/accuracy
stream=2000000 distinct=180304 k=10
structure                precision avg.relerr       memory
exact map + heap              1.00     0.0000     11269 KB (map, ~64 B/key est.)
count-min + heap              1.00     0.0020       212 KB
space-saving m=1000           1.00     0.0000        62 KB (est.)
misra-gries k=1001            1.00     0.0262        46 KB (est.)
heavykeeper 3x2000            1.00     0.0000        46 KB

Read it carefully: on this Zipf stream (exponent 1.1) all four structures find the ten right keys, because the head is far above any error bound. Run it with a flatter stream (change the exponent toward 1.0001 in the source) and watch precision fall: that is the regime where an approximate structure cannot help.

2. The test suite (run).

$ go vet ./... && go test ./...
ok  academy/top-k-heavy-hitters/cms
ok  academy/top-k-heavy-hitters/heavykeeper
ok  academy/top-k-heavy-hitters/merge
ok  academy/top-k-heavy-hitters/spacesaving
ok  academy/top-k-heavy-hitters/trending

3. Redis Stack Top-K (expected, not run).

127.0.0.1:6379> TOPK.RESERVE hot 3 50 5 0.9
OK
127.0.0.1:6379> TOPK.ADD hot a a a b b c d
1) (nil)
2) (nil)
3) (nil)
4) (nil)
5) (nil)
6) (nil)
7) "c"            # d displaced c from the top 3 (illustrative; exact result depends on the decay)
127.0.0.1:6379> TOPK.LIST hot
1) "a"
2) "b"
3) "d"

4. Redis Stack Count-Min (expected, not run).

127.0.0.1:6379> CMS.INITBYPROB views:2026-11-26 0.001 0.01
OK
127.0.0.1:6379> CMS.INCRBY views:2026-11-26 video-1 100 video-2 5
1) (integer) 100
2) (integer) 5
127.0.0.1:6379> CMS.QUERY views:2026-11-26 video-1 video-9
1) (integer) 100
2) (integer) 0

5. Time-bucketed sorted sets with decay (expected, not run).

127.0.0.1:6379> ZINCRBY {trend}:100 "#go" 40
"40"
127.0.0.1:6379> ZINCRBY {trend}:160 "#news" 30
"30"
127.0.0.1:6379> ZUNIONSTORE {trend}:u 2 {trend}:100 {trend}:160 WEIGHTS 0.5 1
(integer) 2
127.0.0.1:6379> ZRANGE {trend}:u 0 1 REV WITHSCORES
1) "#news"
2) "30"
3) "#go"
4) "20"

6. A failure drill (expected). Start a worker sketch, kill the process, restart it: counts restart from zero. Record how long the top-k is wrong (flush interval plus rebuild time). Then restore the last SQL snapshot into the cache and compare. The point of the drill is to put a number on the freshness window you promised.

Common misconceptions ​

BeliefReality
"A Count-Min Sketch can list the top-k"It stores no keys; you must keep a candidate heap beside it
"Count-Min can undercount"It never undercounts (without deletions); it overcounts by at most epsilon N with probability 1-delta
"Space-Saving counts are exact for monitored keys"They are upper bounds; the stored error gives the interval
"Merging local top-k lists gives the global top-k"Only when every key lives on one shard, or k' is large enough, or the bounds certify it
"Trending is the largest count"It is the largest recent count: time windows or decay are required
"Approximate structures are always smaller and better"Below about a million distinct keys an exact map is simpler and cheaper
"HyperLogLog finds the most frequent item"It only estimates how many distinct items; it knows nothing about frequency
"A Bloom filter counts occurrences"It answers membership only; use a Count-Min Sketch for counts
"Redis TOPK can be merged across nodes"The command set has no merge for Top-K; Count-Min has CMS.MERGE
"The top-k should be computed on every request"Compute on a schedule, cache, and store per window
"Exact in Redis means exact on a cluster"A union needs its keys in one slot, and a node failover can lose recent increments

Cheat sheet ​

TopicWhat to remember
Exact top-kHash map plus size-k min-heap: O(n log k) time, O(distinct) memory
Redis exactZINCRBY to count, ZRANGE key 0 k-1 REV WITHSCORES to read, ZUNIONSTORE to merge buckets
Misra-Griesk-1 counters; every key above N/k survives; counts low by at most N/k
Space-Savingm counters; replace the minimum, inherit its count as the error; any key above N/m is monitored
Lossy CountingBuckets of 1/epsilon; undercount by at most epsilon N
Count-Minw = ceil(e/epsilon), d = ceil(ln(1/delta)); estimate = min of rows; never under
Sketch plus heapUpdate the sketch, offer (key, estimate) to a size-k heap
HeavyKeeperFingerprint plus count, decay the owner with probability b^-C; behind Redis TOPK
Redis StackTOPK.RESERVE/ADD/LIST, CMS.INITBYPROB/INCRBY/QUERY/MERGE, PFADD/PFCOUNT
WindowsTumbling bucket per slice, sliding = union of n slices, decay = weights 0.5^(age/half-life)
DistributedLocal top-k' then merge; lower and upper bounds; certify or enlarge k'
Freshnessflush + merge + cache TTL; store the result per window
Hot keysSketch on the access stream; react with replication, local cache or key salting

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is the top-k of the union of two streams not the union of their top-k lists? Important ​

Answer

Answer: A key may be second on both shards (so absent from each local top-1) yet largest in total. Local lists must be longer than k (k-prime) and the merge should carry lower and upper bounds, or the data must be partitioned so each key lives on one shard.

2 — Size a Count-Min Sketch for epsilon 0.001 and delta 0.01. What are w, d and the memory with 4-byte cells? Good to know ​

Answer

Answer: w = ceil(e / 0.001) = 2,719 and d = ceil(ln 100) = 5, so 2,719 x 5 x 4 bytes is about 54 KB.

3 — A Count-Min estimate says a key has 1,200 hits and N is 10 million at epsilon 0.0001. What can you conclude about its true count? Important ​

Answer

Answer: It is at least 200 and at most 1,200 with probability at least 1-delta: the estimate never undercounts and overcounts by up to epsilon N = 1,000.

4 — In Space-Saving, what does the error stored with a counter mean, and how do you use it to block a source safely? Good to know ​

Answer

Answer: It is the count of the counter the key replaced; the true frequency lies in [count - error, count]. Block only when count minus error already exceeds the limit, because that lower bound cannot be too high.

5 — Why does a Count-Min top-k need a heap? Important ​

Answer

Answer: The sketch stores no keys, only counters, so it cannot enumerate its heaviest items. The heap keeps the candidate keys with their latest estimates.

6 — How do you implement "top 10 in the last hour, recent counts weigh more" in Redis? Important ​

Answer

Answer: One sorted set per minute (ZINCRBY plus EXPIRE), then ZUNIONSTORE over the last 60 keys with WEIGHTS of 0.5 to the power of age over half-life, then ZRANGE ... REV WITHSCORES for the top ten, cached for a few seconds. Keys need a shared hash tag in Redis Cluster.

7 — What does HeavyKeeper do differently from Count-Min when two flows collide in a bucket? Good to know ​

Answer

Answer: Count-Min adds both counts to the shared cell. HeavyKeeper keeps a fingerprint and one counter; a different flow decays the owner with probability b^-C, so small counters are removed quickly and large ones survive.

8 — When is an exact hash map better than any sketch? Must-know ​

Answer

Answer: When the distinct keys fit comfortably in memory (up to about a million per process), when the result is audited or paid for, or when the stream is flat so that the error bound is larger than the gap between ranks.

9 — What belongs in the result table per window and why not just query Redis? Important ​

Answer

Answer: Window end, rank, item and score. It survives Redis restarts and key expiry, serves history pages with an indexed read, and makes the batch correction a simple overwrite.

10 — Name two reactions to a detected hot key and the chapter that owns each. Good to know ​

Answer

Answer: A local in-process cache or replication of the key (Caching), key salting into sub-keys or a partition split (Write Buffering and Sharded Counters, Sharding at System Level).

Glossary ​

TermMeaning
Top-kThe k items with the highest counts in a stream or window
Heavy hitterAn item whose frequency exceeds a threshold (a fraction of the stream)
Frequent itemsThe same problem stated with a support threshold instead of k
Frequency estimationEstimating how often one item occurred, as a Count-Min point query does
Exact countingOne counter per distinct key, no error, memory grows with cardinality
Hash mapKey-to-counter table with O(1) updates
Min-heapA tree whose root is the smallest element; used to keep the k largest
Sorted setRedis structure of unique members ordered by score
ZINCRBYRedis command that adds to a member's score
ZREVRANGEOlder Redis command for highest-first range (replaced by ZRANGE ... REV)
ZUNIONSTORERedis command that merges sorted sets with optional weights
ZRANGE BYSCOREZRANGE form that selects members by score range
Time bucketA fixed time slice with its own counters
Misra-Griesk-1 counters with decrement-all; also called Frequent
Frequent algorithmAnother name for Misra-Gries
Space-SavingCounter algorithm that replaces the minimum and keeps its count as error
Stream summaryBucketed sorted linked list that makes Space-Saving updates O(1)
Lossy CountingBucketed deterministic counter with per-entry maximum error
Count-Min Sketchd x w grid of counters, estimate is the minimum cell
WidthNumber of counters per row, w = ceil(e / epsilon)
DepthNumber of rows (hash functions), d = ceil(ln(1/delta))
EpsilonError as a fraction of the total count N
DeltaProbability that the epsilon bound fails
Error boundThe stated maximum difference between estimate and truth
Count SketchSigned-update sketch with median estimate and L2 error scale
HeavyKeeperFingerprint-and-decay structure for elephant flows
TOPK.ADDRedis Stack command adding items to a Top-K and returning expelled ones
TOPK.LISTRedis Stack command listing the current Top-K
CMS.INCRBYRedis Stack command adding counts to a Count-Min sketch
Bloom filterBit-array membership test with false positives and no false negatives
HyperLogLogDistinct-count estimator, 12 KB and 0.81% error in Redis
PFADDRedis command adding elements to a HyperLogLog
Distinct countNumber of different items seen (cardinality)
Sliding windowAnswer over the last n buckets, advancing by one bucket
Tumbling windowFixed, non-overlapping window
Exponential decayWeighting that halves a count every half-life
Windowed aggregationAggregate (count) computed per key per window
Distributed top-kTop-k from data spread over shards
Local top-kA shard's own top list
MergeCombining local results into a global one
k-primeThe longer list length (k') a shard reports so the merge can be right
Kafka Streams aggregationcount() or aggregate() over a keyed, windowed stream
FlinkApache Flink, a stream processor with keyed windows and state
Batch correctionA later exact recount that replaces the fast approximate result
FreshnessHow old the served answer may be
AccuracyHow close the answer is to the truth
Hot key detectionFinding the keys that overload one node, by top-k on accesses
LeaderboardA ranked list served to users
TrendingRanking by recent growth, not all-time size
DDoS source detectionFinding the few addresses behind an attack with a heavy-hitter structure
Redis StackRedis distribution that includes the probabilistic module commands

References ​

Built by Morteza Negahi