Sub topic 12
Merging sketches across machines or time windows
This chapter assumes you have the CountMinSketch class from the earlier chapters, with its add, estimate, w, d, params and table fields.
Why merging matters
Real streams are rarely handled by one process. A site with ten web servers sees ten partial streams. A dashboard may want counts per hour and also per day. You could ship every raw event to one place, but that defeats the purpose of a small summary.
A count-min sketch avoids this. Each machine builds its own sketch. You then combine the sketches, which means sending only a table of counters.
How merging works
Each counter in a sketch is a plain sum of the counts of every item hashed to that cell. If two sketches use the same hash functions, a cell in each one covers the same set of items. Adding the two cells gives what a single sketch would have stored after seeing both streams.
So merging is cell-by-cell addition of the two tables. The result is identical to one sketch that processed both streams.
The merge method
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
CountMinSketch.merge = mergeThe check at the top is the important part. Two sketches can only be merged if they have the same width, the same depth and the same hash parameters. Different parameters would send the same item to different cells, so adding the tables would produce meaningless numbers.
Checking the claim
This example builds two partial sketches and one sketch over the whole stream. It then confirms that the merged tables match.
part_a = CountMinSketch(epsilon=0.01, delta=0.01, seed=7)
part_b = CountMinSketch(epsilon=0.01, delta=0.01, seed=7)
whole = CountMinSketch(epsilon=0.01, delta=0.01, seed=7)
for _ in range(300):
part_a.add("apple")
whole.add("apple")
for _ in range(200):
part_b.add("apple")
whole.add("apple")
for _ in range(40):
part_b.add("banana")
whole.add("banana")
part_a.merge(part_b)
assert part_a.table == whole.table
assert part_a.total == whole.total
print(part_a.estimate("apple"), part_a.estimate("banana"))The same seed gives every sketch the same hash parameters. Both estimates are at least the true counts, 500 and 40, because the merged sketch is the same as the single sketch.
Rules for safe merging
- Share the parameters. Pick
epsilon,deltaandseedonce, and give them to every machine. - Use a stable hash. The class calls Python's built-in
hash(). For strings, its value changes between processes. Sketches built on different machines would therefore disagree about where an item goes. Replace it with a stable hash, such as one fromhashlib, before you merge across processes. - Expect error to add up. The merged sketch has the guarantee for the combined stream length, N = N₁ + N₂. The error bound εN grows with the total count. It does not stay at the size of a single part.
- Conservative update changes the result. If you built the parts with
add_conservative, the merged table is not identical to one conservative sketch over the whole stream. It still never undercounts, since each part's counters are at least the true counts of its own stream and their sum is at least the combined count. It may overcount more than a single conservative sketch would.
Time windows
Merging also supports time windows. Keep one sketch per hour. To answer a question about a day, merge the 24 hourly sketches into a new sketch. To drop old data, discard the oldest hourly sketch. This is simpler than subtracting counts from one large sketch.
Exercise
Two servers each build a sketch with epsilon=0.01 and delta=0.01, but one uses seed=1 and the other uses seed=2. Why is it wrong to add their tables, and what does the merge method do in this case?
Show answer
Different seeds give different hash parameters, so the same item lands in different columns on each server. Adding the tables mixes counts from unrelated items, and the one-sided error guarantee no longer holds. The merge method compares the dimensions and parameters and raises a ValueError.