Sub topic 1
Streams: One Pass, Unknown Length, Limited Memory
Reservoir sampling solves one problem: picking a fair random sample from data that arrives as a stream. This chapter explains what a stream is, which operations a stream allows, and why those limits make sampling harder than calling random.sample on a list. The algorithms come in later chapters. This chapter defines the rules they have to follow.
Prerequisites
This chapter assumes you already know:
- Basic Python: loops, lists, functions, and the difference between an iterable and an iterator.
- Elementary probability: uniform distributions, independence, and conditional probability.
- Big-O notation for time and space.
- Proof by induction. It is not used here, but it becomes central two chapters from now.
You do not need any prior knowledge of streaming algorithms.
What Counts as a Stream
A data stream is a sequence of items x₁, x₂, x₃, … that your program sees one at a time, in order. You can look at each item when it arrives. After that, the item is gone unless you chose to store it.
Here are some real sources that behave this way:
- Lines of a log file too large to load into RAM.
- Network packets passing through a router.
- Rows returned by a database cursor that streams results.
- Messages consumed from a Kafka topic or a message queue.
- Sensor readings that never stop arriving.
In each case, the program sees the data through a narrow window. Python models this with iterators and generators: you call next() to get the next item, and you cannot go back.
The Three Constraints
The streaming model has three constraints. Each one rules out a familiar technique.
| Constraint | What it means | What it rules out |
|---|---|---|
| Single pass | Each item is seen once, in arrival order | Rereading the data, sorting it, random access by index |
| Unknown length | n is not known until the stream ends, and the stream may never end | Choosing random indices in advance, computing k/n up front |
| Bounded memory | State must be much smaller than n, ideally O(k) or O(1) | Buffering the whole stream and processing it afterwards |
Single pass
You get one look at each item. When you move on to x₍ₜ₊₁₎, you cannot ask for xₜ again unless you saved it. Random access, as in data[i], is not available.
Some sources do allow a second pass. You can reopen a file, for example. Even then a second pass often costs too much (rereading terabytes) or gives different results (a live table that changed in between). Streaming algorithms treat one pass as the only pass.
Unknown length
You don't know n while the stream is running. A file's size in bytes says nothing reliable about how many records it holds. A network feed has no defined end. Even when the stream does end, you only learn n at the moment the last item has gone by, and by then you have had to decide what to do with every earlier item.
This constraint is the one that makes sampling hard. If you knew n, you could pick k random indices ahead of time and keep the items at those positions. Without n, you cannot.
Bounded memory
The algorithm keeps some state: a few counters, a small buffer, maybe a heap. That state must stay small compared with n. "Small" usually means O(1) or O(k), where k is a size the user chooses and n can grow without limit. Memory that grows as O(n) breaks the model, because the stream can be longer than any machine's RAM.
Seeing the Constraints in Python
A Python generator is a faithful model of a stream. The generator below produces sensor readings until a random stopping event. Its length is unknown even to the code that wrote it.
import random
def sensor_readings(seed=0):
"""Yield temperature readings until a random stop (about 1000 on average)."""
rng = random.Random(seed)
while rng.random() > 0.001:
yield rng.gauss(20.0, 2.0)
stream = sensor_readings(seed=42)
try:
print(len(stream))
except TypeError as e:
print("No length available:", e)
first_pass = sum(1 for _ in stream)
second_pass = sum(1 for _ in stream)
print("first pass saw", first_pass, "items")
print("second pass saw", second_pass, "items") # 0: the iterator is exhaustedThe output shows two of the constraints directly. len() fails because a generator has no length. The second pass sees zero items because the first pass consumed them all. The only way to learn n was to read the entire stream, and after that the items were gone.
The Shape of a Streaming Algorithm
Every streaming algorithm has the same structure. It keeps a small state, updates that state once per item, and can answer a query from the state alone.
The class below computes the count, mean, variance, and maximum of a stream with this structure. It uses Welford's method for the variance, which updates the result with each item and never stores past values.
class RunningStats:
"""One-pass count, mean, variance, and max in O(1) memory."""
def __init__(self):
self.n = 0
self.mean = 0.0
self._m2 = 0.0
self.max = float("-inf")
def update(self, x):
self.n += 1
delta = x - self.mean
self.mean += delta / self.n
self._m2 += delta * (x - self.mean)
if x > self.max:
self.max = x
def variance(self):
return self._m2 / (self.n - 1) if self.n > 1 else 0.0
stats = RunningStats()
for t, x in enumerate(sensor_readings(seed=7), start=1):
stats.update(x)
if t % 250 == 0:
print(f"after {t} items: mean={stats.mean:.3f} var={stats.variance():.3f}")
print(f"final: n={stats.n} mean={stats.mean:.3f} max={stats.max:.3f}")Two properties of this code matter for the rest of the tutorial.
- Memory does not depend on n. The object holds four numbers whether the stream has ten items or ten billion.
- The answer is correct at every moment. After t items,
stats.meanis the exact mean of x₁ … xₜ. The stream can stop at any point and the state is already the right answer for what came in.
The second property is called the prefix invariant: after processing a prefix of the stream, the state is a correct answer for that prefix. Unknown length forces this property on you. If you can't tell whether the current item is the last one, the state has to be ready after every item.
Measuring the Memory Difference
The bounded-memory constraint is easy to state and easy to break by accident. The script below compares the peak memory of buffering a stream in a list against keeping running statistics.
import random
import tracemalloc
def numbers(n, seed=0):
rng = random.Random(seed)
for _ in range(n):
yield rng.random()
def peak_bytes(fn):
tracemalloc.start()
fn()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def buffer_everything():
data = list(numbers(1_000_000))
return sum(data) / len(data)
def stream_it():
total, count = 0.0, 0
for x in numbers(1_000_000):
total += x
count += 1
return total / count
print("buffered peak bytes:", peak_bytes(buffer_everything))
print("streamed peak bytes:", peak_bytes(stream_it))On a typical CPython build the buffered version peaks at tens of megabytes: each float object takes 24 bytes, plus an 8-byte pointer in the list. The streamed version peaks at a few hundred bytes. Multiply n by a thousand and the first version runs out of memory, while the second does not change.
Why Sampling Is Hard Under These Rules
Now apply the three constraints to the task this tutorial is about: keep k items chosen uniformly at random from the stream. The next chapter defines "uniformly" exactly. For now, it means every item has the same chance of ending up in the sample.
With a list, the task takes one line: random.sample(data, k). That call relies on every operation the streaming model forbids. It needs len(data) to know the range of indices. It needs random access to fetch the chosen positions. It needs the whole list in memory.
A streaming sampler has to make an immediate decision about each item: keep it or let it go. It has to do this without knowing how many items are still coming, using only O(k) memory, and with the prefix invariant holding. After t items, the k kept items must form a fair sample of x₁ … xₜ, because item t might be the last.
That final requirement is the hard part. Item 1 arrives when you know nothing about n. Whatever probability you give it of being kept has to come out right for n = 1, n = 100, and n = 10⁹ at once. The remaining chapters show that one simple rule meets this requirement, and they prove that it does.
Variations of the Model You May Meet
Streaming literature uses a few variations of the basic model. This tutorial uses the simplest one, but you should recognize the others.
| Model | Items | Used in this tutorial |
|---|---|---|
| Insertion-only (cash register) | Items only arrive and are never removed | Yes |
| Turnstile | Items can be inserted and deleted | No |
| Sliding window | Only the most recent W items count | No |
| Partitioned / distributed | Several streams are processed separately and combined | Yes, in a later chapter |
Reservoir sampling in its standard form assumes the insertion-only model. Deletions and sliding windows need different techniques, such as priority sampling with expiry, which are outside this tutorial.
Exercise
A colleague writes def sample(stream, k): idx = random.sample(range(len(stream)), k); return [stream[i] for i in idx]. List each streaming constraint this function violates, and say what happens if you call it with a generator.
Show answer
It violates all three. It needs the length (len(stream)), which a stream does not provide. It uses random access (stream[i]), which breaks the single-pass rule. It assumes the whole stream is held in an indexable container, which breaks bounded memory. Called with a generator, it raises TypeError: object of type 'generator' has no len().
Exercise
Which of these can be computed exactly in one pass with O(1) memory: (a) the sum, (b) the maximum, (c) the median, (d) the number of items greater than 0? Explain the one that cannot.
Show answer
Sum, maximum, and the count of positive items each need one or two numbers of state, so all three work. The exact median cannot be computed this way. Whether an earlier item turns out to be the median depends on items that have not arrived yet, so an exact one-pass algorithm must in the worst case remember Ω(n) items. Approximate quantile sketches get around this by accepting a bounded error.
Exercise
State the prefix invariant for a streaming sampler that keeps k items, and explain why unknown stream length forces it.
Show answer
After processing t items (for every t ≥ k), the k items in memory must be a uniform random sample of x₁ … xₜ. The sampler cannot tell whether item t is the last one, so if the state could be wrong at any t, a stream that happened to end at that t would produce a wrong answer.