Skip to content

Count-Min Sketch: Frequency Estimates, Error Assumptions and Memory Trade-offs

This article explains Count-Min Sketch frequency estimates and the assumptions behind their error bounds.

A stream processor may need approximate frequencies for supplied keys. CMS answers such point queries; it does not itself list the most frequent keys. Heavy-hitter discovery needs candidate tracking or another algorithm, and a “last hour” query needs an explicit window design. A sketch alone does not prevent DDoS.

An exact Map<String, Long> or Redis counter per distinct key consumes storage that grows with cardinality. Whether a workload of 50,000 events per second exceeds capacity depends on implementation, hardware and retention; no OOM threshold is measured here.

Probabilistic summaries trade some query accuracy for a compact representation. We will explain the CMS update/query mechanism and an unexecuted educational Python implementation, without claiming a recent news trend or production readiness.

The Problem with Exact Counting

A straightforward exact dictionary retains a key and counter for every distinct item. That state grows with cardinality, although it need not all reside in RAM: external storage and other exact representations are possible.

Let's look at a basic mental model of an exact counter in Python:

# The traditional, naive approach
class ExactCounter:
    def __init__(self):
        self.counts = {}

    def add(self, item):
        self.counts[item] = self.counts.get(item, 0) + 1

    def estimate(self, item):
        return self.counts.get(item, 0)

The memory of a Python dictionary includes container tables, references, key objects and integer objects; string byte length alone is not its RAM cost. Measure the actual interpreter and workload, taking shared objects into account. sys.getsizeof reports only directly owned memory, not all referenced objects.

Approximate counts can be useful when a bounded chance of overestimation is acceptable. They are not automatically appropriate for billing or access enforcement, where false positives matter. CMS provides estimates for queried keys, not a guaranteed percentage memory saving or a built-in heavy-hitter list.

What is a Count-Min Sketch?

Graham Cormode and S. Muthukrishnan introduced Count-Min Sketch in their paper published in the Journal of Algorithms in 2005, received in 2003. It summarizes a stream for approximate frequency queries with a configurable number of counters.

Use a zero-initialized grid with d rows and w columns. The classical analysis chooses d independently sampled hash functions from a suitable pairwise-independent/universal family; merely adding salts to one digest is not a proof of those assumptions.

Here is how the architecture looks conceptually:

Width: w columns, numbered 0, 1, 2, …, w−1
Row 0: counters ← hash h_0(x)
Row 1: counters ← hash h_1(x)
Row 2: counters ← hash h_2(x)
…
Row d−1: counters ← hash h_(d−1)(x)

The number of counters stays fixed after allocation. Fixed-width counters need an overflow policy; Python’s arbitrary-size integers can grow as counts grow, so this list-based demonstration does not have exactly constant byte usage. Keys are not retained in the sketch.

How the Algorithm Works: Update and Query

The mechanics of a Count-Min Sketch rely on two simple operations: add and estimate.

1. The Add Operation

When an item x arrives in the stream:

  • We pass x through each of our d hash functions.
  • Each hash function h_i(x) maps the item to a column index in row i (specifically, col = h_i(x) % w).
  • Increment grid[i][col] by a nonnegative integer weight c (usually 1). This article does not support negative updates or decay.

2. The Estimate Query Operation

To find out how many times we’ve seen item x:

  • We pass x through our d hash functions again.
  • We look up the values at grid[i][h_i(x) % w] for all rows.
  • We return the minimum value found among those cells.

Why the minimum? Each row contains the key’s count plus collision contributions. The minimum selects the least inflated row. Nonnegative updates preserve this upper-bound property; hashing controls how likely excessive collision noise is.

With nonnegative updates and no overflow, counter saturation, decay or lost updates, the estimate cannot be below the true count. The additive upper error bound is probabilistic for a fixed query under the stated hash assumptions—not a deterministic guarantee for every key or an adaptive adversary.

Building a Count-Min Sketch in Python

The unexecuted example below demonstrates the mechanism using hashlib SHA-256 with a distinct random salt per row. It validates dimensions, byte keys and nonnegative weights and caps allocation. It is not production-grade, thread-safe or a proof of the classical hash-family guarantee. Python integer storage is not eight bytes per cell; no memory benchmark is printed.

import hashlib
import math
import secrets

class CountMinSketchDemo:
    """Insertion-only demonstration; salted SHA-256 is not a hash-family proof."""
    def __init__(self, epsilon, delta):
        if (type(epsilon) not in (int, float) or type(delta) not in (int, float)
                or not 0 < epsilon < 1 or not 0 < delta < 1):
            raise ValueError('epsilon and delta must lie strictly between 0 and 1')
        # Bound calculations before allocating Python lists.
        if epsilon < 1e-6 or delta < 1e-12:
            raise ValueError('Parameters exceed this demonstration budget')
        self.width = math.ceil(math.e / epsilon)
        self.depth = math.ceil(-math.log(delta))
        if self.width * self.depth > 1_000_000:
            raise ValueError('Counter budget exceeded')
        self.grid = [[0] * self.width for _ in range(self.depth)]
        self.salts = [secrets.token_bytes(16) for _ in range(self.depth)]
        self.total_count = 0

    def _indices(self, item):
        if type(item) is not bytes or len(item) > 4096:
            raise ValueError('A byte key of at most 4096 bytes is required')
        return [int.from_bytes(hashlib.sha256(salt + item).digest(), 'big')
                % self.width for salt in self.salts]

    def add(self, item, value=1):
        if type(value) is not int or not 0 <= value <= 1_000_000_000:
            raise ValueError('Bounded nonnegative integer weight required')
        indices = self._indices(item)
        for row, col in enumerate(indices):
            self.grid[row][col] += value
        self.total_count += value

    def estimate(self, item):
        return min(self.grid[row][col]
                   for row, col in enumerate(self._indices(item)))

# No network data, IP collection, invocation, timing or RAM benchmark.

Sizing Your Sketch: The Mathematical Guardrails

Theoretical sizing uses epsilon for additive error and delta for failure probability. These are not absolute control over actual error: the theorem requires its hash and update assumptions, which the illustrative digest construction has not proven.

  • Epsilon (ε): scales the additive error εN, where N is total nonnegative update weight, not the number of distinct keys.
  • Delta (δ): bounds the probability of exceeding that error for a fixed query; the corresponding success probability is at least 1−δ under the theorem’s assumptions.

For a hypothetical total update weight N=1,000,000, ε=0.002 gives additive error 2,000, with per-query failure probability at most δ=0.001 under the classical assumptions. This is not a measured result from the Python code.

Using the formulas inside our Python constructor:

  • width = ceil(e / 0.002) = 1360
  • depth = ceil(ln(1 / 0.001)) = 7

The grid has 1,360×7=9,520 counters. Packed eight-byte counters alone would occupy 76,160 bytes (about 74.4 KiB), excluding all other state. That arithmetic is not the RAM usage of Python lists/integers and does not establish any percentage saving against a dictionary. Fixed-width implementations must reject or otherwise handle overflow without silently invalidating estimates.

Where is Count-Min Sketch Used in the Real World?

Documented implementations and applications illustrate the idea, but their behavior and resource costs differ:

1. Redis Count-Min Sketch commands

Redis documentation describes CMS initialization, increments and queries. Availability depends on the Redis distribution/version and enabled features; check the target environment rather than assuming that every installation exposes those commands. No Redis service was configured or tested here.

2. TinyLFU admission in Caffeine

Caffeine documents Window TinyLFU: an admission window and a main cache use frequency estimates to compare candidates. Its compact frequency sketch is a component of that policy, not the policy itself. Saturating counters and aging have different semantics from the insertion-only textbook sketch. No universal negligible-overhead claim or framework deployment is inferred.

3. Network Traffic Monitoring

Network-stream summaries are an application area discussed in the original research. Whether a particular router, firewall or ASIC uses CMS needs product-specific evidence; this article does not establish such deployments. A sketch stores a lossy summary, not a privacy or security boundary.

Wrapping Up

Exact and approximate counting serve different requirements. Choose based on acceptable error, cardinality, retention and measured resource use, not a blanket assumption that exact counting is too expensive.

Use CMS for point-frequency estimates when its assumptions and failure probability fit the application. Design candidate enumeration, time windows, concurrency, persistence and overflow separately. Do not treat this unexecuted demonstration as a production rate limiter or a guaranteed memory optimization.

What are your thoughts? Have you ever implemented a probabilistic data structure like Bloom Filters, HyperLogLog, or Count-Min Sketch in production? Let me know in the comments below, or share this article with your team's lead architect!

Until next time, keep coding.

Primary references

Post a Comment

Previous Post Next Post