Sub topic 14
Where Reservoir Sampling Fits in Practice
This chapter assumes you know Algorithm R, its O(n) time and O(k) space cost, and the random-key, weighted, and merging variants from earlier chapters. The aim here is judgment: when reservoir sampling is the right tool, and when something simpler or different works better.
Typical Uses
Reservoir sampling helps whenever data arrives faster than you can store it, or the total count isn't known until the end.
| Use case | Why a reservoir fits | Variant |
|---|---|---|
| Sampling log lines or requests for debugging | Volume is unbounded and you want a fixed-size, unbiased sample | Algorithm R |
| Picking random lines from a huge file in one read | You don't know the line count, and a second pass is expensive | Algorithm R or L |
| Training-data subsampling from a data pipeline | You need a fixed budget of examples from an iterator | Algorithm L for long streams |
| Monitoring dashboards with "show me 100 recent examples" | Memory is bounded per metric or key | Algorithm R per key |
| Sampling by importance (bytes, revenue, latency) | Larger items should be more likely to appear | A-Res |
| Sampling across shards or workers | Each partition samples locally, then results combine | Random keys plus merge |
A Practical Example
A command-line tool that prints k random lines from standard input covers the most common real-world case. It works on piped input of any size.
import random
import sys
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
if __name__ == "__main__":
k = int(sys.argv[1]) if len(sys.argv) > 1 else 10
for line in reservoir_sample(sys.stdin, k):
sys.stdout.write(line)Run it as cat access.log | python sample_lines.py 20. Memory stays at 20 lines however large the log is.
Choosing an Approach
When Not to Use It
- Small, in-memory data. If you already have a list,
random.sample(data, k)is clearer and just as correct. - Recency matters. A reservoir gives every item since the start an equal chance, so old data never ages out. If you want "a sample of the last hour," use a sliding-window method or reset the reservoir on a schedule.
- You need aggregates, not examples. For counts, distinct counts, or quantiles, sketches like Count-Min, HyperLogLog, or t-digest are more accurate per byte than estimating from a sample.
- Rare events. A uniform sample of 1,000 items from a billion will probably miss an event that happens 50 times. Use stratified sampling (one reservoir per category) or weighting instead.
Exercises
Exercise
You need 500 sample requests per API endpoint from a service handling 200 endpoints, and you want samples to reflect only the current day. What design do you use?
Show answer
Keep one Algorithm R reservoir of size 500 per endpoint (200 × 500 = 100,000 items at most), and reset all reservoirs at midnight so old requests don't stay in the sample.
Exercise
A batch job runs on 64 workers, each reading part of a dataset, and you want one uniform sample of 1,000 rows overall. Why can't each worker run Algorithm R and you keep 1,000 rows picked at random from the combined results?
Show answer
Partitions differ in size, so a row from a small partition would be overrepresented. Have each worker keep its 1,000 rows with the smallest uniform random keys, then merge by taking the 1,000 smallest keys across all workers.