Reservoir sampling
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Reservoir sampling picks a fair random sample of items from a stream whose length you do not know and cannot store. Every item ends up with the same chance of being chosen, using only a tiny fixed amount of memory.
Practical use cases
- Web app: Sampling log lines from a live server. A DevOps page shows 100 representative error lines from a log that grows by millions of lines a day. Storing everything is impossible. Keeping a basket of 100 and replacing items with the right chance gives a fair sample using almost no memory. Memory use stays flat at 100 lines whether the day brings a million lines or a billion.
- Web app: Picking giveaway winners from live entries. A contest page receives entries until the deadline, with no total count known. Choosing the winner on the fly with this method gives every entrant an equal chance, with no need to save and shuffle the full list. Every entry had the same chance, so nobody can complain the draw was unfair, and no big list was stored.
- Web app: Survey and A/B test sampling. A product team wants 1,000 random user sessions from a day of traffic for review. The app keeps a basket of 1,000 while sessions stream by, and at midnight the basket is a fair sample ready to review, however long the day was.
- System: Streaming analytics. Monitoring systems that see an endless flow of events keep a small reservoir sample so they can estimate averages and spot odd values without storing the stream. The monitoring job can run for months without its memory use ever growing.
The story: The Never-Ending Conveyor
At the railway station canteen, a long conveyor belt carried small cups of chai samples from the kitchen. Nobody knew how many cups would come. It could be 10 or 10 million. The manager said, "At the end, give a free lunch to one random cup's inventor. Fair and square."
Mira thought: "I will write down all cups, count them, and then pick a random one." But the belt was so long that her notebook ran out of pages. She also could not start over once the belt had moved on.
Zoya found the trick. "Hold only one cup in your hand. When cup number 2 arrives, roll a 2-sided die; if it shows 1, swap. When cup number 3 arrives, roll a 3-sided die; if 1, swap. For cup number i, roll an i-sided die: if 1, swap."
Early cups get swapped out often, but they also got in with better odds. It all balances so the final cup in your hand is a perfectly fair pick. This is reservoir sampling: a fair sample from a stream you can only look at once.
How to spot this problem, and where you need it
You need a fair random sample from data that keeps arriving, or is too big to hold in memory, and you do not know in advance how many items there will be.
Signs you need it
- You are reading a file or stream line by line and cannot load it all into an array to shuffle it.
- The total count is unknown until the end, so a simple "pick a random index" does not work.
- Taking the first N items would be biased because early items are not representative.
Where to use it in a project
- Sampling logs, events or user sessions for review dashboards or quality checks.
- Picking contest winners or random testimonials from entries that are still arriving.
- Taking a quick unbiased sample of a huge CSV or database export without loading it all.
The solution
Keep a basket of k items. Put the first k items in it. For the item number i after that, pick a random number from 1 to i. If it is at most k, drop a random basket item and put the new one in; otherwise ignore the new item. After the stream ends, every item had exactly the same chance of being in the basket.
Payoff: Before: storing 50 million lines to pick 100. After: a basket of 100 lines and one pass over the data.
Explain it like I am 8
You are watching a parade and want to pick your favourite float, but you can hold only one photo. For each new float, flip a coin-like die: sometimes you swap your photo for the new one. By the end of the parade, your photo is a fair surprise pick.
How it works, step by step
- Keep a reservoir (a bag with room for k items; here k = 1).
- Fill it with the first k items of the stream.
- For the i-th item after that (counting from 1), pick a random number from 1 to i.
- If the number lands inside the bag size, that item replaces the one at that spot. Otherwise skip it.
- When the stream ends, the reservoir is a uniform random sample. Memory used: only k items.
The code in four languages
PHP
<?php
// A tiny, repeatable random generator so the demo gives the same output each run.
function makeRng(int $seed): Closure {
return function (int $n) use (&$seed): int {
$seed = ($seed * 48271) % 2147483647;
return $seed % $n; // 0 .. n-1
};
}
// Keep k fair random items from a stream of unknown length.
function reservoir(iterable $stream, int $k, Closure $rand): array {
$bag = [];
$i = 0; // how many items we have seen
foreach ($stream as $item) {
if ($i < $k) {
$bag[] = $item; // fill the bag first
} else {
$j = $rand($i + 1); // random spot in 0..i
if ($j < $k) $bag[$j] = $item; // lands inside the bag: replace
}
$i++;
}
return $bag;
}
function numbers(int $n) { for ($x = 1; $x <= $n; $x++) yield $x; } // a stream
$rand = makeRng(7);
echo implode(',', reservoir(numbers(100), 3, $rand)), "\n"; // 3 fair picks
// Fairness check: pick 1 of 5, ten thousand times. Each should win about 2000 times.
$wins = array_fill(1, 5, 0);
for ($t = 0; $t < 10000; $t++) { $wins[reservoir(numbers(5), 1, $rand)[0]]++; }
echo implode(' ', $wins), "\n";JavaScript
// A tiny, repeatable random generator so the demo gives the same output each run.
function makeRng(seed) {
return (n) => {
seed = (seed * 48271) % 2147483647;
return seed % n; // 0 .. n-1
};
}
// Keep k fair random items from a stream of unknown length.
function reservoir(stream, k, rand) {
const bag = [];
let i = 0; // how many items we have seen
for (const item of stream) {
if (i < k) {
bag.push(item); // fill the bag first
} else {
const j = rand(i + 1); // random spot in 0..i
if (j < k) bag[j] = item; // lands inside the bag: replace
}
i++;
}
return bag;
}
function* numbers(n) { for (let x = 1; x <= n; x++) yield x; } // a stream
const rand = makeRng(7);
console.log(reservoir(numbers(100), 3, rand).join(',')); // 3 fair picks
// Fairness check: pick 1 of 5, ten thousand times. Each should win about 2000 times.
const wins = [0, 0, 0, 0, 0];
for (let t = 0; t < 10000; t++) wins[reservoir(numbers(5), 1, rand)[0] - 1]++;
console.log(wins.join(' '));Java
import java.util.*;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
public class Main {
// A tiny, repeatable random generator so the demo gives the same output each run.
static IntUnaryOperator makeRng(long seed) {
long[] state = {seed};
return n -> {
state[0] = (state[0] * 48271) % 2147483647;
return (int) (state[0] % n); // 0 .. n-1
};
}
// Keep k fair random items from a stream of unknown length.
static List<Integer> reservoir(Iterable<Integer> stream, int k, IntUnaryOperator rand) {
List<Integer> bag = new ArrayList<>();
int i = 0; // how many items we have seen
for (int item : stream) {
if (i < k) {
bag.add(item); // fill the bag first
} else {
int j = rand.applyAsInt(i + 1); // random spot in 0..i
if (j < k) bag.set(j, item); // lands inside the bag: replace
}
i++;
}
return bag;
}
static Iterable<Integer> numbers(int n) { // a stream
return () -> IntStream.rangeClosed(1, n).iterator();
}
public static void main(String[] args) {
IntUnaryOperator rand = makeRng(7);
System.out.println(reservoir(numbers(100), 3, rand)); // 3 fair picks
// Fairness check: pick 1 of 5, ten thousand times. Each should win about 2000 times.
int[] wins = new int[5];
for (int t = 0; t < 10000; t++) wins[reservoir(numbers(5), 1, rand).get(0) - 1]++;
System.out.println(Arrays.toString(wins));
}
}Go
package main
import "fmt"
// makeRng is a tiny, repeatable random generator so the demo gives the same output each run.
func makeRng(seed int64) func(n int) int {
return func(n int) int {
seed = (seed * 48271) % 2147483647
return int(seed % int64(n)) // 0 .. n-1
}
}
// reservoir keeps k fair random items from a stream of unknown length.
func reservoir(stream <-chan int, k int, rand func(n int) int) []int {
var bag []int
i := 0 // how many items we have seen
for item := range stream {
if i < k {
bag = append(bag, item) // fill the bag first
} else {
j := rand(i + 1) // random spot in 0..i
if j < k {
bag[j] = item // lands inside the bag: replace
}
}
i++
}
return bag
}
// numbers is a stream: a channel that hands out 1..n one by one.
func numbers(n int) <-chan int {
ch := make(chan int)
go func() {
defer close(ch)
for x := 1; x <= n; x++ {
ch <- x
}
}()
return ch
}
func main() {
rand := makeRng(7)
fmt.Println(reservoir(numbers(100), 3, rand)) // 3 fair picks
// Fairness check: pick 1 of 5, ten thousand times. Each should win about 2000 times.
wins := make([]int, 5)
for t := 0; t < 10000; t++ {
wins[reservoir(numbers(5), 1, rand)[0]-1]++
}
fmt.Println(wins)
}Time: O(n) · Extra space: O(k). One pass over the stream, remembering only the k items in the reservoir.
Watch out for
- Using the wrong range for the random number (it must be 0..i for the item at index i, so the chance shrinks as the stream grows).
- Storing the entire stream "just in case". That defeats the purpose.
- Expecting different runs to match when you use real randomness. Use a seed when you need repeatable tests.
Quick check
- When is reservoir sampling the right tool?
- A stream of unknown length you can only pass over once
- The data is tiny and sorted
- You need the biggest item
- For the 10th item (k = 1), what is the chance it replaces the bag item?
- 1 in 2
- 1 in 10
- Never
- How much memory does it need for k = 3?
- Room for the whole stream
- None at all
- Room for 3 items