The sketches earlier in this series each answer one kind of question fixed in advance: how many distinct keys, how often a key occurs, which value sits at a quantile. A sample answers questions chosen later. A network operator who keeps a sample of flow records can ask afterwards how much traffic went to one customer, one port or one country, and a sample of pageview records can be asked how many views went to German Wikipedia or to pages read between noon and one. This note covers how to draw such a sample in one pass over a stream of unknown length, and how to draw it so that sums over arbitrary subsets of the records come out accurate when the records carry very unequal weights.

Throughout, the stream is a sequence of records with weights , the sample holds records, and the target is a subset sum for a subset specified by any predicate on the records, unknown while the sample is drawn. The tool for turning a sample into an estimate of is the Horvitz–Thompson estimator. If record is in the sample with probability , the estimate is unbiased for , since each record contributes with probability and 0 otherwise. Everything below is a way of choosing the , or a substitute for them, in one pass.

The data

The records are the shared benchmark of the series: 160,961,718 records, one per (project, page, hour) of the Wikimedia pageview files of 4 March 2026, with 445,961,446 views in total. A record’s weight is its view count. Weights are extremely unequal. The mean is 2.77 views and the standard deviation is 34 times that; 68.9% of records have one view and hold 24.9% of all views, and the largest record, one English Wikipedia page in one hour, holds 265,344 views.

The subsets measured below are projects of different sizes (English Wikipedia’s mobile and desktop sites, German, Finnish, Galician and Aragonese Wikipedia, and Portuguese Wikinews), single hours, and the pages whose 64-bit key hash is divisible by 100 or by 10,000, which picks pages at random without regard to their weight.

Uniform samples: reservoir sampling

Algorithm R. To keep a uniform sample of records from a stream whose length is not known in advance, store the first records; then, when record arrives, draw a uniform integer in and, if , replace the record in slot . By induction on , after records every record seen so far is in the reservoir with probability . Record enters with probability . A record already in the reservoir, present with probability , survives step unless record enters and takes its slot, which happens with probability , so it remains with probability . The same argument shows that every -subset is equally likely, so the reservoir is a simple random sample without replacement. Vitter (1985) attributes the algorithm to Waterman and analyses it with faster variants.

Algorithm R draws one random number per record. Most draws change nothing: the expected number of replacements over records is , which for and the 161 million records is about 1,400 out of 161 million draws.

Algorithm L. Attach to each record an independent uniform key and keep the records with the smallest keys. This is again a uniform sample, and it can be maintained by skipping. Let be the largest key in the reservoir. The next record that enters is the first whose key is below , so the number of records skipped is geometric with success probability , which can be drawn directly as . The entering record replaces the one with key , and since the keys now in the reservoir are independent and uniform on , the new largest key is distributed as and can be drawn without storing any keys. Li (1994) calls this Algorithm L. It draws three random numbers per replacement and touches only the records that enter, for expected work in total. Vitter’s Algorithm Z reaches the same bound with rejection sampling.

Measured. I checked Algorithm L’s uniformity directly. Over runs with and , the inclusion counts of the 1,000 positions give on 999 degrees of freedom, a deviation of standard deviations from the expected value. On the 161 million records, held in memory, with one core:

Algorithm R, ns per recordAlgorithm R, random numbersAlgorithm L, ns per recordAlgorithm L, random numbers
1002.10 to 2.27160,961,618below 0.0014,211 to 4,334
10,0002.11 to 2.15160,951,7180.022 to 0.023288,902 to 290,438
1,000,0002.56 to 2.95159,961,7181.20 to 1.3215,237,017 to 15,256,364

The counts of random numbers match : 4,287, 290,000 and 15.2 million. The times measure only the sampler, because Algorithm L never reads a skipped record. In a real stream each record still has to be read and parsed, so Algorithm L’s saving is the random number generation and the branch per record, which at 2.1 ns per record was most of Algorithm R’s cost here. At , Algorithm L makes 15 million replacements and Algorithm R’s random writes spread over a 4 MB reservoir, and both slow down.

Why a uniform sample estimates sums badly

A uniform sample gives each record , so the Horvitz–Thompson estimate of is times the sampled weight in . It is unbiased, and its relative standard error for the whole stream is approximately , where CV is the coefficient of variation of the weights, 34.3 here. At that is 34%.

The error is also badly distributed. Most of the variance comes from rare samples that contain one of the few heaviest records, which then counts times. Over 100 runs at each , 76% to 77% of the uniform estimates of the total fell below the truth, and the root mean squared error measured over those runs (20.6%, 19.4% and 6.1% at , and ) was smaller than the formula, because 100 runs rarely include the runs that hold the heaviest records. For German Wikipedia, whose heaviest record holds 0.44% of its views, one of the 100 runs at drew one of its heaviest records and scaled it by 16,096, overshooting by 6,460%, and the relative error over the 100 runs was 647%.

The remedy is to sample heavy records with higher probability. Sampling with probability proportional to weight, , would make every sampled record contribute the same , so the estimate of the total would have no variance at all. With a fixed sample size this cannot be achieved exactly when some weights are large, since cannot exceed 1, and it has to be done in one pass. The next two schemes do both.

Weighted samples

Weighted sampling without replacement. Efraimidis and Spirakis (2006) give each record the key and keep the largest. Equivalently, give record the rank , which is exponentially distributed with rate , and keep the smallest ranks. The record with the smallest rank among a set is record with probability , by the competing-exponentials property, and by memorylessness the same holds for the next smallest among the rest. The smallest ranks are therefore a sample drawn by successive weighted draws without replacement (PPSWOR), and the reservoir is a heap of ranks, as in Algorithm L.

PPSWOR does not give each record a simple inclusion probability. Cohen and Kaplan (2007) give an unbiased estimator by rank conditioning. Let be the -th smallest rank. Conditioned on the ranks of all other records, record is in the sample exactly when , where is the -th smallest rank among the others, and for a sampled record . Its conditional inclusion probability is , so each sampled record contributes , which is unbiased given the others and hence unconditionally.

Priority sampling. Duffield, Lund and Thorup (2007) use the priority and keep the records with the largest priorities. Let be the -th largest priority. A sampled record counts as

and an unsampled one as 0. Conditioned on the other priorities, record is sampled exactly when , the -th largest of the others, which happens with probability , and when is sampled. The estimate is divided by that probability, so . Records heavier than are always sampled and count at their own weight; lighter ones are sampled with probability about and each counts as . For any subset, is unbiased. Duffield, Lund and Thorup also prove that the of distinct records are uncorrelated, so the variance of is the sum of the per-record variances, and that

is an unbiased estimate of it, computable from the sample alone.

Priority sampling and PPSWOR are both bottom- sketches in Cohen and Kaplan’s terms: each record gets a random rank whose distribution depends on its weight (, uniform on , for priority sampling; exponential with rate for PPSWOR), and the sample is the smallest ranks. Both are mergeable: the sample of a union is the smallest ranks among the two samples, provided the ranks were kept. Szegedy (2006) proved that priority sampling with samples has a total variance no larger than that of any unbiased scheme with samples, settling a conjecture of Duffield, Lund and Thorup. The variance-optimal scheme, VarOpt, keeps exactly records with a more involved update (Cohen, Duffield, Kaplan, Lund and Thorup 2011), and Daliri, Freire, Musco, Santos and Zhang (2023) give a short analysis of priority sampling’s concentration.

Measured subset-sum error

Each sampler ran 100 times at each of over all 161 million records, with independent random numbers per run. The table gives the relative root mean squared error of each subset’s estimated views at , and the share of runs in which priority sampling’s interval held the true value.

SubsetRecordsShare of viewsUniformPriorityPPSWORPriority interval held
All records160,961,718100%19.4%1.0%1.0%94%
English Wikipedia, mobile25,526,00929.9%44.1%1.7%1.9%99%
English Wikipedia, desktop31,724,48321.1%14.3%2.1%2.0%95%
Hour ending 12:00 UTC6,834,7974.03%19.8%4.8%5.4%96%
German Wikipedia, desktop3,909,7032.01%647%7.1%7.0%95%
Pages with key hash divisible by 1001,609,6420.93%49.4%9.5%10.2%94%
Finnish Wikipedia, desktop348,8090.115%28.9%30.8%27.0%94%
Galician Wikipedia, desktop178,4550.043%37.5%46.3%47.1%93%
Portuguese Wikinews33,1750.010%191%92.2%86.9%70%
Pages with key hash divisible by 10,00016,4750.010%185%88.8%89.7%65%
Aragonese Wikipedia, desktop8,3690.003%110%158%204%16%

For the whole stream, priority sampling’s error falls from 3.4% at to 1.0% and 0.3% at and , close to scaled by a constant of about 1. Its variance estimate matched the measured error too: for the whole stream at the mean of was 0.98% of the total against a measured 0.99%.

Three patterns stand out.

  • Heavy subsets. For a subset that holds a fair share of the weight, weighted sampling is 4 to 90 times more accurate than a uniform sample of the same size, and PPSWOR and priority sampling are indistinguishable.
  • Light subsets. Finnish and Galician Wikipedia have light records (Finnish has a mean of 1.47 views per record and a coefficient of variation of 5.2, against 34 for the whole stream). Priority sampling spends its sample on heavy records elsewhere in the stream, and a uniform sample, which spends it evenly over records, was as accurate or more accurate for these subsets at and for Galician at .
  • Tiny subsets. No sampler of this size estimates a subset of 0.003% of the weight. When a subset has only a handful of sampled records, is itself estimated from those few records, often from none, and the interval held the truth in only 16% of runs for Aragonese at . At , with more sampled records in each subset, the intervals held in 93% to 99% of runs for every subset.

The figure

The figure runs the three samplers in the browser on a substream of 39,986 records (every record of the pages whose key hash has its top 12 bits zero, about 1 in 4,096 pages, in recorded order, with 147,216 views). Pick a subset and a sample size, and each dot shows one run’s estimate of the subset’s views divided by the truth, for 100 runs of each sampler. The lower chart shows the records of the first priority sample by views, heaviest first, against the threshold . The records above the line count at their own views; those below it count as each. Records with one view show uniform sampling at its best.

00.511.522.5≥ 3Uniform (Algorithm L)Priority samplingWeighted without replacementestimate ÷ true views (1 is exact)

English Wikipedia, desktop: 7,961 records with 34,939 views, 23.7% of the substream's views. Over 100 runs with K = 100, the relative root mean squared error is 181.0% for the uniform sample, 15.9% for priority sampling and 18.9% for weighted sampling without replacement.

Priority sampling's interval, the estimate ± 2 standard deviations from its own variance estimate, held the true value in 97% of runs.

1101001,00010,000τ = 1482.1the 100 kept records, by views(views on a log scale)

In the first run, the threshold τ is 1482.1 views. The 5 kept records with more views than τ count at their own views, and the other 95 count as τ each. 25 of the kept records belong to the subset (orange).

Each sampler keeps K of the 39,986 records of a fixed substream (every record of 1 in 4,096 pages, in recorded order, 147,216 views) and estimates the subset's views from them, 100 times with independent random draws, in the browser. Each dot is one run. The uniform sample scales its subset total by 39,986/K; priority sampling counts a kept record as max(w, τ); weighted sampling without replacement counts it as w/(1 − e−wτ).

Consequences

A uniform reservoir is the right sample when records count equally, as when estimating the fraction of requests with some property, and Algorithm L draws it with work proportional to the number of replacements. For sums of a heavy-tailed weight such as bytes, views or revenue, a uniform sample is unbiased in principle and unusable in practice: most estimates fall short and a few overshoot by orders of magnitude.

Priority sampling is the simplest weighted alternative. Its state is a heap of priorities, its estimates for any subset are unbiased, and it reports its own variance, which was accurate wherever the subset had more than a few sampled records. It is the sample to keep when the subsets of interest are not known in advance. When they are known and include many light records, as with small projects here, a stratified design, a separate sample per stratum or a uniform sample kept alongside, does better than any single weighted sample.