Heavy Hitters in Turnstile Streams
Misra-Gries and Space-Saving find heavy hitters deterministically, but only in insertion-only streams. With deletions, an item that was heavy and then lost most of its occurrences must disappear from the answer, and an item that rose late must appear, and no counter-based summary can track that. Linear sketches can: count-min and Count-Sketch estimate any frequency at any time. What they lack is a way to find the heavy items without querying all of them. This lesson adds that piece, the dyadic hierarchy, and with it answers range and quantile queries in turnstile streams as well.
The problem
In the strict turnstile model ( at query time) with , report every item with and no item with , with probability . Note that is easy here: in the strict turnstile model it is the sum of all updates, one counter.
A single count-min sketch answers "is heavy?" for a given , but there are candidates. Querying all of them takes time, and a union bound over queries forces rows. With insertions only, the arriving item is the natural candidate; with deletions, an item can become heavy by other items being deleted, at a moment when it does not arrive at all.
The dyadic hierarchy
Let . A dyadic interval at level is a block , the set of items whose binary representation starts with the prefix . Level 0 holds the single items, level the whole universe, and every dyadic interval at level is the disjoint union of two children at level .
Keep one count-min sketch per level, where level treats the prefix as its item. An update goes to all sketches. The frequency of a dyadic interval is the sum of the frequencies of its items, and in the strict turnstile model it is at least the frequency of any item inside it. So:
- if is heavy, every dyadic interval containing is heavy;
- at each level, at most disjoint intervals can be heavy, since their frequencies add up to at most .
Heavy hitters are found by descending from the root, expanding only the intervals whose estimate passes the threshold:
Dyadic heavy-hitter search (Cormode and Muthukrishnan, 2005)
1 frontier ← {the root interval}
2 for ℓ ← L down to 1:
3 next ← {}
4 for each interval I in frontier, for each child J of I:
5 if estimate_{ℓ−1}(J) ≥ φ · ||f||_1: add J to next
6 frontier ← next
7 report frontier (single items at level 0)Since estimates never fall below the truth, no heavy item is lost. Each level keeps at most about intervals (true heavy ones plus a few false positives, which a count-min with error admits only if their true count exceeds ), so the search makes point queries instead of , and a union bound over those queries needs only rows per sketch.
Theorem (Cormode and Muthukrishnan, 2005). In the strict turnstile model, -approximate -heavy hitters can be maintained with counters, update time and query time , succeeding with probability .
The program inserts 23 400 items into a universe of (four planted heavy items among random noise), then deletes 12 000 of them again, and searches for the items above of what remains.
import random
from collections import Counter
P = (1 << 61) - 1
class CountMin:
def __init__(self, w, d, rng):
self.w = w
self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
self.C = [[0] * w for _ in range(d)]
def add(self, x, c):
for row, (a, b) in zip(self.C, self.ab):
row[((a * x + b) % P) % self.w] += c
def estimate(self, x):
return min(row[((a * x + b) % P) % self.w] for row, (a, b) in zip(self.C, self.ab))
class DyadicCountMin:
"""One count-min per level; level l counts the prefixes x >> l (dyadic intervals of length 2^l)."""
def __init__(self, bits, w, d, rng):
self.bits = bits
self.levels = [CountMin(w, d, rng) for _ in range(bits + 1)]
self.total = 0 # ||f||_1 = sum of updates (strict turnstile)
def update(self, x, delta):
self.total += delta
for l, cm in enumerate(self.levels):
cm.add(x >> l, delta)
def heavy_hitters(self, phi):
thr, queries = phi * self.total, 0
frontier = [0] # the root interval: prefix 0 at the top level
for l in range(self.bits, 0, -1):
nxt = []
for p in frontier:
for child in (2 * p, 2 * p + 1):
queries += 1
if self.levels[l - 1].estimate(child) >= thr:
nxt.append(child)
frontier = nxt
return frontier, queries
rng = random.Random(2003)
bits = 16
sk = DyadicCountMin(bits, 64, 3, rng)
exact = Counter()
inserted = []
heavy = {1234: 2000, 40000: 1600, 65000: 1200, 777: 600}
for x, c in heavy.items():
inserted += [x] * c
inserted += [rng.randrange(1 << bits) for _ in range(18000)]
rng.shuffle(inserted)
for x in inserted:
sk.update(x, +1); exact[x] += 1
for x in inserted[:12000]: # delete two thirds of the stream again
sk.update(x, -1); exact[x] -= 1
L1 = sum(exact.values())
phi = 0.05
found, q = sk.heavy_hitters(phi)
print(f"{len(inserted)} insertions, 12000 deletions; ||f||_1 = {L1}, threshold phi*||f||_1 = {phi * L1:.0f}")
print(f"found {found} with {q} point queries (instead of {1 << bits})")
print("true heavy hitters:", sorted(x for x in exact if exact[x] >= phi * L1), "with counts", {x: exact[x] for x in found})
print("item 777, inserted 600 times:", exact[777], "left after the deletions")23400 insertions, 12000 deletions; ||f||_1 = 11400, threshold phi*||f||_1 = 570
found [1234, 40000, 65000] with 104 point queries (instead of 65536)
true heavy hitters: [1234, 40000, 65000] with counts {1234: 925, 40000: 837, 65000: 587}
item 777, inserted 600 times: 303 left after the deletions
The search used about a hundred point queries instead of 65 536. Item 777 was planted too, but most of its copies were deleted and it now holds less than the threshold: a summary that only grows (like Misra-Gries) could not have dropped it.
In C++
The same hierarchy with one flat array per level; the search keeps a frontier of prefixes.
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
class CountMin {
static constexpr std::uint64_t P = (1ULL << 61) - 1;
std::size_t w, d;
std::vector<std::uint64_t> a, b;
std::vector<std::int64_t> C;
std::size_t cell(std::size_t r, std::uint64_t x) const {
return (std::size_t)((std::uint64_t)(((unsigned __int128)a[r] * x + b[r]) % P) % w);
}
public:
CountMin(std::size_t w, std::size_t d, std::mt19937_64& rng) : w(w), d(d), C(w * d) {
for (std::size_t r = 0; r < d; ++r) { a.push_back(1 + rng() % (P - 1)); b.push_back(rng() % P); }
}
void add(std::uint64_t x, std::int64_t c) { for (std::size_t r = 0; r < d; ++r) C[r * w + cell(r, x)] += c; }
std::int64_t estimate(std::uint64_t x) const {
std::int64_t best = INT64_MAX;
for (std::size_t r = 0; r < d; ++r) best = std::min(best, C[r * w + cell(r, x)]);
return best;
}
};
int main() {
const int L = 20; // universe of 2^20 items
std::mt19937_64 rng(2005), gen(9);
std::vector<CountMin> level;
for (int l = 0; l <= L; ++l) level.emplace_back(256, 4, rng);
std::int64_t total = 0;
auto update = [&](std::uint64_t x, std::int64_t delta) {
total += delta;
for (int l = 0; l <= L; ++l) level[l].add(x >> l, delta);
};
std::vector<std::uint64_t> noise;
for (int t = 0; t < 300000; ++t) { noise.push_back(gen() % (1u << L)); update(noise.back(), +1); }
for (int t = 0; t < 20000; ++t) update(123456, +1); // heavy, then mostly deleted
for (int t = 0; t < 18000; ++t) update(123456, -1);
for (int t = 0; t < 15000; ++t) update(999999, +1); // stays heavy
for (int t = 0; t < 250000; ++t) update(noise[t], -1); // most of the noise is deleted again
const double phi = 0.1;
std::vector<std::uint64_t> frontier{0};
long queries = 0;
for (int l = L; l >= 1; --l) {
std::vector<std::uint64_t> next;
for (auto p : frontier)
for (auto c : {2 * p, 2 * p + 1})
if (++queries, level[l - 1].estimate(c) >= phi * total) next.push_back(c);
frontier = next;
}
std::printf("||f||_1 = %lld, threshold %.0f, %ld point queries\n", (long long)total, phi * total, queries);
for (auto x : frontier)
std::printf("heavy: %llu (estimate %lld)\n", (unsigned long long)x, (long long)level[0].estimate(x));
}||f||_1 = 67000, threshold 6700, 50 point queries
heavy: 999999 (estimate 15180)
Range queries and quantiles
The same hierarchy answers range counts : every interval is the disjoint union of at most maximal dyadic intervals, one or two per level, so the estimate is a sum of at most point estimates and its error is at most (one-sided, with the union bound over the pieces). Setting restores error at a factor in space. A quantile query, "the smallest with ", is then a binary search over range queries. The program sketches 20 000 values in (think of response times in milliseconds) and answers four range queries and the median.
import random
P = (1 << 61) - 1
class CountMin:
def __init__(self, w, d, rng):
self.w = w
self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
self.C = [[0] * w for _ in range(d)]
def add(self, x, c):
for row, (a, b) in zip(self.C, self.ab):
row[((a * x + b) % P) % self.w] += c
def estimate(self, x):
return min(row[((a * x + b) % P) % self.w] for row, (a, b) in zip(self.C, self.ab))
def dyadic_cover(lo, hi):
"""Split [lo, hi] into maximal dyadic intervals; yields (level, prefix)."""
while lo <= hi:
l = 0
while lo % (1 << (l + 1)) == 0 and lo + (1 << (l + 1)) - 1 <= hi:
l += 1
yield l, lo >> l
lo += 1 << l
rng = random.Random(1)
bits = 12
levels = [CountMin(128, 3, rng) for _ in range(bits + 1)]
values = [int(1000 * sum(rng.random() for _ in range(4))) for _ in range(20000)] # e.g. response times in ms
for v in values:
for l, cm in enumerate(levels):
cm.add(v >> l, 1)
print("range exact estimate dyadic pieces")
for lo, hi in [(0, 999), (1500, 2500), (1234, 3210), (3000, 4095)]:
pieces = list(dyadic_cover(lo, hi))
est = sum(levels[l].estimate(p) for l, p in pieces)
exact = sum(lo <= v <= hi for v in values)
print(f"[{lo:4}, {hi:4}] {exact:6} {est:8} {len(pieces):6}")
# a quantile from range queries: the smallest t with estimated count of [0, t] >= m/2 (binary search)
lo, hi = 0, (1 << bits) - 1
while lo < hi:
mid = (lo + hi) // 2
if sum(levels[l].estimate(p) for l, p in dyadic_cover(0, mid)) >= len(values) / 2:
hi = mid
else:
lo = mid + 1
print(f"median estimate {lo}, exact median {sorted(values)[len(values) // 2]}")range exact estimate dyadic pieces
[ 0, 999] 842 919 6
[1500, 2500] 11953 12325 8
[1234, 3210] 17771 18425 11
[3000, 4095] 844 911 3
median estimate 1996, exact median 2002
Every range estimate is above the truth, as count-min promises, by an amount that grows with the number of dyadic pieces. Deletions are handled for free, which is the reason to use this structure rather than an insertion-only quantile summary.
Other approaches
- Group testing (Cormode and Muthukrishnan, 2005, "What's hot and what's not"): hash items into buckets; in each bucket keep the total and, for each of the bit positions, the total of the items whose bit is 1. If one item holds more than half of its bucket's mass, its bits can be read off by majority, without any search. Repetition handles buckets with two heavy items.
- -heavy hitters: replace count-min by Count-Sketch at each level. The search is the same, but the error is ; the space becomes words for constant . For insertion-only streams, words suffice (the BPTree of Braverman, Chestnut, Ivkin, Nelson, Wang and Woodruff, 2017).
- Deterministic point queries and heavy hitters in turnstile streams are possible too, with more space: linear sketches built from explicit incoherent matrices give error with -type space (see Nelson, Nguyen and Woodruff, 2012, for the bounds and their limits). The randomized sketches above are what is used in practice.
Test yourself
Why can Misra-Gries not be used when the stream has deletions?
- It uses too much space
- Its counters only track items it saw arriving; an item can become heavy because other items were deleted, without arriving, and a decremented counter cannot be restored
- It is randomized
- It needs to know
In the dyadic search, why are at most about intervals expanded per level?
- Because the hierarchy is binary
- Because the intervals of one level are disjoint, so at most of them can each hold (plus a few false positives with count-min error)
- Because count-min has columns
- Because there are levels
Into how many dyadic intervals can an arbitrary range of a universe of size be split?
- At most 2
- At most
- At most
- Up to