Sub topic 13
Merging Reservoirs Across Partitions
This chapter assumes you have read the earlier chapter on sampling by random keys, and that you are comfortable with Python's heapq module and basic conditional probability.
Large streams are often split across workers. Each worker might handle one Kafka partition, one log file, or one shard of a table. Each worker can build its own reservoir in one pass. The question is how to combine those reservoirs into a single uniform sample of the whole stream without reading the data again.
Why Plain Algorithm R Reservoirs Don't Merge Directly
Suppose worker A saw 1,000 items and worker B saw 1,000,000 items, and each kept k = 10. If you pick 10 items at random from the 20 kept items, A's items are heavily overrepresented. Each of A's items had a 1/100 chance of being in A's reservoir. Each of B's items had a 1/100,000 chance. A correct merge has to account for how many items each worker saw.
You can merge unkeyed reservoirs correctly by tracking the counts n₁ and n₂ and drawing a hypergeometric split of the k slots. That method gets awkward once you have many partitions. Random keys make the merge simple.
The Keyed Merge
Every item gets an independent uniform key, and each worker keeps the k items with the smallest keys. Those k items form a uniform sample of the worker's partition. Across the whole stream, the k smallest keys overall also form a uniform sample.
Any item among the global k smallest is also among the k smallest of its own partition. Fewer than k keys in the whole stream are smaller than it, so fewer than k keys in its own partition are smaller than it. As a result, no worker ever throws away an item the global sample needs. Taking the k smallest keys from the union of the reservoirs gives exactly the sample a single pass over the whole stream would have produced.
The merge is associative and commutative. You can merge pairwise in a tree, in any order, or one at a time as results arrive. This fits reduce-style frameworks such as Spark's reduce or a combiner in MapReduce.
Code and a Uniformity Check
import heapq
import random
from collections import Counter
def keyed_reservoir(stream, k, rng=random):
# Keep the k items with the smallest uniform random keys
return heapq.nsmallest(k, ((rng.random(), item) for item in stream),
key=lambda pair: pair[0])
def merge_reservoirs(a, b, k):
# The k smallest keys of the union form a uniform sample of both streams
return heapq.nsmallest(k, a + b, key=lambda pair: pair[0])
# Uneven partitions, including one smaller than k
partitions = [range(0, 4), range(4, 10), range(10, 12)]
k = 3
trials = 50_000
counts = Counter()
for _ in range(trials):
merged = []
for part in partitions:
merged = merge_reservoirs(merged, keyed_reservoir(part, k), k)
for _, item in merged:
counts[item] += 1
for item in range(12):
print(item, round(counts[item] / trials, 3)) # each close to 3/12 = 0.25Every item should appear with a frequency near 0.25, whatever its partition size. A partition with fewer than k items simply contributes all of its items.
Common Errors
| Mistake | Effect | Fix |
|---|---|---|
| Discarding keys after sampling | Reservoirs can no longer be merged correctly | Store `(key, item)` pairs until the final merge |
| Seeding every worker with the same seed | Keys are correlated across partitions, so the sample is biased by position | Give each worker a distinct seed, e.g. derived from the partition ID |
| Merging by random choice from the union | Small partitions are overrepresented | Merge by smallest key |
| Mixing "smallest" and "largest" conventions | The result is not the global top-k | Use one convention on every worker |
The same merge works for the weighted A-Res sampler from the previous chapter if you flip the direction: keep the k largest keys u ** (1 / w) from the union.
Exercise
Worker A returns [(0.02, "x"), (0.40, "y")] and worker B returns [(0.10, "p"), (0.15, "q")], with k = 2. What is the merged sample, and why is it valid even though A's partition might be much larger than B's?
Show answer
The merged sample is ["x", "p"], the items with keys 0.02 and 0.10. It is valid because the keys are independent uniform draws, so the k smallest keys in the whole stream form a uniform sample. Each global winner must also have been among the k smallest keys in its own partition. Partition sizes are already reflected in the keys: a larger partition tends to produce smaller minimum keys.
Exercise
Why can't you merge two Algorithm R reservoirs by taking k random items from their union?
Show answer
Items from a small partition were kept with a higher probability (k/n₁) than items from a large one (k/n₂). Choosing uniformly from the union would overrepresent the small partition. A correct unkeyed merge must weight the choice by n₁ and n₂.