Back to Streaming Sketching

Quantiles, Ranks & Distribution Summaries

September 25, 2026 Wasil Zafar 15 min read

Summarize ranks, quantiles, and distributions with bounded error.

Table of Contents

  1. Where Does This Value Rank?
  2. Ranks, Quantiles and Approximate Order
  3. Compaction Error and Rank Guarantees
  4. Latency Percentiles and Sensor Distributions
  5. Design a Percentile Monitoring Contract

Where Does This Value Rank?

Imagine lining up ten delivery times: 1, 2, 2, 3, 4, 5, 7, 8, 9, 40 minutes. The middle of the queue is near 4–5 minutes, but the last delivery took 40. An average cannot tell a customer how often deliveries run late. A rank counts how many observations lie at or below a value; a quantile names a value at a chosen position in the ordered data. For this list the empirical 90th-percentile nearest-rank value is the ninth observation, 9; the maximum is 40. If observations arrive continually, keeping every value for sorting may be too expensive. How many stored values suffice to answer percentile questions within an acceptable rank error? What changes when some observations represent thousands of requests? The sampling and concentration prerequisites explain why randomness can control error, but a rank bound requires its own explicit statement.

Ordering deliveries makes middle and tail visible Observations 10 wait times Sort 1, 2, ... 40 Choose rank q=.9 means 9th Report 9 minutes
TermMeaning with exact exampleBoundary or non-exampleQuestion
Inclusive rankIn $(1,2,2,5)$, $r(2)=3$The lower rank is 1; ties span ranks 2–3How many values are at most 2?
QuantileAt $q=3/4$, nearest rank in that list is position 3, value 2An interpolated percentile uses another conventionWhich value occupies the target position?
Rank errorFor $N=1000$, $\varepsilon=.01$ allows ten positionsIt does not promise ten milliseconds of value errorHow far can position drift?
Weighted rankWeight 5 on a value acts like five unit observationsNegative weights do not define an ordinary CDFWhat share of positive weight lies below a value?
Warm-up

Where Does This Value Rank?

Sort $1,2,2,3,4,5,7,8,9,40$ and set $N=10$. Checkpoint 1: $r(2)=3$ and the tie occupies positions 2–3. Checkpoint 2: for nearest-rank $q=.5$, use position $\lceil5\rceil=5$, value 4; for $q=.9$, position 9, value 9. If $\varepsilon=.1$, the rank budget is one position. Reflection: why can moving from ninth to tenth change the numeric answer by 31 despite that small budget?

Ranks, Quantiles and Approximate Order

Let $x_1,\ldots,x_N$ be observations from a totally ordered domain, with $N>0$. Define the inclusive rank $r(v)=\#\{i:x_i\leq v\}$. If equal values occur, the lower rank $r_{\lt }(v)=\#\{i:x_i\lt v\}$ and upper rank $r(v)$ bracket the entire tie block. Under the nearest-rank convention, the $q$-quantile for $0\lt q\leq1$ is the value at sorted position $\lceil qN\rceil$. An additive rank-error contract seeks a returned stored value with some valid position within $\varepsilon N$ of $qN$; ties require comparing rank intervals with the target rather than assuming one unique rank. An $\varepsilon$-approximation of the empirical CDF means $\lvert\widehat F(v)-F(v)\rvert\leq\varepsilon$ for every query value $v$, where $F(v)=r(v)/N$. A CDF guarantee for all values implies a rank guarantee when carefully inverting around jumps; a few accurate reported quantiles do not necessarily provide an accurate CDF everywhere. Greenwald–Khanna (GK) maintains deterministic rank intervals in an insertion-only stream and offers $O(\varepsilon^{-1}\log(\varepsilon N))$ space in its standard analysis, with convention-dependent constants. KLL uses randomized weighted compaction and offers high-probability rank error with space depending on $\varepsilon$ and failure probability; state the chosen variant's bound when implementing it. A t-digest often prioritizes tail accuracy empirically, but its common deployments do not furnish a universal worst-case rank guarantee equivalent to GK. A q-digest assumes a bounded ordered integer domain; histograms partition value space and can lose ordering detail within a bin. Weighted quantiles replace each item by a positive weight $w_i$ and normalize rank by $W=\sum_iw_i$; signed weights do not define an ordinary CDF.

Quantiles, Ranks & Distribution Summaries: Ranks, Quantiles and Approximate Order
flowchart TD
 A["Ordered insertion stream"] --> B["Inclusive rank and tie intervals"]
 B --> C["Nearest-rank quantile"]
 B --> D["Empirical CDF"]
 A --> E["GK rank intervals"]
 A --> F["KLL random compaction"]
 E --> G["Bounded rank error"]
 F --> G
 G --> H["Threshold decision with guard band"]
 classDef navy fill:#17365D,color:#fff
 classDef teal fill:#147D84,color:#fff
 classDef crimson fill:#C6284D,color:#fff
 classDef purple fill:#6C3BAA,color:#fff
 class A,B navy
 class C,D teal
 class E,F purple
 class G,H crimson
Sorted observations and interval around a target position Values 1 2 2 3 4 5 Ranks 1 through 6 Target q=.5; rank 3 Tie 2 spans 2–3
Definition or methodGuarantee and assumptionsCounterexample or consequence
Empirical CDF$F(v)=r(v)/N$ for positive unweighted observationsA tie creates a jump; rank need not uniquely specify a value
Nearest rankPosition $\lceil qN\rceil$ for $0\lt q\leq1$$q=0$ requires a separate minimum convention
Uniform CDF error$\sup_v\lvert\widehat F(v)-F(v)\rvert\leq\varepsilon$Reporting only one accurate quantile says nothing about other values
GKDeterministic rank guarantee for insertion-only streamIts usual tuple compression is not automatically mergeable
KLLProbabilistic rank bound with stated seed and failure budgetOne parity selection may be wrong; multiple trials matter
t-digestPractical tail compression, configuration dependentAn observed small error is not a universal worst-case theorem
q-digestOrdered bounded integer universeArbitrary unbounded real values require encoding or another method

Rank uncertainty and value uncertainty are different quantities. For a rank budget $\varepsilon N$, a query may return a nearby order statistic with an arbitrarily different numeric value if adjacent sorted observations are far apart.

Compaction Error and Rank Guarantees

A deterministic summary records a rank interval for each retained value. In GK, a tuple $(v,g,\Delta)$ has lower-rank increment $g$ and uncertainty $\Delta$; the upper rank of a stored value is at most its lower rank plus $\Delta$, and compression preserves a global rank-slack invariant on the order of $2\varepsilon N$. A query selects a value whose feasible rank interval meets the requested position to achieve its specified additive rank tolerance. This guarantee is about positions, not the numeric gap between values: if an extreme outlier sits next to the chosen rank, a one-rank discrepancy can change the reported value enormously. KLL instead groups values at levels. On an even sorted buffer $(a,b,c,d)$, randomly keeping either positions $(a,c)$ or $(b,d)$ with doubled weights preserves total represented weight and yields an unbiased prefix-weight estimate at every fixed query threshold: within each pair, either 0 or 2 represents the pair's true count of 1 for thresholds between the pair's values, with mean 1. Independent level compactions and a carefully allocated capacity schedule bound cumulative rank error with high probability. That argument needs the specified randomness and update/merge model; choosing one parity deterministically on an adversarial order may bias particular ranks. Merging same-parameter KLL summaries can preserve its designated error contract if compaction and seed semantics are respected; a generic deterministic GK merge does not inherit a guarantee merely because each input has one. Repeated observations need tie handling, and weighted streams require a weight-aware implementation rather than blindly expanding huge weights.

One KLL compaction turns four unit weights into two double weights Sorted pairs (a,b), (c,d) Random parity keep a,c or b,d New weights 2 on each kept Prefix error mean zero at fixed v
Quantiles, Ranks & Distribution Summaries: Compaction Error and Rank Guarantees
flowchart TD
 A["Positive ordered observations"] --> B["Track rank intervals in GK"]
 A --> C["Sort and compact pairs in KLL"]
 B --> D["Maintain global rank slack"]
 C --> E["Random parity; double weights"]
 E --> F["Unbiased prefix estimate"]
 F --> G["Concentration across levels"]
 D --> H["Rank-error query"]
 G --> H
 A --> X["Signed or arbitrary merges"]
 X --> Y["Recheck assumptions"]
 classDef navy fill:#17365D,color:#fff
 classDef teal fill:#147D84,color:#fff
 classDef crimson fill:#C6284D,color:#fff
 classDef purple fill:#6C3BAA,color:#fff
 class A,B,C navy
 class D,E teal
 class F,G,H purple
 class X,Y crimson
Worked Derivation

Compaction Error and Rank Guarantees

Compact sorted values $a=1,b=3,c=7,d=9$. Pair neighbors and flip one fair parity for this compaction. Keep $(1,7)$ or $(3,9)$, each retained item with weight 2; represented total weight remains 4. At threshold 2, the true prefix weight is 1; the two possible estimated weights are 2 and 0, whose mean is 1. At threshold 5, the true prefix weight is 2 and either outcome estimates 2. A single run may err at threshold 2, so report a probabilistic bound across configured compactions, not exactness of each outcome. Variation: always retain the smaller element. At threshold 2 the estimate is always 2, a systematic overcount; randomness is the needed unbiasedness assumption.

Analytical toolWhat it establishesRequired conditionLimit or failure case
GK rank intervalsDeterministic bounded rank uncertaintyInsertion-only ordered values and valid compression invariantDoes not bound numerical distance
Pairwise compactionPreserves total represented weight exactlyEven buffer, positive weights, valid pairingOne fixed parity can bias a prefix
Random parityUnbiased prefix count at fixed query valueFair independent coin for designated compactionsSingle realization can deviate
Concentration analysisHigh-probability rank error after levelsCapacity schedule and randomness matching chosen KLL variantChanged merge policy needs fresh analysis
CDF inversionConverts global CDF control to quantile rank controlTie-aware inverse and all-value CDF boundOne accurate quantile does not imply a CDF bound

Latency Percentiles and Sensor Distributions

A small team can monitor call-center wait times to ask whether 90% of callers wait no longer than a threshold. In a production service, a fleet of 200 instances emits about $10^7$ latency events per minute; fixed one-minute windows, arrival completeness, units, and a defined per-request weight matter as much as the sketch. A global percentile requires combining counts or compatible summaries across instances: averaging per-instance p99 values generally gives the wrong global p99. If an incident sends only slow requests through one tiny instance, equal weighting of instances hides real traffic proportions. For sensor data, a reading repeated because a device retries can shift percentiles without any physical change; deduplicate or clarify that the population is messages rather than sensors. An adversary may also inject extreme samples: rank guarantees remain valid for observed events but cannot certify that events are authentic. A rank-error budget of $0.001N$ at $N=10^7$ spans ten thousand positions; whether that is acceptable for p99.9 depends on the tail density and the SLO decision boundary. Validate numeric-value sensitivity separately.

Percentile pipeline from request events to guarded decision Ingest units and identity Window event-time bounds Summary rank approximation SLO gate uncertainty margin
Case Study

Latency Percentiles and Sensor Distributions: Quantiles, Ranks & Distribution Summaries

Twelve support-call waits in minutes are $1,1,2,2,3,3,4,4,5,7,9,30$. Select an insertion-only, unweighted nearest-rank model. At $q=.75$, the target position is $\lceil9\rceil=9$, so p75 is 5 minutes; p90 uses $\lceil10.8\rceil=11$, so p90 is 9 minutes. With $\varepsilon=1/12$, one position of error permits p90 to differ sharply if position 12 is returned: 30 minutes. Expected observation: rank control alone cannot certify a tight minute error. Success criterion: show positions, values, and the tie convention, and state which additional check would protect an SLO at 10 minutes.

Production

Latency Percentiles and Sensor Distributions: Quantiles, Ranks & Distribution Summaries

A fleet of 200 services emits $10^7$ request latencies per minute. Define the population as completed requests, use millisecond values and event-time minute windows, and ask for global p99 with rank error at most $0.0005N$ and failure below $10^{-3}$ per window. Choose a compatible mergeable KLL variant with declared parameters and shared configuration, then merge weighted summaries without averaging per-instance p99. The rank budget is 5000 requests; near an SLO threshold, compare bounds on the CDF at that threshold or check exact replay samples before making a binary incident decision. Track late and missing events, instance traffic imbalance, duplicates, clock drift, seed behavior, serialization, and merge-tree tests. Evidence: exact sorted reference windows, empirical coverage across seeds, memory and latency, and disagreement rates near the SLO. Written decision: use the merged summary for dashboards; trigger an unambiguous SLO action only when uncertainty bounds lie wholly on one side of the threshold.

Design a Percentile Monitoring Contract

Specify the population, event-time window, desired percentiles, tie and weight conventions, allowable rank error, failure probability, and merge policy. Separate a rank guarantee from a numerical latency tolerance or a guarantee that an SLO threshold is exceeded. Select GK when deterministic insertion-only rank intervals and its update model fit; use a correctly configured mergeable randomized sketch when distributed merging is essential; use a histogram when known bin resolution is enough. Check exact sorted samples near the decision boundary and include repeated values, missing events, outliers and shard imbalance. The exercises below lead from hand ranks to a reviewable percentile monitoring contract. The probability-concentration prerequisite supports interpreting randomized failure, while sampling principles help check whether the collected stream represents the intended population.

Practice

Practice: Design a Percentile Monitoring Contract

Tier 1: sort $(1,2,2,5,9)$, compute $r(2)=3$, lower rank 1, and nearest-rank p80 at position 4, value 5. Tier 2: with $N=1000$ and $\varepsilon=.01$, state the ten-position rank budget and explain why no finite value error follows. Tier 3: compact $(1,3,7,9)$ into two weight-2 representatives; at threshold 2 calculate estimates 2 and 0 with mean 1. Tier 4: always choose the smaller representative and identify the resulting biased prefix at threshold 2; discuss why a signed negative weight is outside the positive-CDF model. Tier 5: two instances have 99 latencies of 1 ms and one latency of 100 ms, versus one instance with 100 latencies of 50 ms; compute global nearest-rank p99 from 200 events: position 198 has value 50 ms, while the mean of per-instance p99 values (1 and 50) is 25.5 ms. Deliver sorted lists, calculations, a compaction diagram, the counterexample and a monitoring contract naming population, window, $\varepsilon$, $\delta$, ties and merge. Rubric: 2 points each tier; at least 8/10 and a correct global percentile required. Hint: combine raw counts before ranking. Debugging: if a retained pair has weight 1 after compaction, restore weight 2. Stretch: compare weighted ranks when the second instance doubles its traffic. Reflection: how would late arrivals alter your window definition?

Decision checklist: define the request population and window; select percentile and tie convention; budget rank error and failure probability; verify weighted and merged behavior; add a guard band for value-sensitive decisions. Rank error does not imply a millisecond guarantee, and averaging shard percentiles is invalid; revisit sampling and concentration when interpreting randomized summaries and uncertain input coverage.

Next in the Series

In Similarity, MinHash & Locality-Sensitive Hashing, we'll explore Estimate similarity and retrieve approximate neighbors..