ELLMEngineering Large
Language Models
Download PDF

Chapter 52

Heavy Hitters and Probabilistic Sketches

On this page

A sketch trades retained state for a precisely defined error. Frequency, cardinality, membership, and rank are different queries; their guarantees and merge operations cannot be interchanged.

Deterministic heavy hitters with Misra-Gries

For an insertion-only stream of length N, a phi-heavy hitter is a key with frequency greater than phi N. Exact counts may require one counter per distinct key. Misra-Gries provides deterministic candidates with bounded error.

Choose r counters. For each key x:

  1. if x is tracked, increment its counter;
  2. else if fewer than r keys are tracked, insert x with count one;
  3. else decrement every counter and delete zeros.

With r = ceil(1/phi) - 1, every key with frequency greater than N/(r + 1) is retained as a candidate.

Why? Each global decrement can be paired with the untracked arriving item and one occurrence from each of the r tracked keys, canceling r + 1 distinct occurrences. There can be at most floor(N/(r + 1)) such cancellation rounds. A key absent from the final table must have had all of its occurrences canceled, so its true frequency is at most that number.

If c_hat(x) is the final counter for a retained key, then:

c_hat(x) <= f(x) and f(x) - c_hat(x) <= g <= N/(r + 1),

where g is the number of decrement-all rounds. Also,

g = (N - sum_x c_hat(x)) / (r + 1),

because every ordinary increment increases counter mass by one, while a decrement-all round consumes the arriving untracked item and removes one from each of r counters. A second pass over replayable data can compute exact frequencies for the candidates. Without replay, report estimates and bounds, not exact counts.

Misra-Gries is excellent when a deterministic no-false-negative candidate guarantee matters. It does not directly retain the numerical top k under arbitrary signed updates or event-time expiration.

Reference implementation and cost

Example status: Illustrative Python excerpt; not standalone.

def misra_gries(stream, capacity):
    if capacity <= 0:
        raise ValueError("capacity must be positive")

    counters = {}
    for key in stream:
        if key in counters:
            counters[key] += 1
        elif len(counters) < capacity:
            counters[key] = 1
        else:
            dead = []
            for candidate in counters:
                counters[candidate] -= 1
                if counters[candidate] == 0:
                    dead.append(candidate)
            for candidate in dead:
                del counters[candidate]
    return counters

This literal implementation spends O(r) time on a decrement-all step, but there are at most N/(r+1) such steps. With expected constant-time hash-map operations, total processing time is therefore O(N), with O(1) amortized update time and O(r) worst-case work for one arrival. Global offsets, counter buckets, or another batched-decrement representation can reduce update spikes. Those optimizations must preserve deletion at logical zero; merely postponing decrements without handling zero crossings changes the candidates.

As a trace, process a, b, a, c, a, b, d, a with r = 2. The table evolves:

Arrival Counters after update Explanation
a {a:1} Free counter
b {a:1, b:1} Free counter
a {a:2, b:1} Tracked increment
c {a:1} Cancel a, b, and arriving c
a {a:2} Tracked increment
b {a:2, b:1} Free counter
d {a:1} Cancel a, b, and arriving d
a {a:2} Tracked increment

Here N = 8, final counter mass is two, and g = (8 - 2)/3 = 2. Thus 2 <= f(a) <= 4; the true count is four. The estimate is deliberately a lower bound.

Merging Misra-Gries states

Suppose two disjoint partitions have the same capacity r, stream masses N_A, N_B, and counter maps c_A, c_B. First add counters keywise:

c(x) = c_A(x) + c_B(x).

There are at most 2r keys. If there are more than r, let C be the (r + 1)th-largest positive combined counter. Replace every counter by:

c'(x) = max(c(x) - C, 0).

At most r positive counters remain. This is a weighted reduction: it is equivalent to performing enough cancellation rounds on the summarized weighted items.

The error proof is worth stating. Define each input error budget:

Delta_A = (N_A - sum_x c_A(x))/(r + 1)

and likewise for B. Before pruning,

0 <= f(x) - c(x) <= Delta_A + Delta_B.

Pruning decreases any one counter by at most C, so its error rises by at most C. At least r + 1 combined counters were at least C, hence pruning removes at least (r + 1)C total counter mass. Therefore the merged budget

Delta' = (N_A + N_B - sum_x c'(x))/(r + 1)

is at least Delta_A + Delta_B + C, which covers the new pointwise error. The merged state retains the same deterministic contract. Repeated merges remain valid, although they need not produce the same counters as one serial ordering.

Space-Saving: tighter candidates in practice

Space-Saving also keeps r entries but uses a different replacement rule:

  1. increment a tracked key;
  2. insert an untracked key with (estimate=1, error=0) if a slot is free;
  3. otherwise replace a minimum entry of estimate c_min by the new key with (estimate=c_min+1, error=c_min).

For a tracked key:

estimate(x) - error(x) <= f(x) <= estimate(x).

For an untracked key, its frequency is at most the current minimum estimate. Unlike Misra-Gries, Space-Saving estimates tracked keys from above and often allocates counters more effectively to skewed streams. It guarantees that every key with frequency greater than N/r is tracked.

These intervals can certify a ranking only when they separate. If the kth candidate's lower bound exceeds every other tracked candidate's upper bound and the untracked upper bound, the top-k set is established. Otherwise the result is a candidate ranking, not an exact one.

The ordinary Space-Saving update is nonlinear, so two tables cannot be merged by simply adding entries or taking local winners. Use a published error-aware merge procedure, convert to a summary with a proved reduction rule, or use Misra-Gries when simple deterministic merging is a core requirement. Record which variant is implemented; the shared name alone does not specify merge correctness.

Count-Min Sketch and its error derivation

Three independent row hashes select counters for a key. Querying takes their minimum; collision mass explains why the result can overestimate a nonnegative frequency. Blank cells contain other counters whose values are irrelevant to this query.
Open full diagram ↗

Three independent row hashes select counters for a key. Querying takes their minimum; collision mass explains why the result can overestimate a nonnegative frequency. Blank cells contain other counters whose values are irrelevant to this query.

A Count-Min Sketch estimates nonnegative key frequencies using a table with depth d and width w. Row j has an independent pairwise-independent hash h_j. An increment (x, c) with c >= 0 adds c to cell (j, h_j(x)) in every row. The estimate is:

f_hat(x) = min_j table[j, h_j(x)].

For a fixed row, the queried counter equals the true frequency plus collision noise:

C_j(x) = f(x) + sum_{y != x, h_j(y)=h_j(x)} f(y).

Because every current frequency is nonnegative, C_j(x) >= f(x), so the estimate never undercounts. The insertion-only stream used in this derivation satisfies that condition directly.

Let total mass be F_1 = sum_y f(y). For a pairwise-independent hash into w columns, any other key collides with probability 1/w. The expected collision noise in one row is at most:

E[noise_j] <= (F_1 - f(x)) / w <= F_1 / w.

Choose w = ceil(e / epsilon). Then E[noise_j] <= epsilon F_1 / e. By Markov's inequality:

P(noise_j >= epsilon F_1) <= 1/e.

The estimate takes the minimum over d independent rows, so it exceeds f(x) + epsilon F_1 only if every row has large collision noise:

P(f_hat(x) > f(x) + epsilon F_1) <= e^(-d).

Choosing d = ceil(ln(1/delta)) gives, for a fixed queried key:

f(x) <= f_hat(x) <= f(x) + epsilon F_1

with probability at least 1 - delta.

The table uses O((1/epsilon) log(1/delta)) counters. Update and query cost are O(log(1/delta)). Counter width must accommodate total mass; overflow silently destroys the guarantee.

Pointwise versus many-query guarantees

The derivation is pointwise: fix x independently of the randomly chosen hashes, then ask for its estimate. If a job will issue Q fixed queries and wants every one to satisfy the bound with total failure probability at most eta, the union bound is:

P(any query fails) <= Q delta.

Allocate delta = eta/Q, which changes the depth to:

d = ceil(ln(Q/eta)).

This is conservative but explicit. It does not automatically cover an adversary that adaptively chooses the next query after seeing previous outputs or keys crafted after learning the hash functions. For exposed services, protect seeds, rotate versions deliberately, and validate the threat model.

As a sizing example, epsilon = 0.001 and pointwise delta = 10^(-6) give:

  • w = ceil(e/epsilon) = 2,719;
  • d = ceil(ln(1/delta)) = 14;
  • 38,066 counters;
  • about 297.4 KiB with unsigned 64-bit counters, before array and metadata overhead.

If F_1 = 100,000,000, the additive error allowance is epsilon F_1 = 100,000. That may be excellent for million-count heavy hitters and useless for hundred-count rare keys. Count-Min Sketch does not turn an additive guarantee into a relative one merely because the observed estimate is small.

From frequency estimates to top-k

The sketch contains counters but not the original keys, so it cannot enumerate heavy hitters by itself. Pair it with a candidate mechanism:

  • a bounded heap or Space-Saving summary updated from observed keys;
  • a Misra-Gries candidate table;
  • an external dictionary for a constrained key universe;
  • a second pass that queries known candidates.

Using sketch estimates as heap priorities can admit false positives due to overestimation. A candidate near the boundary should be reported with its error interval. If the gap between the kth and (k+1)th true frequency is smaller than the possible sketch error, exact ordering is not guaranteed.

Standard sketches merge by elementwise addition only when width, depth, hash functions, seeds, counter type, and update semantics match. Include those fields in the serialized schema. For disjoint stream partitions, the merged sketch represents the union multiset. It does not deduplicate replicated events.

For an unweighted increment, conservative update raises only counters at the current row minimum and often reduces empirical overestimation. For a weighted nonnegative increment c, let m = min_j C_j(x) and set every addressed counter to max(C_j(x), m + c); merely adding c to counters equal to m is correct only when c = 1. Conservative update is not the same state transition as ordinary Count-Min. Adding two conservatively updated arrays produces useful combined counters in some implementations, but not the state that serial conservative updates would have produced; use only a merge contract proved by the chosen library and do not silently attach the standard linear-state interpretation.

Valid strict-turnstile deletions preserve this argument for the standard linear sketch: apply the signed delta to every hashed row, and require all true frequencies to remain nonnegative. The bound then uses current mass F_1. A sketch cannot itself certify that a deletion was valid; authoritative event or keyed state must enforce that contract. In a general-turnstile stream, negative true frequencies can cancel collision mass and break the minimum estimator's one-sided guarantee. Use a sketch and estimator analyzed for that model, or exact keyed state.

Cardinality with HyperLogLog

HyperLogLog estimates the number of distinct keys, not total frequency. Hash each key to a uniformly distributed bit string. Use the first p bits to choose one of m = 2^p registers. In the remaining suffix, let rho be one plus the number of leading zeros. Update the selected register:

M[j] = max(M[j], rho).

The intuition begins with one bit string: the event rho > r means the first r suffix bits are zero, which has probability 2^(-r). Seeing a very long zero prefix is therefore evidence of many distinct hashes. Multiple registers reduce variance, and the harmonic mean limits domination by unusually large registers.

The raw estimator is:

E_raw = alpha_m * m^2 / sum_{j=1}^m 2^(-M[j]),

where alpha_m is a bias-correction constant determined by the estimator analysis. In the original estimator, for m >= 128:

alpha_m = 0.7213 / (1 + 1.079/m).

For the usual range and sufficiently large m, relative standard error is approximately:

RSE ~= 1.04 / sqrt(m).

Choosing p = 14 gives m = 2^14 = 16,384 and:

RSE ~= 1.04 / 128 = 0.008125 = 0.8125%.

A plain byte per register therefore uses 16 KiB, plus metadata; packed implementations can use less. This RSE is a standard deviation, not a hard maximum error. A rough normal-model 95% interval would be about +/- 1.96 RSE, but real implementations should expose their calibrated interval and estimator version.

Sparse representations save memory at low cardinality. If V registers are still zero, the classical small-range estimate is linear counting:

E_small = m ln(m/V).

For example, with m = 16,384 and V = 10,000, this gives about 8,089 distinct items. Implementations switch estimators using tested thresholds and bias tables; very large ranges also need a hash-width correction. Use the library's published estimator rather than applying every correction unconditionally.

The update itself is idempotent. Repeating an identical canonical key produces the same register index and rho, and max(M[j], rho) does not change. That means HLL estimates set cardinality despite duplicate occurrences. It does not mean two different events with the same business identifier should always be deduplicated; canonical key choice defines the set being counted.

Two compatible HLL states merge by registerwise maximum because each register summarizes the maximum rho seen in that bucket. This produces a cardinality estimate for set union. Inclusion-exclusion, |A intersect B| = |A| + |B| - |A union B|, can be numerically poor when the intersection is small relative to estimation error. Use a sketch designed for set expressions when intersections are a primary query.

Ordinary HLL cannot delete a key: a register maximum does not reveal the second-largest rho that should replace it. Windowed distinct counting therefore uses separate sketches per pane/window, a specialized time-aware sketch, or recomputation from retained state. Subtracting registers or cardinality estimates is invalid.

Hash width bounds useful cardinality and collision behavior. Seeds, precision p, estimator version, and canonical key encoding are part of the state definition. An attacker who can choose hashes can bias registers or create denial-of-service behavior, so exposed systems need keyed hashing or controlled input.

Bloom filters and the false-positive derivation

A Bloom filter represents approximate set membership in m bits using h hash locations per inserted key. Insert sets all h bits. Query returns "possibly present" if all h bits are one and "definitely absent" otherwise.

Under independent uniform hashing, after inserting n distinct keys:

  • one hash leaves a particular bit zero with probability 1 - 1/m;
  • all h n hash placements leave it zero with probability (1 - 1/m)^(h n);
  • for large m, this is approximately exp(-h n / m);
  • a queried bit is therefore one with probability 1 - exp(-h n / m);
  • all h queried bits are one with approximate probability:

p_fp ~= (1 - exp(-h n / m))^h.

This is the false-positive probability for a key not inserted. There are no false negatives only if the filter has not lost bits, hashing and encoding are consistent, and no unsupported deletion occurs.

Optimal number of hashes

For fixed m and expected n, let a = m/n and minimize:

log p_fp(h) = h ln(1 - exp(-h/a)).

Set y = exp(-h/a). Differentiating with respect to continuous h gives:

d(log p_fp)/dh = ln(1-y) + h y/(a(1-y)).

At y = 1/2, the relation h = a ln 2 makes the two terms -ln 2 and +ln 2, so the derivative is zero. This is the unique interior minimum. Thus the optimum occurs when about half the bits remain zero and:

h_opt = (m / n) ln 2.

At that point:

p_min ~= (1/2)^h = exp(-(m/n) (ln 2)^2) ~= (0.6185)^(m/n).

Solving for a desired false-positive rate p gives:

m ~= -n ln p / (ln 2)^2

and:

h ~= (m/n) ln 2 = -ln p / ln 2.

For n = 10,000,000 and p = 0.001, the design needs about 143,775,876 bits, or 17.1 MiB, and roughly 10 hash probes. Capacity planning must use the number of distinct inserted keys during the filter's lifetime, not request count.

The optimum is real-valued, but an implementation uses an integer. Evaluate the predicted false-positive rate for the two neighboring positive integers and choose based on both probability and CPU cost. The common double-hashing construction derives locations as:

g_i(x) = (h_1(x) + i h_2(x)) mod m, for i = 0, ..., h-1.

This avoids computing h unrelated hashes, but h_1, h_2, modulus choice, and domain separation must follow a construction with an appropriate independence argument. If h_2 shares a factor with m, locations can cycle through only part of the bit array.

If actual n exceeds the design capacity, more bits become one and false positives rise. If observed fraction q of bits is one, the same occupancy model estimates:

n_hat = -(m/h) ln(1-q).

Use that as an operational saturation signal, not as an exact distinct counter. Rotate, layer, or rebuild before occupancy approaches one.

Counting Bloom filters replace bits with counters so deletion can decrement locations. They cost more memory and still require exact update discipline: deleting a key that was never inserted, applying a duplicate deletion, or losing an insertion can reduce counters shared by other keys and create false negatives. Stable Bloom filters intentionally forget old membership and therefore change the error contract.

Compatible Bloom filters can be unioned with bitwise OR. Their bitwise AND has no false negatives for keys in the intersection under the same valid-use assumptions, but its false positives are not determined by intersection cardinality alone: keys present in only one input may still pass. Do not treat AND as a freshly built filter sized for the true intersection, or use it to count the intersection. Filters must share m, hash count, seeds, and encoding.

Streaming quantiles

A percentile query asks for a value by rank, not by numeric distance. For sorted values x_(1) <= ... <= x_(N), a target quantile fraction phi corresponds to rank near phi N, with an explicitly chosen rounding convention. For distinct values, an epsilon-approximate quantile summary can express its returned-value guarantee as a rank in:

[r - epsilon N, r + epsilon N].

Clamp the interval to [1, N]. With repeated values, v occupies the occurrence-rank interval [R_lt(v)+1, R_le(v)]; a returned value is valid when this interval intersects the permitted target range. Using only its upper rank would incorrectly reject the median of a stream of identical values. This returned-value criterion differs from a rank query, which estimates a specified inclusive or strict cumulative count. Pin the library's convention; the DataSketches quantile overview distinguishes rank error from value error and exposes inclusive/exclusive query choices.

This rank contract does not guarantee a small value error. Consider 500 zeros followed by 500 values equal to one billion. For target rank 500 with tolerance ten, the permitted range is [490,510]. Zero occupies ranks 1–500 and one billion occupies 501–1000, so both occurrence intervals intersect that range. Either value can therefore satisfy the returned-quantile contract despite a numerical difference of one billion. In a dense region, the same rank error may have negligible value effect.

Without assumptions on the value distribution, an exact arbitrary quantile in one pass requires linear state in the worst case: an adversary can arrange unseen order information so that many retained distinctions may determine the final rank. Approximate rank is what permits sublinear summaries.

The deterministic Greenwald-Khanna summary stores ordered tuples that bound the minimum and maximum possible rank of retained values. It periodically compresses adjacent tuples while preserving a maximum rank uncertainty proportional to epsilon N. Its usual asymptotic space bound is O((1/epsilon) log(epsilon N)) in the large-stream regime. For epsilon N <= 1, retain the small stream exactly in O(N) space; the logarithmic expression is not a meaningful small-stream allocation formula.

How KLL compaction works

KLL is a randomized hierarchy of compactors. Level ell stores values with implicit weight 2^ell. New items enter level zero with weight one. When a level exceeds its configured capacity:

  1. sort the level;
  2. choose odd or even positions with an independent fair coin;
  3. discard the other positions;
  4. promote the survivors to level ell + 1, doubling their implicit weight;
  5. recursively compact an overflowing higher level.

For an even buffer of 2s items, compaction retains s items of double weight, so represented total mass remains 2s * 2^ell. An odd buffer must leave one item at its original level and compact an even subset; otherwise mass changes. For any fixed query threshold v, sorted pairing means the number of retained representatives at or below v, after doubling, differs from the original prefix count by at most one level-ell item. Thus that compaction contributes rank error at most 2^ell. Choosing odd versus even positions makes the contribution conditionally mean zero. Later buffers depend on earlier choices, so the errors are not simply independent; the capacity schedule and concentration analysis control their accumulation.

A tiny example shows the approximation. Compact level-zero values [1, 2, 4, 7]. If the coin retains [2, 7], each survivor has weight two. Estimated cumulative weights at thresholds 1, 2, 4, 7 are 0, 2, 2, 4, whereas true ranks are 1, 2, 3, 4; the absolute rank error is at most one, exactly the level-zero bound. Retaining [1, 4] gives the opposite signed error.

To query, gather retained items from all levels, attach weight 2^ell, sort by value, and scan cumulative weight until reaching the target rank. A production sketch caches or incrementally maintains enough structure to avoid rebuilding everything for each query.

Compatible KLL states merge by concatenating corresponding levels and running the same compaction rule until capacities are restored. The merge represents the union's weighted items, but random choices and merge-tree shape can change the retained sample. Compatibility includes the capacity parameter, comparator or numeric encoding, weight semantics, randomization/serialization version, and the library's declared merge contract.

The canonical analysis achieves space logarithmic in the failure-probability logarithm, commonly stated as O((1/epsilon) log log(1/delta)) words for its core probabilistic quantile contract. Constants, all-quantiles versus single-query guarantees, and confidence interpretation vary by implementation. Size from the selected library's published normalized-rank-error table rather than treating its tuning parameter as literally 1/epsilon.

Three different tail guarantees

KLL is a useful general rank sketch. REQ concentrates rank accuracy toward a configured end of the distribution. DDSketch, a 2019 foundation still relevant to telemetry, uses logarithmic value buckets to bound relative value error for supported quantiles. These solve different measurement problems.

Requirement Error quantity Engineering consequence
General percentiles Absolute normalized-rank error A small rank interval can span a large latency jump
Extremely high or low ranks Rank error concentrated toward the chosen tail Choose and record which tail the REQ configuration favors
Latency values within a percentage Relative numerical-value error Specify value range, near-zero treatment, and bucket-collapse policy

For an original numerical example, a true p99 of 2,000 ms with a valid 1% relative-value guarantee permits 1,980-2,020 ms. A normalized-rank error of 0.01 around p99 instead permits a broad rank neighborhood; it does not promise a 20 ms error. Near zero, a relative-value contract needs a separate absolute tolerance. If a bounded sketch collapses buckets, establish which quantiles retain its guarantee rather than applying the unbounded analysis to every query.

A hard SLO such as "at least 99% of requests finish within 2,000 ms" often needs only a threshold counter: increment total requests and requests meeting that boundary. That avoids estimating a percentile to answer a threshold question. Choose the treatment of cancellation and timeout first; excluding failed requests can make a broken service look faster. Merge compatible histograms or sketches, never average per-worker p99 values.

Worked check: two shards have p99 values of 10 ms and 1,000 ms. Is the fleet p99 505 ms? No. Those two numbers omit counts and the distributions needed to locate the fleet's 99th percentile.

Choosing a quantile sketch

Distribution-oriented structures such as t-digest are often chosen for accurate tails, but their guarantee and merge behavior differ from deterministic uniform rank error. The phrase "relative error" is ambiguous: it may refer to the rank domain or to numerical value. Name the quantity before choosing a library. A design should name:

  • the exact rank-error definition;
  • pointwise versus simultaneous rank queries;
  • deterministic versus probabilistic failure and the value of delta;
  • support for weights and deletions;
  • merge behavior and whether repeated merging degrades accuracy;
  • tail accuracy requirements;
  • serialization compatibility.

Ordinary KLL and GK summaries support insertion, not arbitrary deletion. Sliding-window quantiles need pane decomposition, an expiration-aware algorithm, or retained raw data; subtracting one sketch from another is invalid. Weighted updates also require a library whose compaction and error analysis cover weights.

Do not use a histogram with arbitrary fixed buckets as if it were a general quantile sketch. Its value resolution is fixed by bucket boundaries, and distribution drift can make the approximation useless. Conversely, do not claim KLL bounds numerical interpolation error: it bounds rank.

Check your design: approximation

Before choosing a sketch, state whether a false positive, a missed candidate, or a rank error is acceptable. Give the guarantee's failure probability and update model. A correct answer rejects using a membership filter as a frequency estimator, subtracting an insertion-only quantile sketch, or advertising a point-query guarantee as an unlimited simultaneous guarantee.