Skip to main content
← CONCEPTS / DATA-STRUCTURES-ALGORITHMS
An end-to-end domain learning journey

Vitter's Algorithm L
Reservoir Sampling.

Standard Reservoir Sampling (Algorithm R) generates N random numbers for a stream of N items, bottlenecking CPU on 100M+ event streams.
Start the journey4 sections
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Vitter's Algorithm L samples the exact geometric gap S between accepted items using W = W * exp(log(u)/k), cutting PRNG calls from N to O(k(1 + log(N/k))).

TL;DR30-second simplified summary
▾

For k=1,000 and N=1,000,000,000, Algorithm R makes 10^9 PRNG calls while Algorithm L makes ~14,000—a 70,000x reduction in RNG work.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Algorithm R Uniformity Invariant
At stream index i > k, item x_i is included with probability k/i and replaces a uniformly random slot in R[0..k-1].
Inverse Transform Sampling
Drawing u ~ Uniform(0,1) and computing floor(log(u)/log(1-W)) samples a geometric skip distance in O(1).
Full walkthrough · 4 stages
01
L4 · FUNDAMENTALS

P — The O(N) PRNG Bottleneck in Algorithm R.

Algorithm R vs. Vitter's Algorithm L

Before · Algorithm R (1 RNG/item)
After · Algorithm L (Geometric Skip)

Suppose a network telemetry agent monitors N = 10^9 packets/hour and maintains a uniform sample of k = 1,000 packets. Algorithm R calls randInt(0, i) on every single packet, even when i = 500,000,000 and the acceptance probability k/i is 0.0002%.

At 10–15 ns per cryptographic or thread-safe PRNG call, 10^9 draws burn 10–15 seconds of pure RNG overhead per billion events—more expensive than parsing the packet header itself.

02
L4 · FUNDAMENTALS

R — Geometric Skip Distribution.

Algorithm L Skip-and-Replace Loop

Instead of asking 'is item i accepted?' one item at a time, Vitter's Algorithm L asks: how many items S will be skipped before the next item is accepted into the reservoir?

After each acceptance, the effective inclusion probability threshold W decays via W <- W * exp(log(u) / k) (where u ~ Uniform(0, 1)), and the next skip count is S = floor(log(u2) / log(1 - W)). The algorithm simply increments a counter until S items pass, then replaces R[rand(0, k-1)].

03
L5 · APPLIED DESIGN

I — Production Python Implementation of Algorithm L.

Algorithm L Execution Trace (k=3)

Input StreamSkip Counter SReservoir R[0..2]1. Load x1, x2, x32. Sample S=4, advance 4 items3. x8 replaces R[rand(0,2)]4. Update W, sample S=11
Engineering Decision Framework
Problem
Which reservoir sampling algorithm should be used for a 100M+ event/min telemetry stream?
Naive Solution
Run Algorithm R, calling the PRNG on every incoming event.
Why It Fails
Algorithm R performs Theta(N) PRNG calls, wasting CPU on millions of rejected events.
Alternatives
Algorithm R (O(N) PRNG calls),Vitter's Algorithm L (O(k(1 + log(N/k))) PRNG calls),Fixed modulo sampling (every 1000th event)
Engineering Decision
Use Vitter's Algorithm L for unweighted uniform sampling when N >> k.
Trade-Offs
Requires floating-point log/exp per accepted item, but amortizes to negligible cost as N grows.
Decision Exercise · Make the Call

Why does Algorithm L use math.log1p(-w) instead of math.log(1 - w) when N is very large?

Careful implementations guard random.random() against 0.0 (since log(0) raises ValueError) and use math.log1p(-w) for numerical stability when W becomes tiny (W < 1e-9):

import math
import random
from typing import Iterable, List, TypeVar

T = TypeVar("T")

def reservoir_sample_l(stream: Iterable[T], k: int, rng: random.Random) -> List[T]:
    if k <= 0:
        raise ValueError("Reservoir size k must be positive")
    it = iter(stream)
    reservoir: List[T] = []
    for _ in range(k):
        try:
            reservoir.append(next(it))
        except StopIteration:
            return reservoir

    def uniform_pos() -> float:
        u = rng.random()
        return u if u > 0.0 else 1e-16

    w = math.exp(math.log(uniform_pos()) / k)
    while True:
        skip = math.floor(math.log(uniform_pos()) / math.log1p(-w))
        for _ in range(skip):
            try:
                next(it)
            except StopIteration:
                return reservoir
        try:
            candidate = next(it)
        except StopIteration:
            return reservoir
        reservoir[rng.randrange(k)] = candidate
        w *= math.exp(math.log(uniform_pos()) / k)
04
L5 · APPLIED DESIGN

M & E — Complexity Proof & When Not to Use Algorithm L.

Algorithm L Operational States

len(R) == kS == 0Compute next SFILL_INITIAL_KSKIP_S_ITEMSSWAP_AND_DECAY_W

Each accepted item multiplies W by a factor whose expected value is k / (k + 1), so the expected number of accepted items out of N is k * H_N = O(k(1 + log(N/k))). Each accepted item triggers 3 PRNG draws (u1 for S, rand(0,k-1) for slot, u2 for W), keeping total RNG work logarithmic in N/k.

When NOT to use Algorithm L: If elements have non-uniform weights (e.g., sampling by request latency or dollar value) or if you need a sliding-window / time-decayed sample, Algorithm L's uniform skip assumption breaks—use Efraimidis-Spirakis (key = u^(1/w)) instead.

Recommended Learning Flow