Sub topic 8
Merging sketches to count unions
This chapter assumes you have read the earlier chapters on registers, ranks, and the estimator. You should also be comfortable with Python lists and the max function. Here you will see why two HyperLogLog sketches can be combined into a sketch of the union of their data, and how to use that in code and in Redis.
Why merging works
Each register holds the largest rank seen among the items that were routed to it. Suppose sketch A saw set X and sketch B saw set Y. Take any register index. The largest rank over X ∪ Y in that register is the larger of two values: the largest rank over X and the largest rank over Y.
So taking the register-wise maximum of A and B gives exactly the registers you would have built by feeding X ∪ Y into one fresh sketch. The merged sketch is not an approximation of that sketch. It is the same sketch.
This also explains why overlap does not cause double counting. An item that appears in both sets hashes to the same register with the same rank in both sketches. Taking a maximum of two equal contributions changes nothing.
Merging in Python
The merge method from the implementation chapter is one line of real work. This example assumes the HyperLogLog class from that chapter is defined in the same file.
import math
a = HyperLogLog(p=12)
b = HyperLogLog(p=12)
for i in range(100_000):
a.add(f"user-{i}")
for i in range(50_000, 150_000):
b.add(f"user-{i}")
print(round(a.estimate())) # close to 100000
print(round(b.estimate())) # close to 100000
a.merge(b)
print(round(a.estimate())) # close to 150000, the size of the union
print(f"standard error: {1.04 / math.sqrt(a.m):.1%}") # about 1.6% for p=12The two sets share 50,000 users. A plain sum of the two estimates would give about 200,000. The merged estimate is close to 150,000, with the usual relative error of 1.04/√m.
Note that a.merge(b) changes a in place. If you still need the original a, make a copy of its registers first.
Properties that make merging useful
Register-wise maximum is commutative, associative, and idempotent. These properties give you several practical abilities:
| Property | What it lets you do |
|---|---|
| Commutative | Merge sketches in any order and get the same result. |
| Associative | Merge partial results in a tree, such as per-server, then per-region, then global. |
| Idempotent | Merge the same sketch twice, for example after a retry, without changing the answer. |
A typical use is a distributed job. Each worker builds a sketch of its own shard. A coordinator receives only the registers, which are a few kilobytes each, and merges them. No raw items cross the network.
Requirements for a valid merge
Merging is only correct when both sketches interpret their registers the same way.
- Same precision. The code raises
ValueErrorifpdiffers, because the index is taken from a different number of bits. Some libraries can reduce a higher-precision sketch to a lower one before merging. - Same hash function. If two sketches hash with different functions, the same item lands in different registers with different ranks, and the maximum is meaningless. Use the same function and the same seed everywhere.
- Same item encoding. The string
"42"and the integer42must be turned into the same bytes before hashing, or they count as different items.
Merging in Redis
Redis offers the same operation. PFCOUNT with several keys counts their union without changing any key. PFMERGE stores the merged sketch in a destination key.
redis-cli PFADD visitors:monday alice bob carol
redis-cli PFADD visitors:tuesday bob dave
redis-cli PFCOUNT visitors:monday
redis-cli PFCOUNT visitors:monday visitors:tuesday
redis-cli PFMERGE visitors:week visitors:monday visitors:tuesday
redis-cli PFCOUNT visitors:weekMonday has three visitors. The multi-key PFCOUNT returns 4, because bob appears on both days. After PFMERGE, the key visitors:week also reports 4. At counts this small Redis uses an exact-looking sparse form, so the numbers match the true values.
Because merging is cheap, you can keep one sketch per day and build weekly or monthly counts later, instead of deciding the time window up front.
Common mistakes
- Adding two estimates together instead of merging the sketches. This double counts shared items.
- Merging sketches built with different seeds or different hash libraries.
- Merging into a sketch you meant to keep unchanged.
- Subtracting sketches to find "new" items. A sketch cannot be un-merged, because the maximum discards information.
Exercise
Sketch A has seen 1,000 distinct users and sketch B has seen 1,000 distinct users. The two groups are identical. What is the merged estimate close to, and what does the merged register array look like compared with A's?
Show answer
The merged estimate is close to 1,000, not 2,000. Every item has the same register index and rank in both sketches, so the register-wise maximum equals A's registers exactly, and the merged sketch is identical to A (and B).
Exercise
Why does a merge fail to give a meaningful result if the two sketches use different hash functions, even when p is the same?
Show answer
Register positions and ranks come from the hash bits. With different hash functions, the same item maps to different registers with different ranks, so the maximum no longer matches what a single sketch over the union would hold, and the estimate is wrong.