Library / Documentation
Reservoir sampling (Wikipedia)
Algorithm R, weighted variants and proofs of uniformity.
By Wikipedia contributors · Wikipedia · Added 2026-10-12
All content belongs to Wikipedia contributors / Wikipedia. We only link to it and give credit. Report a problem
Learn this doc
About 30 min left. Your work is saved as you go.
What you want from these docs
Wikipedia documents a tool you may use. Decide what you want to do with it, then read only what answers that.
Ideas you will meet
- Distributed Systems
- Consensus, time, failure and the fundamentals of scale-out.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Search, Analytics and Geo · 9 minReservoir sampling: a fair sample of a stream you cannot storeHow to keep k uniformly random items from a stream of unknown length using only k slots of memory, why it works, and where it is used.Read here
The problem
You want a small, unbiased sample of a stream: log lines, requests, events. You cannot store the whole stream, and you do not know how long it will be. "Keep every 1,000th item" is not random and can be biased by periodic traffic. "Pick random items" needs to know the total in advance.
Reservoir sampling keeps exactly
kitems so that, at any moment, each of thenitems seen so far has the same probabilityk / nof being in the sample.Algorithm R
- Put the first
kitems in the reservoir. - For each later item number
i(counting from 1), draw a random integerjbetween 1 andi. - If
jis at mostk, replace reservoir slotjwith the new item. Otherwise discard the new item.
100%Figure SDA-SAG-06-1 · Algorithm R for one new item · © forcsguy.com
function reservoir<T>(stream: Iterable<T>, k: number, rand = Math.random): T[] { const sample: T[] = []; let i = 0; for (const item of stream) { i++; if (sample.length < k) sample.push(item); else { const j = Math.floor(rand() * i); if (j < k) sample[j] = item; } } return sample; }Why it is fair
Item
ienters with probabilityk / i. Then it survives each later stepmwith probability1 - (k / m) x (1 / k) = (m - 1) / m. Multiply them for itemiafternitems:(k / i) x (i / (i + 1)) x ... x ((n - 1) / n) = k / n. Every item ends with the same chance, whatever its position.Where it is used
- Debug and audit samples of request logs or events, at constant memory.
- Estimating statistics, such as the share of requests with a certain property, from the sample.
- Training data selection from a live stream.
- Approximate quantiles when a small error is acceptable (for tighter tail accuracy see the t-digest lesson).
Sampling many streams
100%Figure SDA-SAG-06-2 · Merging samples from several servers · © forcsguy.com
Keep the count with every sample; without it you cannot merge correctly. A simple way is to draw each output slot by choosing a server with probability equal to its share of the total count, then taking a not-yet-used item from that server's reservoir.
Variants and limits
- Weighted sampling (Efraimidis and Spirakis, A-Res) lets some items be more likely, for example by traffic weight.
- Sliding windows need extra structure: plain reservoir sampling treats the whole history equally.
- A sample answers "what does a typical item look like?" It does not answer exact counts or rare-event questions; for those use sketches such as HyperLogLog or count-min.
Real-world reading
- Put the first
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Reservoir sampling (Wikipedia).
Warm upGet the vocabulary first.
Books · Free from the author
Concurrent and Distributed Systems (Cambridge lecture notes)
Eight lectures on time, broadcast, replication, consensus and transactions, with notes, slides and video. Free from the author under CC BY-SA.
University of CambridgeIntermediate
Books · Free from the author
Computer Networks: A Systems Approach
How networks are built and why: protocols, routing, congestion control and the internet's architecture. The authors publish it free online under CC BY 4.0.
Systems ApproachIntermediate
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs · Free from the author · Read here
Scalable Web Architecture and Distributed Systems
A full chapter on the building blocks of large websites: availability, performance, reliability, scalability, caches, proxies, indexes, load balancers and queues. Free to read here under CC BY 3.0.
The Architecture of Open Source ApplicationsBeginner40 min
Papers · Read here
Facebook’s photo storage
This paper describes Haystack, an object storage system optimized for Facebook’s Photos application. Facebook currently stores over 260 billion images, which translates to over 20 petabytes of data.
USENIXIntermediate
See it in another companyThe same ideas, a different system.
Case Studies · Read here
Aroma: Using ML for Code Recommendation at Facebook
Thousands of engineers write the code to create our apps, which serve billions of people worldwide. This is no trivial task—our services have grown so diverse and complex that the codebase contains…
FacebookIntermediate
Case Studies · Read here
Brooklin: Distributed Service for Near Real-Time Data Streaming at LinkedIn
Brooklin—a distributed service for streaming data in near real-time and at scale—has been running in production at LinkedIn since 2016, powering thousands of data streams and over 2 trillion messages per day. Today, w...
LinkedInIntermediate
Read the codeSee how it looks when it is real.
GitHub
Engineering Blogs
A huge directory of company engineering blogs to learn from real production systems.
kilimchoiIntermediate
GitHub
Awesome Scalability
Curated reading list of articles on the architecture of scalable, reliable systems.
binhnguyennusIntermediate
Keep learning
Loading community…