Inferensys

Glossary

Reservoir Sampling

Reservoir sampling is a randomized algorithm for selecting a simple random sample of fixed size from a data stream of unknown length, often used to implement replay buffers for non-stationary data streams.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
ALGORITHM

What is Reservoir Sampling?

Reservoir sampling is a foundational randomized algorithm for selecting a fixed-size, unbiased sample from a data stream of unknown or infinite length, with each item having an equal probability of being included in the final sample.

Reservoir sampling is a family of randomized algorithms designed to select a simple random sample of k items from a data stream where the total number of items n is unknown or too large to store. The core algorithm, Algorithm R, maintains a reservoir (a buffer) of size k. It includes the first k items directly. For each subsequent item i (where i > k), it replaces a randomly selected item in the reservoir with probability k/i. This ensures every item in the stream has an equal final probability of selection, precisely k/n.

In machine learning, reservoir sampling is critical for implementing experience replay buffers in online and continual learning systems. It provides a memory-efficient mechanism to maintain a representative, unbiased sample of past data in non-stationary streams. This allows models to revisit and learn from historical experiences, mitigating catastrophic forgetting by interleaving old and new data during training. Its O(n) time and O(k) space complexity make it ideal for production systems processing endless data.

ALGORITHMIC FOUNDATIONS

Key Properties of Reservoir Sampling

Reservoir sampling is defined by a set of core mathematical and computational properties that make it uniquely suited for streaming data and implementing replay buffers. These properties guarantee its correctness and efficiency.

01

Single-Pass Guarantee

The algorithm processes each data point exactly once, in the order it arrives, without requiring prior knowledge of the total stream length N. This makes it memory-efficient for infinite or very large streams where storing all data is impossible.

  • Mechanism: It maintains a reservoir of size k. For each new element at index i, it is included with probability k/i. If selected, it randomly replaces an existing element in the reservoir.
  • Implication: Essential for online learning and real-time data streams, as it operates with constant memory O(k) beyond the reservoir itself.
02

Uniform Random Sample

When the stream ends, every possible subset of size k from the N total elements has an equal probability of being the final reservoir. This ensures a simple random sample without replacement.

  • Proof: The probability any specific element is in the final reservoir is k/N. For a proof, consider the inductive logic: the probability an element at position i is in the reservoir at that time is k/i. It then must survive all subsequent replacement attempts (i+1...N), each with probability 1 - k/j * 1/k = (j-1)/j. The product telescopes to k/N.
  • Critical For: Statistical validity in experience replay, ensuring the buffer does not introduce temporal bias.
03

Constant Time Per Element

The algorithm runs in O(1) amortized time per stream element, independent of the stream length or reservoir size. The core operation involves a random number generation and a potential array replacement.

  • Operation: For element i, generate a random integer j from [0, i). If j < k, replace reservoir[j] with the new element.
  • Efficiency: This predictable, low-cost per-item processing is why it's favored for high-throughput data pipelines and integrating into tight reinforcement learning training loops.
04

Adaptive to Stream Length

The inclusion probability k/i automatically adjusts as the stream progresses. Early elements have a high chance of entering the reservoir but a high chance of later being replaced.

  • Early Stream: When i <= k, all elements are included with probability 1 (the reservoir is filling).
  • Late Stream: As i grows large, the probability a new element enters the sample becomes very small (≈ k/i).
  • Application: In non-stationary environments, this property can be modified (e.g., with a decaying probability) to bias the sample toward more recent experiences, creating a sliding window effect within the reservoir.
05

Algorithm R (The Classic Version)

Algorithm R is the standard, in-place implementation. It is the reference for understanding all reservoir sampling variants.

Pseudocode:

python
# Initialize: fill reservoir with first k elements
reservoir = stream[:k]

for i in range(k, N):
    j = random.randint(0, i)  # inclusive range [0, i]
    if j < k:
        reservoir[j] = stream[i]
  • Key Detail: The random integer must be drawn from an inclusive range [0, i]. This ensures the correct probabilities.
  • Foundation: This algorithm is the basis for weighted reservoir sampling and distributed reservoir sampling extensions.
06

Link to Replay Buffers

In reinforcement learning, a replay buffer is often implemented as a circular buffer (FIFO). Reservoir sampling provides a statistically rigorous alternative or complement.

  • Uniform vs. FIFO: A simple FIFO buffer is a deterministic sample of the most recent k experiences. Reservoir sampling provides a uniform random sample of all N experiences seen, preserving information from earlier in training.
  • Hybrid Approaches: Prioritized Experience Replay (PER) modifies the sampling distribution away from uniform. Reservoir sampling can be viewed as the uniform baseline (p=1) before priorities are applied.
  • Use Case: In continual learning, a reservoir sampling-based buffer helps mitigate catastrophic forgetting by ensuring a model revisits a representative sample of past tasks.
REPLAY BUFFER SAMPLING

Reservoir Sampling vs. Alternative Sampling Methods

A comparison of sampling algorithms used to select experiences from a replay buffer for training machine learning models on non-stationary data streams.

FeatureReservoir SamplingUniform Random Sampling (FIFO)Prioritized Experience Replay (PER)

Algorithm Type

Online, single-pass

Offline, multi-pass

Online/Offline, multi-pass

Memory Complexity

O(k) for sample size k

O(n) for buffer size n

O(n) for buffer size n

Time Complexity per Item

O(1)

O(1) for insertion, O(1) for sampling

O(log n) for insertion & sampling (heap)

Sample Guarantee

True uniform random sample of stream seen so far

Uniform sample of current buffer contents only

Sample proportional to temporal-difference (TD) error

Handles Unknown Stream Length

Requires Full Buffer Pass for Sample

Varies (requires priority update)

Bias Correction Required

Primary Use Case

Streaming data, unknown total N, replay buffer maintenance

Stationary data, simple replay buffers (e.g., DQN)

Reinforcement learning, focusing on informative transitions

Key Advantage

Uniform sample from entire history with fixed memory

Simplicity and speed

Faster learning via focused sampling on high-error experiences

RESERVOIR SAMPLING

Frequently Asked Questions

Reservoir sampling is a foundational algorithm for unbiased sampling from data streams. These FAQs address its core mechanics, applications in machine learning, and practical implementation details.

Reservoir sampling is a family of randomized algorithms designed to select a simple random sample of k items from a data stream of unknown (or very large) length n, where every subset of size k has an equal probability of being chosen. The classic Algorithm R works by initially filling a 'reservoir' array with the first k items from the stream. For each subsequent item i (where i > k), the algorithm generates a random integer j uniformly from 1 to i. If j ≤ k, the item at reservoir position j is replaced with the new stream item i. This process guarantees that after processing the entire stream, each item has a probability of exactly k/n of being in the final reservoir.

Key Property: The algorithm processes the stream in a single pass, requiring only O(k) memory, which is independent of the total stream size n.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.