Inferensys

Glossary

Reservoir Sampling

Reservoir sampling is a randomized algorithm for selecting a simple random sample of k items from a data stream of unknown length n, where every item has an equal probability of being included.
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 online learning and streaming data systems.

Reservoir sampling is a randomized algorithm for selecting a simple random sample of k items from a data stream of unknown or very large length n, where every item has an equal probability (k/n) of being included in the final sample. It is a cornerstone technique for maintaining a fixed-size replay buffer in continual learning systems, enabling models to efficiently retain and revisit representative past experiences without requiring prior knowledge of the total data volume.

The classic Algorithm R fills the reservoir with the first k stream elements. For each subsequent element i (where i > k), it generates a random integer j between 1 and i; if j ≤ k, the new element replaces the item at position j in the reservoir. This elegant process ensures the uniform sampling property. Its primary use in machine learning is within experience replay mechanisms for online and reinforcement learning, where it provides a statistically sound method for managing memory under constraints.

RESERVOIR SAMPLING

Key Features and Properties

Reservoir sampling is a family of randomized algorithms designed to select a simple random sample from a data stream of unknown or infinite length, ensuring every item has an equal probability of inclusion. Its core properties make it indispensable for online learning and streaming analytics.

01

Single-Pass Algorithm

The defining characteristic of reservoir sampling is its single-pass nature. It processes each item in the stream exactly once, requiring only O(k) memory to hold the reservoir of size k. This makes it impossible to store the entire stream, which is essential for applications like:

  • Maintaining a replay buffer for continual learning.
  • Sampling from live network traffic or sensor feeds.
  • Log sampling in high-throughput distributed systems.
02

Equal Probability Guarantee

The algorithm's core guarantee is that every item seen in the stream has an identical probability of being in the final sample. For a stream of length n and reservoir size k, the probability for any item is exactly k/n. This property holds even though n is unknown when processing begins. It ensures a statistically unbiased simple random sample, which is critical for:

  • Creating representative training datasets from non-stationary streams.
  • Fairly selecting experiences for reinforcement learning replay.
  • Providing valid inputs for downstream statistical tests.
03

Algorithm R (The Classic)

Algorithm R is the foundational, straightforward implementation.

  • Initialization: Fill the reservoir with the first k items from the stream.
  • Inductive Step: For each incoming item i (where i > k), generate a random integer j uniformly from 1 to i. If j ≤ k, replace the j-th item in the reservoir with the new item.
  • Complexity: The time complexity is O(n), and it requires k random numbers to be generated. While simple, it can be inefficient for very large n due to the random number generation for every item.
04

Algorithm L (Optimized for Large n)

Algorithm L introduces a key optimization to reduce the number of random number generations. Instead of checking every item, it uses skip intervals.

  • It calculates how many items to skip before the next replacement, based on a geometric distribution.
  • This reduces the number of random variate generations from O(n) to O(k log(n/k)) on average.
  • It is the algorithm of choice for extremely long streams (e.g., sampling from petabytes of log data) where the cost of random number generation becomes a bottleneck.
05

Weighted Reservoir Sampling

A crucial extension where each item i has an associated weight w_i. The goal is to sample such that the probability of selecting an item is proportional to its weight. Common algorithms include:

  • Algorithm A-Res: Uses a key u_i^(1/w_i) for each item, where u_i is a uniform random number. It maintains the k items with the largest keys.
  • Algorithm A-ExpJ: An optimized version that reduces computational cost.
  • Use Case: Essential for importance sampling in online learning, where recent or high-loss data points should be sampled with higher probability for replay.
06

Distributed & Parallel Variants

Reservoir sampling can be scaled to parallel and distributed streams.

  • Parallel/Distributed Sampling: Each node (or thread) maintains its own reservoir of size k from its local stream. The final reservoir is created by performing a second round of reservoir sampling on the merged outputs from all nodes.
  • Use Case: Sampling from sharded databases, distributed log aggregators (like Apache Kafka topics), or federated learning nodes where data cannot be centralized. This preserves the equal-probability guarantee across the entire global dataset.
COMPARISON

Reservoir Sampling Algorithm Variants

A comparison of core algorithmic variants for selecting a simple random sample of k items from a data stream of unknown length n, highlighting their computational trade-offs and use cases in continuous learning systems.

Algorithmic FeatureAlgorithm R (Original)Algorithm L (Optimal)Distributed Reservoir Sampling

Time Complexity (per item)

O(1)

O(1)

O(1) per node

Space Complexity

O(k)

O(k)

O(k) per node + O(k) coordinator

Requires Known Stream Length (n)

Requires Random Access to Stream

Optimal for Large k (k > 1)

Varies by implementation

Key Mechanism

Replace with probability k/i

Skip items using geometric jumps

Merge local reservoirs

Primary Use Case

Simple streams, small k

High-throughput streams, any k

Parallel or distributed data streams

Suitability for Replay Buffer

RESERVOIR SAMPLING

Frequently Asked Questions

Reservoir sampling is a foundational algorithm for online learning systems, enabling fair sampling from data streams of unknown length. These questions address its core mechanics, applications, and relationship to continuous learning architectures.

Reservoir sampling is a randomized algorithm for selecting a simple random sample of k items from a data stream of unknown length n, where every item has an equal probability (k/n) of being included in the final sample. It works by initially filling a reservoir (an array of size k) with the first k items from the stream. For each subsequent item i (where i > k), the algorithm generates a random integer j between 1 and i inclusive. If j ≤ k, the item at reservoir index j is replaced with the new stream item i. This process guarantees a uniform random sample without requiring prior knowledge of the total stream length.

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.