Sub topic 11
Sampling by Random Keys: Keep the k Best
Algorithm R decides each item's fate the moment the item arrives, and that decision depends on the item's position in the stream. This chapter describes a second way to think about uniform sampling. Each item gets a random number called a key, and the sample is the k items with the smallest keys. In expectation this method does the same amount of work as Algorithm R, but it has a property Algorithm R lacks. The key is a stored, comparable record of why an item was kept. That property is what makes weighted sampling and merging possible in the chapters that follow.
This chapter assumes you know Algorithm R and its k/n proof, Python's heapq module, and the basic fact that independent continuous random variables are tied with probability zero.
The Idea: A Random Permutation You Never Materialize
There is a simple offline way to draw a uniform sample of k items from n: shuffle all n items uniformly at random and take the first k. The random-key method does the same thing without storing the shuffle.
- Give every item an independent key
u, drawn uniformly from [0, 1). - Sort the items by key. Because the keys are i.i.d. and continuous, every ordering of the n items is equally likely. The sorted order is a uniform random permutation.
- Keep the k items with the smallest keys. These are the first k positions of a uniform random permutation, so they form a uniform k-subset.
A full sort is not needed. You only need to know which k keys are currently smallest. A bounded max-heap does that job: it holds the k smallest keys seen so far, with the largest of them at the top, ready to be evicted.
Why It Is Uniform
The argument is short and needs no induction.
By symmetry, each of the n items is equally likely to hold any given rank among the n keys. So the probability that item i has one of the k smallest keys is k/n. A stronger claim also holds. Every one of the C(n, k) subsets of size k has the same chance of being the bottom-k set, because every permutation is equally likely and each subset appears in the first k positions of exactly k!(n − k)! permutations.
The proof never uses n, and it does not depend on the order in which items arrive. The sample is a function of the set of (key, item) pairs alone. That order independence is what makes merging work later.
A Streaming Implementation
The version below keeps at most k entries in memory. Python's heapq is a min-heap, so the code stores negated keys. That puts the largest retained key at heap[0], where it can be compared against each new key in O(1).
import heapq
import random
def bottom_k_sample(stream, k, rng=random):
"""Return a list of (key, item) pairs: the k items with the smallest keys."""
if k <= 0:
return []
heap = [] # entries are (-key, index, item); heap[0] holds the largest key kept
for idx, item in enumerate(stream):
key = rng.random()
if len(heap) < k:
heapq.heappush(heap, (-key, idx, item))
elif key < -heap[0][0]:
heapq.heapreplace(heap, (-key, idx, item))
return sorted((-neg_key, item) for neg_key, _, item in heap)
if __name__ == "__main__":
rng = random.Random(42)
print(bottom_k_sample("abcdefghij", 3, rng))The index field matters. If two keys are equal, tuple comparison moves on to the next field. Without the index, Python would compare the items themselves. That raises TypeError for dicts and other types that don't support ordering, and it sneaks a dependence on item values into the sampler. Indices are unique, so comparison never gets as far as the item.
The function returns the keys along with the items. Don't throw them away. A sample without its keys cannot be merged with another sample or extended later.
Without the comments, the tutorial's compact version is a one-liner:
import heapq
import random
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])heapq.nsmallest consumes a generator in one pass and keeps only k elements internally, so it also uses O(k) memory. Passing key=lambda pair: pair[0] stops it from comparing items when keys tie.
Cost Analysis
| Measure | Algorithm R | Bottom-k with heap |
|---|---|---|
| Random numbers | one per item after the first k | one per item |
| Memory | k items | k items plus k keys and indices |
| Work per rejected item | O(1) | O(1) comparison |
| Work per accepted item | O(1) slot overwrite | O(log k) heap replace |
| Expected accepted items after the first k | about k ln(n/k) | about k ln(n/k) |
| Order of the final sample | arbitrary | sortable by key |
| Mergeable across partitions | no | yes |
The expected number of accepted items is identical for both methods, and the reason is the same. Item i (1-based, i > k) enters the heap only if its key is among the k smallest of the first i keys. That happens with probability k/i. Summing over i = k+1..n gives k(Hn − Hk) ≈ k ln(n/k). The total expected time is therefore O(n + k log k · log(n/k)). For n much larger than k, that is O(n) in practice, because the heap is rarely touched.
The threshold view also explains Algorithm L. The largest key in the heap, call it w, is the bar a new item must clear. A new key clears it with probability w, so the number of items skipped before the next acceptance is geometric with parameter w. Algorithm L draws that skip length directly and never generates keys for the skipped items. Its variable w is exactly this threshold.
Checking It Empirically
The same frequency test used for Algorithm R applies here:
import heapq
import random
from collections import Counter
def keyed_reservoir(stream, k, rng=random):
return heapq.nsmallest(k, ((rng.random(), item) for item in stream),
key=lambda pair: pair[0])
rng = random.Random(7)
trials = 100_000
counts = Counter()
for _ in range(trials):
for _, x in keyed_reservoir(range(10), 3, rng):
counts[x] += 1
for x in range(10):
print(x, round(counts[x] / trials, 4)) # each close to 0.3With 100,000 trials, the standard error for each frequency is about √(0.3 · 0.7 / 100000) ≈ 0.0014. Values between 0.296 and 0.304 are therefore normal.
Edge Cases and Gotchas
Ties and Floating-Point Keys
random.random() returns one of 2^53 evenly spaced values in [0, 1). Ties are possible but rare. For n items, the chance of any tie at all is about n²/2^54, which is roughly 5 × 10⁻⁵ at n = 10⁶. A tie only matters when it falls exactly at the k-th boundary. Even then, breaking it by index introduces a bias too small to measure. If you need exact guarantees at a very large scale, draw 64-bit integer keys with rng.getrandbits(64).
A key of exactly 0.0 is harmless here, because it just means "always keep." It does cause trouble in the weighted variant, where keys are raised to the power 1/w.
Keys Must Be Independent of the Items
Any correlation between keys and item content breaks uniformity. The usual mistake is to draw keys from RNGs with identical seeds on different workers. Every partition then generates the same key sequence, so item j on worker A and item j on worker B always get the same key. Seed each partition independently, for example with random.Random(base_seed * 1_000_003 + partition_id) or numpy.random.SeedSequence.spawn.
Hash-Based Keys: Deterministic Sampling
Sometimes you want the same items selected on every run, or across different datasets. A common example is sampling the same user IDs from two log streams so you can join them. Replace the random draw with a hash of the item:
import hashlib
import heapq
def hash_key(item: str, salt: str = "sample-v1") -> float:
digest = hashlib.blake2b((salt + item).encode(), digest_size=8).digest()
return int.from_bytes(digest, "big") / 2**64
def hashed_bottom_k(stream, k, salt="sample-v1"):
seen = {}
for item in stream:
seen.setdefault(item, hash_key(item, salt))
if len(seen) > 4 * k: # trim to keep memory bounded
seen = dict(heapq.nsmallest(k, seen.items(), key=lambda kv: kv[1]))
return heapq.nsmallest(k, seen.items(), key=lambda kv: kv[1])
print(hashed_bottom_k(["u1", "u2", "u3", "u1", "u4", "u5"], 2))The sample is now taken over distinct items. A repeated item always gets the same key, so it cannot take up two slots. This is the bottom-k sketch used for estimating distinct counts and set similarity. The method is uniform only as far as the hash behaves randomly, and it is deterministic, so anyone who knows the salt can predict which items will be chosen. Use Python's built-in hash() only if you have accounted for two facts: it is randomized per process for strings, and it is the identity for small integers.
When Not to Use Keys
If you need a single uniform sample from a single stream and never plan to merge it, Algorithm R is simpler and makes fewer random-number calls. If the stream is very long and random-number generation is the bottleneck, use Algorithm L. Choose random keys when you need any of the following:
- mergeable samples
- weights, which the next chapter covers
- a sample ordered by key
- deterministic, coordinated selection through hashing
Exercise
A stream of n = 1,000,000 items is sampled with bottom-k, k = 100. About how many heap replacements do you expect after the heap first fills, and roughly what is the largest retained key at the end?
Show answer
Replacements ≈ k ln(n/k) = 100 · ln(10,000) ≈ 100 · 9.21 ≈ 921. The largest retained key is the 100th smallest of 10^6 uniform values, whose expectation is k/(n+1) ≈ 1 × 10^-4. A new item at the end of the stream would be accepted with only about that probability.
Exercise
A colleague writes heapq.nsmallest(k, ((rng.random(), item) for item in stream)) without the key= argument, and the stream yields dicts. What can go wrong, and how often?
Show answer
When two keys are equal, tuple comparison falls through to comparing the dicts, which raises TypeError. Ties among 53-bit floats are rare (about n²/2^54 for any tie at all), so the bug can pass every test and then crash once in production. Fix it by passing key=lambda pair: pair[0] or by inserting a unique index as the second tuple element.
Exercise
Two workers each run bottomksample on half of a dataset, but both use random.Random(0). Explain why the union of their samples is not a uniform sample of the whole dataset.
Show answer
Both workers produce the same key sequence, so the j-th item of each partition gets the same key. Keys are then correlated across partitions. For example, the items at the same positions are kept or dropped together, and when the two halves are combined, some subsets can never be chosen while others are over-represented. Uniformity needs independent keys for all n items, so each partition needs an independent seed.