Sub topic 12
Merging sketches across machines or time windows
This chapter assumes you can already build and query a count-min sketch (a d by w grid of counters with one hash per row, estimated by the row minimum). It also assumes you know the (ε, δ) guarantee and basic Python. Here you will see why two sketches can be added together, what must match for that to be valid, and how to use merging for distributed streams and sliding time windows.
Why merging works
Updating a sketch adds count to one cell in each row. Each cell is therefore a plain sum of the counts of every item that hashes to it. Sums are linear. If sketch A saw stream S₁ and sketch B saw stream S₂, and both use the same hash functions, then A's cell [r][c] holds the total count of S₁ items hashing to that cell, and B's holds the same for S₂. Their cell-by-cell sum equals what a single sketch would hold after seeing S₁ followed by S₂.
This gives the sketch three useful properties:
- Order does not matter. Merging is commutative and associative, so you can merge in any order or in a tree.
- Cost does not depend on stream length. Merging touches
w × dcounters. For ε = 0.001 and δ = 0.01 that is 13,595 counters, whether the streams held a thousand events or a trillion. - The guarantee carries over. The merged sketch satisfies the same ε and δ bound, with N now equal to the combined stream length N₁ + N₂.
What must match
Adding two tables is only meaningful if cell [r][c] means the same thing in both. That requires identical dimensions and identical hash functions.
| Property | If it differs |
|---|---|
| Width `w` | Columns refer to different hash buckets. The sum is meaningless. |
| Depth `d` | Rows cannot be paired. |
| Hash parameters `(a, b)` per row | The same item lands in different columns in each sketch. Estimates become garbage, and they may still look plausible. |
| The base hash of the item | Same effect as differing parameters. |
The last row catches many people in practice. Python's built-in hash() for strings is randomized per process (controlled by PYTHONHASHSEED). Two worker processes would map "apple" to different integers, so their tables would not line up even with identical (a, b) values. For sketches that leave a process, use a stable hash. The code below uses hashlib.blake2b.
A mergeable implementation
This version is self-contained. It uses a stable item hash and a seeded generator, so any process that builds a sketch with the same epsilon, delta, and seed gets the same hash functions.
import hashlib
import math
import random
class CountMinSketch:
def __init__(self, epsilon, delta, seed=0):
self.w = math.ceil(math.e / epsilon)
self.d = math.ceil(math.log(1 / delta))
self.p = (1 << 61) - 1
rng = random.Random(seed)
self.params = [
(rng.randrange(1, self.p), rng.randrange(0, self.p))
for _ in range(self.d)
]
self.table = [[0] * self.w for _ in range(self.d)]
self.total = 0
def _cols(self, item):
digest = hashlib.blake2b(str(item).encode("utf-8"), digest_size=8).digest()
x = int.from_bytes(digest, "big") % self.p
for a, b in self.params:
yield ((a * x + b) % self.p) % self.w
def add(self, item, count=1):
for row, col in zip(self.table, self._cols(item)):
row[col] += count
self.total += count
def estimate(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))
def merge(self, other):
if (self.w, self.d, self.params) != (other.w, other.d, other.params):
raise ValueError("sketches must share dimensions and hash parameters")
for row_a, row_b in zip(self.table, other.table):
for i, v in enumerate(row_b):
row_a[i] += v
self.total += other.total
return self
events = ["apple"] * 600 + ["banana"] * 50 + ["cherry"] * 3 + ["date"] * 200
shards = [events[0::3], events[1::3], events[2::3]]
workers = []
for shard in shards:
sketch = CountMinSketch(epsilon=0.01, delta=0.01, seed=42)
for item in shard:
sketch.add(item)
workers.append(sketch)
merged = CountMinSketch(epsilon=0.01, delta=0.01, seed=42)
for sketch in workers:
merged.merge(sketch)
whole = CountMinSketch(epsilon=0.01, delta=0.01, seed=42)
for item in events:
whole.add(item)
assert merged.table == whole.table # identical, not just close
print(merged.total, merged.estimate("apple"), merged.estimate("cherry"))
stranger = CountMinSketch(epsilon=0.01, delta=0.01, seed=7)
try:
merged.merge(stranger)
except ValueError as err:
print("rejected:", err)The assertion merged.table == whole.table is the key result. With plain updates, merging is exact: the merged table is the table you would have built by sketching everything in one place. Each estimate is still at least the true count, as before.
Pass the seed (or the full parameter list) along with a serialized sketch, and refuse to merge when it does not match. The ValueError check in merge does this. A silent merge of mismatched sketches is the worst failure mode, because nothing crashes.
Merging across time windows
Suppose you want counts for "the last hour" but keep only per-minute sketches. Keep one sketch per bucket, and merge the buckets when you query.
from collections import deque
class SlidingWindow:
def __init__(self, buckets, epsilon, delta, seed=0):
self.args = (epsilon, delta, seed)
self.buckets = deque([CountMinSketch(*self.args)], maxlen=buckets)
def add(self, item):
self.buckets[-1].add(item)
def advance(self):
# With maxlen set, appending drops the oldest bucket automatically.
self.buckets.append(CountMinSketch(*self.args))
def window(self):
out = CountMinSketch(*self.args)
for sketch in self.buckets:
out.merge(sketch)
return out
win = SlidingWindow(buckets=3, epsilon=0.01, delta=0.01, seed=42)
for _ in range(5):
win.add("a")
win.advance()
for _ in range(2):
win.add("a")
win.advance()
win.add("a")
print(win.window().estimate("a")) # 8: all three buckets are inside the window
win.advance() # the oldest bucket (5 events) falls out
print(win.window().estimate("a")) # 3The trade-off is granularity. Expiry happens a whole bucket at a time, so the window length is only accurate to one bucket. Memory is buckets × w × d counters, and each query costs buckets merges. A shorter bucket gives sharper windows at higher cost.
Because the table is linear, there is a cheaper alternative. Keep one running window sketch. When a bucket expires, subtract its table from the running sketch instead of re-merging everything. This works only if you added that bucket with plain updates, and it needs counters that can be decremented, as in the turnstile model covered in a later chapter. It also requires keeping the expired bucket's table until it leaves the window.
Merging and conservative update
Conservative update raises counters only as far as the new minimum estimate. This makes the table depend on the order of arrivals, so it is no longer a simple sum of per-item contributions. Merging is still valid, but with weaker properties.
- Upper bound holds. Each item's estimate in each input sketch is at least its true count in that stream. The sum of tables gives an estimate at least the sum of those, so the merged estimate never undercounts.
- Error bound holds. Every cell of a conservative sketch is at most the cell of a plain sketch over the same stream. The merged table is therefore at most the table of a plain merge, and the εN bound still applies.
- Exactness is lost. The merged table is generally not equal to what one conservative sketch would have produced on the combined stream. The result is usually tighter than a plain merge but is not guaranteed to be.
- Subtraction is not safe. Removing an expired bucket from a conservative running sketch can leave counters that do not match any real stream. Use the re-merge approach for windows if you rely on conservative update.
Gotchas and edge cases
- Merging is not idempotent. Adding the same sketch twice doubles its counts. If a worker retries after a network failure, you can double-count a shard. Tag each sketch with a shard and window ID and merge each ID once. This differs from HyperLogLog, where merging takes the maximum and duplicates are harmless.
- Counter overflow. Python integers do not overflow, but a compact implementation with 32-bit counters can. Merging adds counts, so a cell that fit in each input may overflow in the sum. Size the counter type for the combined N.
- Different widths can sometimes be reconciled. With the hash
((a·x + b) mod p) mod w, a column in a sketch of widthk·wmaps to columnc mod win a sketch of widthwfor the same hash parameters. You can fold the wider table down by adding columnsc,c + w,c + 2w, and so on, and then merge. The result has the narrower sketch's error, so you lose the precision you paid for. This works only if the row parameters match and one width is a multiple of the other. - Heavy-hitter heaps do not merge directly. A sketch merges, but a top-k heap of candidates next to it does not. Take the union of candidate items from all workers, then re-query each candidate against the merged sketch and keep the top k. An item that is heavy overall but not in any single worker's top k can be missed, so keep a few more candidates than k per worker.
- Error grows with N, not with the number of merges. Merging 100 sketches does not add 100 times the error. The bound is ε times the combined stream length. If one huge stream dominates, the small streams inherit its absolute error.
Choosing a merge strategy
| Situation | Approach |
|---|---|
| Sharded stream, one global count | Sketch each shard with the same seed, merge periodically or at query time |
| Fixed rolling window | One sketch per bucket, deque with a maximum length, merge on query |
| Large window, frequent queries, plain updates | Running sketch with subtraction of expired buckets |
| Conservative update in use | Merge by addition, re-merge buckets instead of subtracting |
| Workers with different sizes | Fold the wider tables if widths are multiples, otherwise rebuild |
Exercise
Two sketches share w, d, and hash parameters. Sketch A saw 1,000 events and estimates "x" at 120. Sketch B saw 4,000 events and estimates "x" at 310. What does the merged sketch estimate for "x" at most, how large can the overcount be in the merged result under an (ε, δ) guarantee with ε = 0.01, and why does the merged estimate still never undercount?
Show answer
With plain updates, every cell in the merged table is the sum of the matching cells, so the merged estimate for "x" is the minimum over rows of the summed cells. It is at most 120 + 310 = 430, because a minimum of sums is at least the sum of minimums (so it can be higher than 430 only if row minimums fall in different rows). The guarantee applies to the combined stream, N = 5,000, so with probability at least 1 − δ the overcount is at most 0.01 × 5,000 = 50. Each cell holds at least the true count of every item hashing there, and sums keep that inequality. The row minimum is therefore still at least the true count of "x" in the combined stream.
Exercise
A worker crashes after sending its sketch for window 14 and its replacement resends the same sketch. What happens if the coordinator merges both copies, and how do you prevent it?
Show answer
The counts for that worker's shard are added twice, so every estimate that includes those items is inflated by their true counts. This breaks accuracy, not the one-sided property, because the estimates are still never below the true count. Merging is not idempotent. Prevent it by tagging each sketch with a worker ID and a window ID, and having the coordinator record which pairs it has merged and skip repeats.