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.
Glossary
Reservoir Sampling

What is Reservoir Sampling?
Reservoir sampling is a foundational randomized algorithm for online learning and streaming data systems.
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.
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.
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.
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.
Algorithm R (The Classic)
Algorithm R is the foundational, straightforward implementation.
- Initialization: Fill the reservoir with the first
kitems from the stream. - Inductive Step: For each incoming item
i(wherei > k), generate a random integerjuniformly from1toi. Ifj ≤ k, replace thej-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
ndue to the random number generation for every item.
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.
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, whereu_iis a uniform random number. It maintains thekitems 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.
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
kfrom 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.
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 Feature | Algorithm 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 |
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.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Reservoir sampling is a foundational technique within online learning systems. These related concepts define the broader ecosystem of algorithms and architectures for models that learn continuously from data streams.
Online Learning
Online learning is the core machine learning paradigm where a model updates its parameters sequentially, processing one data point or a small mini-batch at a time without revisiting past data. This makes it essential for:
- Streaming data applications like financial tickers or IoT sensor feeds.
- Real-time adaptation where model predictions must reflect the most recent information.
- Large-scale datasets where storing the entire history is computationally infeasible. The primary challenge is balancing immediate learning with long-term stability, often analyzed through the framework of regret minimization.
Experience Replay Buffer
An experience replay buffer is a fixed-size memory store used in reinforcement learning and continual learning to cache past experiences (e.g., state-action-reward transitions). Its core functions are:
- Breaking temporal correlations by randomly sampling past data in mini-batches.
- Mitigating catastrophic forgetting by allowing the model to revisit and rehearse old tasks.
- Improving sample efficiency by reusing valuable experiences. Reservoir sampling is the canonical algorithm for maintaining a uniform random sample within this buffer when the stream length is unknown, ensuring every past experience has an equal probability of being retained.
Concept Drift Detection
Concept drift detection refers to algorithms that automatically identify when the underlying statistical properties of a target variable change over time relative to the input data. In streaming contexts, this is critical because:
- A model's performance will degrade silently if the data distribution shifts.
- Detection triggers model adaptation, retraining, or alerting. Common algorithms include ADWIN (Adaptive Windowing) and CUSUM. These methods often work in tandem with sampling techniques like reservoir sampling, which provides a representative recent history of data to analyze for statistical change.
Stochastic Gradient Descent (SGD)
Stochastic Gradient Descent is the fundamental optimization algorithm for online learning. It updates model parameters using the gradient computed from a single data point or a small, randomly sampled mini-batch.
- Core Mechanism:
θ = θ - η * ∇J(θ; x_i, y_i), whereηis the learning rate. - Connection to Streaming: SGD processes data in the order it arrives, making it inherently online.
- Asynchronous Variants: Asynchronous SGD allows parallel workers to update shared parameters without tight synchronization, crucial for high-throughput streaming systems. While reservoir sampling manages which data is stored, SGD defines how the model learns from each new piece of data.
Regret Minimization
Regret minimization is the primary theoretical framework for analyzing and designing online learning algorithms. Regret is defined as the cumulative difference between the losses incurred by the online algorithm and the losses of the best fixed decision in hindsight.
- Goal: Design algorithms with sublinear regret, meaning the average regret per round goes to zero.
- Application: This framework provides performance guarantees for algorithms dealing with adversarial data streams, where patterns can change arbitrarily. While practical algorithms like reservoir sampling are heuristic, their effectiveness in maintaining a representative buffer supports the overall goal of minimizing regret in continual learning systems.
Multi-Armed Bandit
A multi-armed bandit is a sequential decision-making framework that formalizes the explore-exploit tradeoff. An agent chooses from a set of actions (arms) with unknown reward distributions to maximize cumulative reward over time.
- Exploration: Gathering information about unknown arms.
- Exploitation: Choosing the arm with the highest known reward. Key solving algorithms include Thompson Sampling (Bayesian) and Upper Confidence Bound (UCB). Bandits represent a specialized form of online learning where feedback is limited to the chosen action. Reservoir sampling can be used in contextual bandits to maintain a sample of past contexts for more efficient off-policy evaluation.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us