Sub topic 3
Why Storing Everything or Using a Fixed Probability Fails
This chapter assumes you know basic Python, including generators and random.Random. It also assumes you are comfortable with binomial probabilities, and that you understand the stream constraints and the definition of a uniform sample from the previous two chapters. In short, a stream is read once, its length n is unknown until it ends, and you can only hold O(k) items. A uniform sample of size k without replacement gives every k-subset the same probability. As a result, each item lands in the sample with probability k/n.
The obvious ways to sample a stream each break one of these rules. Looking at exactly which rule each one breaks tells you what a correct algorithm has to do.
The Requirements, Stated as a Checklist
A correct streaming sampler must satisfy all of the following at once:
- It reads each item once, in order, and never goes back.
- It uses
O(k)memory, independent ofn. - It returns exactly
min(k, n)items. - It gives each item inclusion probability
k/n, and more strongly, everyk-subset is equally likely. - It does not need to know
nin advance.
Every naive approach below fails at least one of these.
Approach 1: Store Everything, Then Sample
The simplest correct-looking answer is to collect the stream into a list and call random.sample.
import random
def sample_by_storing(stream, k, rng=random):
items = list(stream) # materializes the whole stream
return rng.sample(items, min(k, len(items)))
print(sample_by_storing(range(1_000), 5, random.Random(1)))The output is perfectly uniform, so requirement 4 holds. The cost is memory. list(stream) holds all n items, which violates requirement 2. That is fine for a thousand integers and impossible for a firehose of log lines, a network packet capture, or an unbounded event feed. The program will run until it exhausts RAM, and if the stream never ends, it never returns.
A variant stores everything on disk instead of in memory. That moves the problem without solving it: you now need O(n) storage and a second pass to read the data back.
Approach 2: Keep Each Item with Fixed Probability p
The next idea is Bernoulli sampling: flip a biased coin for each item and keep it with probability p. It uses one pass, needs no lookahead, and every item has the same inclusion probability p.
import random
def bernoulli_sample(stream, p, rng=random):
return [x for x in stream if rng.random() < p]
rng = random.Random(42)
sizes = [len(bernoulli_sample(range(1_000), 0.01, rng)) for _ in range(10_000)]
print("min size:", min(sizes))
print("max size:", max(sizes))
print("fraction with exactly 10:", sum(s == 10 for s in sizes) / len(sizes))You picked p = 0.01 hoping for 10 items out of 1,000. The sample size is not 10. It follows a Binomial(n, p) distribution with mean np = 10 and standard deviation sqrt(np(1-p)) ≈ 3.15. The chance of getting exactly 10 is only about 12.5%. Runs commonly return anywhere from 3 to 20 items. This violates requirement 3.
The deeper problem is that a good p depends on n. To expect k items you need p = k/n, and you don't know n. A wrong guess fails badly:
| True stream length n | p chosen for n = 1,000, k = 10 | Expected sample size | What goes wrong |
|---|---|---|---|
| 10 | 0.01 | 0.1 | Empty sample about 90% of the time (0.99^10 ≈ 0.904) |
| 1,000 | 0.01 | 10 | Size varies roughly 4 to 16 |
| 1,000,000 | 0.01 | 10,000 | Memory grows linearly with n, which breaks requirement 2 |
Memory is also unbounded. The sample grows as pn, so for any fixed p > 0 it grows linearly with n.
Approach 3: Bernoulli, Then Truncate to k
A natural patch is to oversample with a generous p and stop once you have k items. That caps both memory and size, but it destroys uniformity.
import random
from collections import Counter
def bernoulli_then_truncate(stream, k, p, rng=random):
out = []
for x in stream:
if rng.random() < p:
out.append(x)
if len(out) == k:
break
return out
rng = random.Random(7)
trials = 50_000
counts = Counter()
for _ in range(trials):
for x in bernoulli_then_truncate(range(100), 5, 0.2, rng):
counts[x] += 1
for i in (0, 10, 20, 50, 99):
print(i, round(counts[i] / trials, 4))A uniform sampler would give every item probability 5/100 = 0.05. Here, item i is kept only if its coin comes up heads and at most 4 earlier items were already kept. That gives 0.2 × P(Binomial(i, 0.2) ≤ 4):
| Item index | Theoretical inclusion probability | Uniform target |
|---|---|---|
| 0 | 0.200 | 0.05 |
| 10 | 0.193 | 0.05 |
| 20 | 0.126 | 0.05 |
| 50 | 0.0037 | 0.05 |
| 99 | ≈ 0 | 0.05 |
Early items are four times overrepresented and late items almost never appear. Any rule of the form "fill up, then stop" has this bias toward the front of the stream. The same flaw shows up in a common production bug: sampling the "first few" events after a deploy and treating them as representative of the whole day.
Approach 4: First k or Last k
Keeping the first k items (itertools.islice(stream, k)) or the last k (collections.deque(stream, maxlen=k)) uses O(k) memory and returns exactly k items. It is deterministic, though. Item i has inclusion probability 1 or 0 depending only on its position. If the stream is sorted, time-ordered, or grouped by source, which real streams usually are, the sample shows only one slice of the data.
Approach 5: Pick Random Indices in Advance
If you knew n, you could draw k distinct indices with random.sample(range(n), k), put them in a set, and keep the items at those positions in a single pass. This is uniform, uses O(k) memory, and is a perfectly good algorithm when n is known. Requirement 5 is exactly what rules it out.
The workaround is two passes: count the items first, then sample. This fails in several practical ways:
- Many streams cannot be replayed: sockets, stdin, Kafka topics past retention, Python generators.
- Replayable sources still cost double the I/O, which dominates when the data sits on disk or across a network.
- The data can change between passes. A growing log file has more lines on the second pass, so the indices you drew refer to a different population.
Systematic sampling ("keep every m-th item") has the same dependency, since m = n/k needs n. It adds a second problem: if the data has a periodic pattern aligned with m, the sample can miss whole categories.
Approach 6: Random Key, Then Sort
You can attach a uniform random number to each item, sort by it, and take the first k. This is uniform, because a random key order is a uniformly random permutation. Done naively, though, it stores and sorts all n keyed items: O(n) memory and O(n log n) time. A later chapter shows that you only need to keep the k smallest keys seen so far, which turns this idea into a valid reservoir method. The naive version still fails requirement 2.
Comparing the Failures
| Approach | Memory | Needs n? | Passes | Exactly min(k, n) items? | Uniform? |
|---|---|---|---|---|---|
| Store everything | O(n) | No | 1 (plus storage) | Yes | Yes |
| Bernoulli with fixed p | O(pn) | To choose p | 1 | No | Per item, yes |
| Bernoulli then truncate | O(k) | To choose p | 1 | Usually | No, front-biased |
| First k / last k | O(k) | No | 1 | Yes | No, deterministic |
| Pre-drawn indices | O(k) | Yes | 1 if n known, else 2 | Yes | Yes |
| Sort by random key (naive) | O(n) | No | 1 | Yes | Yes |
What a Correct Algorithm Must Do
Because the stream can end at any moment, the sample must be a correct uniform sample of the items seen so far after every single item. After i items, each item must be in the sample with probability k/i. That target keeps falling as i grows. No fixed p can match it, which is why Bernoulli sampling fails. Front-biased rules ignore it, and storing everything only delays the decision until the end.
So a correct sampler has to give the i-th item a probability that depends on i, and when a new item is admitted it has to evict an existing one in a way that keeps the older items balanced. The next chapter builds this for k = 1. The chapter after that extends it to Algorithm R.
Exercise
You run Bernoulli sampling with p = 0.05 on a stream that turns out to have n = 40 items, hoping for about k = 2 items. What is the probability the sample is empty, and what is the probability it has more than 2 items?
Show answer
The sample size is Binomial(40, 0.05). P(0) = 0.95^40 ≈ 0.129. P(1) = 40 × 0.05 × 0.95^39 ≈ 0.271 and P(2) = 780 × 0.0025 × 0.95^38 ≈ 0.278, so P(more than 2) = 1 − 0.129 − 0.271 − 0.278 ≈ 0.322. About one run in eight returns nothing, and about one in three returns too many.
Exercise
In bernoullithentruncate with k = 5 and p = 0.2, why is item 0 included with probability 0.2 rather than 0.05, and what would happen to the bias if you raised p to 0.9?
Show answer
Item 0 is always within the first k selected items, so it is kept whenever its own coin succeeds, which happens with probability p = 0.2. Raising p to 0.9 makes the bias worse: the first five items are kept about 90% of the time and nearly everything after about index 7 is almost never kept. The result is close to the deterministic "first k" sampler.
Exercise
A colleague proposes reading a log file once to count lines, drawing k random line numbers, then reading it again to collect those lines. Give two concrete situations where this produces a wrong or impossible result.
Show answer
First, if the file is still being appended to, the second pass sees more lines than were counted, so the new lines can never be sampled and the sample is not uniform over the final file. Second, if the input is a pipe, a socket, or a generator, it cannot be read twice, so the second pass is impossible. Rotated or truncated logs and doubled I/O cost on large remote files are also valid answers.