Sub topic 14
Where Reservoir Sampling Fits in Practice
This chapter assumes you have read the earlier chapters. You should know Algorithm R, the k/n inclusion probability, the random-key method, and the idea of merging reservoirs. You also need basic Python and some comfort with estimating a statistic from a sample.
The earlier chapters covered how reservoir sampling works. This one is about when to use it. That means recognizing the problems it solves well, the problems it seems to solve but doesn't, and the simpler tools that are often a better choice.
The Conditions That Call for a Reservoir
Reservoir sampling is the right tool when all of these hold at the same time:
- You see each item once, or a second pass costs too much. Examples are network packets, log lines arriving over a socket, or a file too large to read twice.
- You don't know the total count in advance. If you knew n, you could pick k random indices up front and keep those items.
- You need a fixed-size sample. A downstream consumer, such as a dashboard, a human reviewer, or a model trainer, wants exactly k items, no matter whether the stream had a thousand items or a billion.
- Every item should have the same chance of selection, or a chance proportional to a known weight if you use A-Res.
If any of these is missing, a simpler method usually works better. The table below compares the common alternatives.
| Method | Needs n in advance | Sample size | Memory | Typical use |
|---|---|---|---|---|
| `random.sample` on a list | Yes (data in memory) | Exactly k | O(n) | Data already loaded |
| Pick k random indices, then scan | Yes | Exactly k | O(k) | Files or tables with a known row count |
| Bernoulli sampling (keep each item with probability p) | No | Random, about pn | Unbounded as n grows | Tracing a fixed fraction of requests |
| Reservoir sampling (Algorithm R or L) | No | Exactly k | O(k) | Fixed-size sample of an unbounded stream |
| Shuffle buffer (as in `tf.data`) | No | Streams all items | O(buffer) | Partial shuffling for training, not uniform |
The Bernoulli row matters most in practice. Bernoulli sampling is often the right answer when you want a rate, for example "trace 1% of requests," instead of a count. Its output grows with traffic, and that is fine when storage scales with traffic too. Reservoir sampling is the better fit when the budget is fixed, for example "show 100 example errors from today."
Typical Applications
Sampling Logs and Events for Inspection
A service writes millions of error events per day, and an engineer wants 50 representative ones to read. If you take the first 50, they all come from the morning. If you take the last 50, they all come from the most recent incident. A reservoir of size 50 gives every event the same chance, so a noisy hour shows up in proportion to its volume and does not crowd out the rest of the day.
A common pattern is one reservoir per key, such as per error type or per endpoint, stored in a dictionary. Memory is O(k × number of keys), so you must bound the number of keys too.
Estimating Statistics Over a Stream
A uniform sample supports estimates of quantiles, means, and proportions without storing the stream. The example below simulates request latencies, keeps a reservoir of 1,000, and compares the sample's percentiles to the true values.
import random
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
def percentile(values, p):
s = sorted(values)
idx = min(len(s) - 1, int(p * len(s)))
return s[idx]
rng = random.Random(42)
n = 500_000
# Latencies in ms: mostly fast, with a slow tail
latencies = [rng.expovariate(1 / 20) + (200 if rng.random() < 0.02 else 0)
for _ in range(n)]
sample = reservoir_sample(iter(latencies), 1_000, rng=random.Random(7))
for p in (0.50, 0.95, 0.99):
print(f"p{int(p * 100)}: true={percentile(latencies, p):7.1f} "
f"sample={percentile(sample, p):7.1f}")The median and p95 estimates land close to the true values. The p99 estimate is noisier, because only about 10 of the 1,000 sampled items lie above it. This is a general rule: the further into the tail you look, the larger k has to be. If tail quantiles are your main goal, a quantile sketch such as t-digest or KLL gives tighter error bounds per byte of memory.
To estimate a total instead of a proportion, scale up. If 37 of the k sampled items are errors and the stream had n items, the estimate is 37 × n / k. You still need n, but a single integer counter tracks it at no real cost.
Picking a Random Line From a Large File
Choosing a random line from a multi-gigabyte file with unknown line count takes one pass with the size-one reservoir. Command-line tools such as shuf -n use reservoir sampling when the input comes from a pipe.
Database and Query Engines
Query engines use reservoir sampling to build statistics for the query planner, such as histograms of column values, and for operators that return a fixed number of random rows. PostgreSQL's ANALYZE reads a sample of table blocks and then applies reservoir sampling to the rows in them. Distributed engines build one reservoir per partition and merge them with the random-key method from the previous chapter.
Training Data Selection
When training data arrives as a stream of examples, a reservoir can maintain a fixed-size, uniformly drawn evaluation set or a replay buffer. In continual learning, "reservoir replay" keeps a uniform sample of everything seen so far, which reduces forgetting of older data.
When Reservoir Sampling Is the Wrong Tool
You Need Recent Data, Not All Data
Algorithm R gives the millionth item the same chance as the first. On a long-running stream, each new item is accepted with probability k/n, which shrinks toward zero. After a week, the reservoir mostly reflects history and reacts slowly to a change in behavior. For "a sample of the last hour," look at these options instead:
- Sliding-window sampling, such as chain sampling or priority sampling over a window, which handles expiring items.
- Time-decayed weights with A-Res, where newer items get larger weights. A common approach sets the weight to exp(λt) and works in log space to avoid overflow.
- Periodic resets: start a fresh reservoir every hour. This is simple and often good enough.
The Data Has Deletions
If items can be removed later, such as cancelled orders or retracted events, a plain reservoir cannot repair itself. When a sampled item is deleted, nothing is left to replace it with. Methods such as random pairing were designed for streams with inserts and deletes.
You Need Aggregates, Not Examples
A count of distinct users, the heaviest hitters, or a frequency per key are better answered by sketches:
| Question | Better tool |
|---|---|
| How many distinct items? | HyperLogLog |
| How often does item x appear? | Count-Min Sketch |
| Which items are most frequent? | Misra–Gries, Space-Saving |
| What is the 99.9th percentile? | t-digest, KLL |
| Show me representative raw records | Reservoir sampling |
A reservoir is the general-purpose option: it keeps real records, so you can ask questions you didn't plan for. Specialized sketches give better accuracy for the one question they were built to answer.
Rare Groups Matter
A uniform sample of 1,000 from a stream where one customer tier makes up 0.1% of traffic contains about one item from that tier. If you need every group represented, use stratified sampling: keep a separate reservoir per group, or use weights that give rare groups a larger share. Remember to reweight when you compute overall estimates from such a sample.
A Decision Guide
The last choice between Algorithm R and Algorithm L depends on cost. If each item has already been parsed by the time you see it, the random-number savings of Algorithm L are small compared with the parsing. If the source can skip items cheaply, as with fixed-width records you can seek past, Algorithm L avoids touching most of the stream.
Operational Concerns
- Reproducibility. Pass a seeded
random.Randominstance into the sampler so a sample can be regenerated for debugging. For security-sensitive sampling, such as audit selection where users must not predict which items get checked, userandom.SystemRandomorsecrets. - Checkpointing. A long-running sampler's state is the reservoir, the count n, and the RNG state, plus the next-skip value for Algorithm L. Save all of them. If you restore the reservoir but reset n to zero, every later item is accepted far too often.
- Item size. O(k) memory means k items. If items are large, store references or the selected fields only.
- Privacy. A sample contains real records. Retention and access rules for the full data apply to the sample too.
Exercise
A monitoring system wants to show 20 example slow requests from the current day, and the dashboard refreshes at midnight. Traffic is about 50 million requests per day, but varies by a factor of 10. Should it use Bernoulli sampling or a reservoir, and what state must survive a process restart?
Show answer
Use a reservoir of size 20, reset at midnight. The output size must be fixed at 20 no matter how much traffic arrives, and Bernoulli sampling with any fixed p would return a number that varies tenfold with traffic. To survive a restart, save the reservoir contents, the count n of slow requests seen so far today, and the RNG state. If n is lost and reset to zero, the following items are accepted with too high a probability and the sample is biased toward the time after the restart.
Exercise
A reservoir of k = 500 drawn uniformly from a stream of n = 2,000,000 events contains 35 events flagged as fraud. Estimate the total number of fraud events, and explain why a stratified design might be better if fraud makes up only 0.01% of events.
Show answer
The estimate is 35 × 2,000,000 / 500 = 140,000. At a 0.01% rate, a uniform sample of 500 would contain about 0.05 fraud events on average, so most samples would contain none and the estimate would be either 0 or very large. Keeping a separate reservoir for flagged events, or giving them a larger weight, ensures they are represented. You then reweight each stratum by its own count when estimating totals.
Exercise
A training pipeline uses a shuffle buffer of size 10,000 on a stream of 10 million examples and keeps the first 100,000 outputs as a "random subset." Is that subset uniform over the whole stream? What should be used instead?
Show answer
No. A shuffle buffer only mixes items that are near each other in the stream. The first 100,000 outputs come almost entirely from roughly the first 110,000 input items, so later data is excluded. Use a reservoir of size 100,000 over the full stream, or pick random indices if the stream length is known.