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

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.
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.
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.
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 indexi, it is included with probabilityk/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.
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 positioniis in the reservoir at that time isk/i. It then must survive all subsequent replacement attempts(i+1...N), each with probability1 - k/j * 1/k = (j-1)/j. The product telescopes tok/N. - Critical For: Statistical validity in experience replay, ensuring the buffer does not introduce temporal bias.
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 integerjfrom[0, i). Ifj < k, replacereservoir[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.
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
igrows 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.
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.
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
kexperiences. Reservoir sampling provides a uniform random sample of allNexperiences 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.
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.
| Feature | Reservoir Sampling | Uniform 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 |
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.
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 algorithm within a broader ecosystem of techniques for managing data streams and memory in machine learning. These related concepts are essential for building robust, efficient learning systems.
Experience Replay Buffer
An experience replay buffer is a core data structure in reinforcement learning that stores past interactions (state, action, reward, next state). Its primary functions are:
- Breaking temporal correlations by randomly sampling past experiences for training.
- Improving sample efficiency by reusing experiences multiple times.
- Stabilizing training for deep neural networks, as famously demonstrated in the Deep Q-Network (DQN) algorithm. A common implementation is a circular buffer (FIFO), but reservoir sampling provides a statistically sound method for maintaining a fixed-size, uniform random sample from an unbounded stream.
Prioritized Experience Replay (PER)
Prioritized Experience Replay is an advanced sampling strategy that selects experiences from a replay buffer with probability proportional to their temporal-difference (TD) error. This focuses learning on transitions the agent found more surprising or informative.
- Core Mechanism: Uses a priority queue (often a binary heap) instead of uniform random access.
- Bias Correction: Requires importance sampling weights to correct for the shifted sampling distribution, ensuring convergence.
- Impact: Can dramatically accelerate learning in complex environments by prioritizing high-learning-value experiences.
Online Learning
Online learning is a machine learning paradigm where a model updates its parameters incrementally, one data point (or mini-batch) at a time, as the data arrives in a stream. This contrasts with batch learning on a static dataset.
- Key Challenge: Adapting to non-stationary data distributions (concept drift).
- Connection to Reservoir Sampling: Reservoir sampling is a canonical algorithm for maintaining a representative sample from an online data stream, which can be used for monitoring, evaluation, or as a replay buffer for continual learning systems.
- Architectures: Includes algorithms like Follow-The-Regularized-Leader (FTRL) and stochastic gradient descent applied to streaming data.
Catastrophic Forgetting
Catastrophic forgetting (or catastrophic interference) is the tendency of a neural network to abruptly and drastically lose performance on previously learned tasks when trained on new data. It is the central challenge in continual learning.
- Role of Replay: Experience replay mechanisms, including those using reservoir sampling, directly combat forgetting by interleaving old and new data during training.
- Related Techniques: Generative replay uses a generative model to produce synthetic old data. Elastic Weight Consolidation (EWC) regularizes important weights for old tasks.
- Buffer-based solutions: Methods like Gradient Episodic Memory (GEM) explicitly store exemplars in a buffer to constrain new learning.
Importance Sampling
Importance sampling is a fundamental statistical technique for estimating expected values under one distribution using samples drawn from a different distribution. It is critical for off-policy reinforcement learning.
- Core Formula: Corrects estimates using a ratio of probability densities (or policy probabilities), known as the importance sampling ratio.
- Application in PER: Used to correct the bias introduced by non-uniform sampling in Prioritized Experience Replay.
- Advanced Methods: Algorithms like Retrace and V-trace use sophisticated importance sampling for stable off-policy correction with function approximation.
Streaming Algorithms
Streaming algorithms are designed to process data sequentially, in a single pass, using memory sublinear in the size of the data stream. They are essential for big data and real-time analytics.
- Reservoir Sampling's Place: It is a quintessential streaming algorithm for the random sampling problem.
- Other Key Streaming Problems:
- Frequency Estimation (e.g., Count-Min Sketch).
- Distinct Element Counting (e.g., HyperLogLog).
- Heavy Hitters Identification (e.g., Misra-Gries).
- ML Relevance: These algorithms enable efficient feature statistics collection, data distribution monitoring, and memory-efficient preprocessing for online learning systems.

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