We are building a DDoS mitigation filter monitoring billions of network packets per minute. We need to count the frequency of each source IP address in real-time to detect anomalous spikes.
Using a standard hash map of counters would require tens of gigabytes of RAM and quickly run out of memory. We are looking into the Count-Min Sketch algorithm. How does it work mathematically, why does it never underestimate frequency, and how do we choose the optimal table width and depth?
The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics).
1. Architectural Layout
A Count-Min Sketch consists of a 2D matrix of integer counters with
drows (depth) andwcolumns (width), paired withdindependent hash functions:2. The Operations
A. Add Item `x` (Increment):
For each row
ifrom0tod - 1, compute column indexcol = h_i(x) % w, and increment that counter:B. Query Frequency of `x` (Point Query):
Because multiple items might collide at the same counter bucket, hash collisions can only increase a counter, never decrease it!
Therefore, to get the best possible estimate, we take the MINIMUM across all d rows:
The Golden Invariant: A Count-Min Sketch NEVER underestimates the true count! True frequency is always $le$ estimated frequency.
3. Mathematical Dimensioning Rules
If you want an error bound within $epsilon cdot N$ with confidence probability $1 – delta$:
ceil pprox lceil rac{2.718}{epsilon}
ceil$
ceil$
For example, to guarantee $le 0.1%$ error with $99%$ confidence, you need only $w = 2718$ columns and $d = 5$ rows. That’s just 13,590 integer counters (~54 KB of RAM) to monitor billions of events!
Clean Python 3.12 Implementation
Complexity Breakdown
O(d)— strictly constant time ($5$ hash calculations and memory writes).O(d)— strictly constant time ($5$ lookups).O(w * d)— strictly fixed in size. Bounded memory that never grows regardless of how many billions of packets arrive!Here is a modern C++ implementation of the Count-Min Sketch for streaming frequency tracking under strict memory caps.
Guarantees: Strictly bounded RAM overhead and zero underestimations.