Compacting Ordered Samples Without Losing Rank
Suppose a service records millions of response times but can retain only a small summary. Keeping the mean misses tail latency, while storing every value is expensive. A quantile sketch answers questions such as “what value has about 99% of observations below it?” KLL—the K-form of the Karnin–Lang–Liberty sketch—does this by repeatedly sorting small buffers and randomly keeping half their items.
Think of a stack of trays. New observations enter the bottom tray with weight one. When a tray overflows, sort its items, flip a fair coin, keep either the even or odd positions, discard the other positions, and move the kept items one tray upward. An item on level \(h\) carries weight \(2^h\). Two adjacent items of weight \(2^h\) are therefore represented by one randomly selected item of weight \(2^{h+1}\).
For a tiny compaction, sort \([2,4,7,9]\) at level zero. Choosing even positions retains \([2,7]\); choosing odd positions retains \([4,9]\). Each survivor moves to level one and represents weight two. Both outcomes preserve total represented mass \(4\). For a rank query at \(x=5\), the exact compacted-block rank is two. The even choice contributes weight two from value \(2\); the odd choice contributes weight two from value \(4\). Both happen to be exact here. At \(x=3\), the two outcomes contribute two or zero instead of exact rank one—an error of \(+1\) or \(-1\), centered at zero.
This deep dive builds on streaming quantiles by explaining why compaction preserves rank approximately and how weighted queries reconstruct a distribution. A weighted level assigns weight \(2^h\) to every retained level-\(h\) item. Compaction replaces a sorted group by one random parity at the next level. Capacity schedules decide how many items each level may hold; true KLL uses a carefully chosen schedule rather than merely giving every level the same capacity. Rank error is \(\widehat R(x)-R(x)\), where \(R(x)\) counts stream values at most \(x\). Mergeability means compatible summaries can combine their level buffers and compact again. Tail accuracy describes behavior near extreme quantiles; ordinary KLL targets uniform absolute rank error, while specialized variants can emphasize tails.
KLL approximates ranks, not numeric distances. A small rank error can correspond to a large value error across a distribution gap. Duplicates need a documented rank convention, and NaN handling, ordering, serialization, and randomness are part of the implementation contract.
KLL preserves exact total weight while random compactions trade pairs of nearby ordered samples for one double-weight representative. Its guarantee is about rank, not closeness in value, and it depends on unbiased parity choices plus a valid capacity schedule.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Main assumption | Question answered |
|---|---|---|---|---|---|
| Weighted level | Higher trays represent more observations per item | Level \(3\) item has weight \(8\) | Treat every retained item as weight one | Promotion doubles weight | How does a small summary preserve mass? |
| Compaction | Sort and keep one parity | \([2,4,7,9]\to[2,7]\) or \([4,9]\) | Arbitrarily drop the largest half | Fair parity choice and total order | How is memory reduced? |
| Randomized parity | Choose even or odd sorted positions | One fair bit per compaction | Always keep even positions | Unbiased independent-enough choices | Why is rank error centered? |
| Capacity schedule | Per-level buffer limits | Geometric KLL allocation | Unlimited buffers | Schedule matches proof and implementation | Where is memory spent? |
| Rank error | Difference in counts below a threshold | Exact \(1\), estimated \(0\), error \(-1\) | Numeric value difference | Fixed rank convention | What does accuracy mean? |
| Mergeability | Combine compatible weighted levels | Concatenate same levels, then compact | Average two reported medians | Same ordering, type, parameters, and format | How do partitions combine? |
| Tail accuracy | Accuracy near small or large ranks | Error at p99 measured in rank units | Assuming uniform relative tail error | Variant-specific guarantee | Are extreme percentiles specially protected? |
Compacting Ordered Samples Without Losing Rank
Compact sorted level-zero values \([1,3,6,8]\).
- If even positions are kept, promote \([1,6]\) with weight two.
- If odd positions are kept, promote \([3,8]\) with weight two.
- For threshold \(x=5\), exact rank within the block is two. The two outcomes contribute two or two: zero error.
- For \(x=2\), exact rank is one. Outcomes contribute two or zero: errors \(+1\) and \(-1\).
- In both outcomes, represented weight is four.
Reflection: why does sorting before selecting parity localize rank error, whereas keeping two arbitrary values may not?
Levels, Weights and Random Compaction
Let level \(h\) contain values of weight \(w_h=2^h\). New items enter level zero. When a level exceeds its capacity, KLL sorts an eligible even-sized region, flips a fair parity bit \(b\in\{0,1\}\), retains positions \(b,b+2,b+4,\ldots\), and promotes those survivors to level \(h+1\). Each promoted value's weight doubles.
Mass preservation is exact. Compacting \(2m\) items of weight \(2^h\) removes represented mass \(2m\cdot2^h\) and promotes \(m\) items of weight \(2^{h+1}\), the same amount. Consequently \[ \sum_{h\ge0}2^h|L_h|=n \] after every completed update, assuming no overflow and no temporarily retained odd remainder is misweighted.
For rank threshold \(x\), consider one sorted compaction. Pair adjacent values. Every pair entirely at or below \(x\) contributes its full weight whichever parity wins; every pair entirely above contributes zero. At most one pair straddles the cutoff. Its exact contribution is \(2^h\), while the compacted contribution is either \(0\) or \(2^{h+1}\). Thus one compaction contributes rank error in \(\{-2^h,0,+2^h\}\), with conditional expectation zero under a fair parity bit.
Errors at higher levels are larger, but far fewer high-level compactions occur. KLL's capacity schedule balances the number and scale of these random errors. A full proof charges variance or tail probability across levels and chooses capacities geometrically, with more protection at influential upper levels and specialized handling near the top. The resulting family attains near-optimal space: \(O((1/\varepsilon)\log\log(1/\delta))\) items for additive rank error \(\varepsilon n\) with failure probability \(\delta\), with \(O(1/\varepsilon)\) space at constant confidence. Precise constants, schedule, and small-\(n\) behavior depend on the KLL variant.
Always keeping one parity is a counterexample to unbiasedness. For the block \([1,3,6,8]\) and \(x=2\), always keeping evens always returns rank two instead of one, accumulating directional error. Random choice is not aesthetic; it turns deterministic drift into a mean-zero sum that concentration bounds can control.
Compared with deterministic GK summaries, KLL trades deterministic worst-case rank bounds for randomized bounds and typically strong compactness and merge behavior. Compared with reservoir sampling, KLL explicitly organizes weighted compactions to control ranks across the distribution.
flowchart TD
A[New value enters level zero with weight one] --> B{Level exceeds capacity?}
B -->|no| C[Retain current weighted state]
B -->|yes| D[Sort eligible items]
D --> E[Flip fair parity bit]
E --> F[Keep alternating positions]
F --> G[Promote survivors to next level]
G --> H[Double their represented weight]
H --> I[Total represented mass unchanged]
I --> J[Each threshold sees bounded mean-zero error]
J --> K[Charge errors across scheduled levels]
K --> L[High-probability additive rank bound]
E --> M{Biased or reused parity?}
M -->|yes| N[Directional rank error may accumulate]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,C,D navy;
class E,F,G,H purple;
class I,J,K,L teal;
class M,N crimson;
Level \(h\) items carry weight \(2^h\); compacting \(2m\) such items into \(m\) promoted items preserves mass exactly. For any fixed rank threshold, one fair-parity compaction contributes bounded mean-zero error of magnitude at most \(2^h\); KLL's scheduled capacities limit how these errors accumulate, yielding near-optimal randomized rank space.
Charging Rank Error Across Levels
Fix a threshold \(x\). The final estimated rank is \[ \widehat R(x)=\sum_{h\ge0}2^h\,|\{v\in L_h:v\le x\}|. \] Every compaction contributes a random error variable \(E_{h,t}(x)\) with conditional mean zero and \(|E_{h,t}(x)|\le2^h\). The total error is their sum. The proof challenge is not one compaction but the number of compactions at each level, their dependence structure, and their increasing weights.
A useful audit ledger records, for each level, its capacity, compaction count, parity choices, and maximum error charge. KLL analysis exploits the fact that level \(h\) represents increasingly large blocks: the number of possible compactions drops rapidly as \(h\) rises. Properly scheduled capacities keep the variance proxy and tail bound small enough that \[ \Pr\!\left[|\widehat R(x)-R(x)|>\varepsilon n\right]\le\delta. \] The strongest KLL results carefully handle all rank queries and schedule details; a simple equal-capacity hierarchy demonstrates the mechanism but uses \(O(k\log n)\) retained space and should not be mislabeled as the full near-optimal construction.
For a hand trace, compact \([1,3,6,8]\) at level zero, keep \([1,6]\), and promote with weight two. Add uncompacted level-zero values \([2,9]\). The weighted summary is \(1:2,6:2,2:1,9:1\), total mass six. At \(x=4\), estimated rank is \(2+1=3\). If the original six values were \([1,3,6,8,2,9]\), exact rank is three. At \(x=2\), estimate is three while exact rank is two, a \(+1\) error attributable to that compaction.
Perturb the parity to keep \([3,8]\). At \(x=2\), only uncompacted \(2\) contributes, so estimate one and error \(-1\). The two outcomes are symmetric. If the same biased choice is forced across many similar blocks, errors can align; independent fair bits are the defense.
Charging Rank Error Across Levels
Start with stream values \([1,3,6,8,2,9]\). Compact the first four level-zero items.
- Even parity retains \(1,6\) at weight two; leave \(2,9\) at weight one.
- Verify mass: \(2+2+1+1=6\).
- Query \(x=4\): weighted items \(1\) and \(2\) contribute \(2+1=3\), matching exact rank three.
- Query \(x=2\): the summary contributes \(2+1=3\), while exact rank is two; charge \(+1\) to the level-zero compaction.
- With odd parity \(3,8\), the rank at \(x=2\) becomes one, giving error \(-1\).
- Perturb by duplicating value \(2\). State whether rank means \(\le x\) or \(\lt x\) before comparing; otherwise two correct implementations may appear inconsistent.
| Variant | Assumptions and schedule | Space or cost | Guarantee/role | Strength | Failure mode | Prefer when |
|---|---|---|---|---|---|---|
| Full KLL | Proven geometric capacities, fair compactions, total order | Near \(O((1/\varepsilon)\log\log(1/\delta))\) items | Additive rank error \(\varepsilon n\) with failure \(\delta\) | Near-optimal randomized space; mergeable design | Parameter or schedule drift | General production quantiles |
| Equal-capacity compactor | Same capacity at each level | \(O(k\log n)\) retained items | Demonstrates weighted compaction; separate analysis required | Simple reference implementation | Mistakenly claiming full KLL space bound | Teaching and invariant tests |
| Deterministic GK | Insertion stream and ordered domain | \(O((1/\varepsilon)\log(\varepsilon n))\) typical bound | Deterministic rank error | No randomness failure | More metadata; merge story differs by implementation | Deterministic guarantees |
| Reservoir sample | Uniform sample of stream items | Fixed sample size | Sampling error, not KLL level guarantee | Very simple; broad reuse | Weak tail/rank efficiency | Exploratory sampling |
| Tail-focused quantile sketch | Variant-specific compaction policy | Parameter-dependent | Improved relative accuracy near tails | Better extreme-percentile focus | Assuming ordinary KLL has same guarantee | Tail SLOs needing relative-rank behavior |
| Exact sort | Store all \(n\) values | \(O(n)\) memory, \(O(n\log n)\) final sort | Exact ranks and quantiles | Audit oracle | Unbounded stream memory | Tests and bounded windows |
Percentiles at Production Scale
In a teaching case, use cards numbered one through sixteen, compact them by coin flips, and verify weighted mass after every move. Learners can query several thresholds and attribute every discrepancy to a specific compaction.
At production scale, a latency service can maintain one KLL sketch per service, region, and time window. Queries return p50, p90, p99, and rank-based SLO diagnostics. Partition sketches merge only when value type, ordering, \(k\) or accuracy parameters, capacity schedule, serialization version, NaN policy, and weighting semantics match. Merge buffers first and compact; averaging percentile values is mathematically invalid.
A retail event platform may use KLL for order-value distributions, but must distinguish unweighted events from weighted transactions. Repeating a value by weight can be too slow, while a native weighted KLL variant needs its own proof and format. Likewise, deletions are not handled by simply inserting a negative-weight value into an ordinary KLL.
Failure cases include adversarial ordering combined with predictable parity, biased pseudo-random bits, overflow of represented weights, incompatible merges, and treating value error as rank error. A p99 rank guarantee does not bound milliseconds when the distribution has a gap. Evidence invalidating deployment includes mass mismatch, exact-audit rank error above the configured envelope, merge results depending excessively on partition layout, serialized-version disagreement, or tail SLO decisions that remain unstable inside the allowed rank interval.
flowchart TD
A[Define rank error and percentile decisions] --> B{Need absolute or tail-relative rank accuracy?}
B -->|absolute| C[Evaluate standard KLL]
B -->|tail-relative| D[Evaluate tail-focused variant]
C --> E[Choose error confidence and schedule]
D --> E
E --> F[Fix type ordering NaN and merge contract]
F --> G[Validate on exact sampled windows]
G --> H{Mass rank error and latency acceptable?}
H -->|no| I[Reject resize or change sketch]
H -->|yes| J[Version and deploy]
J --> K[Monitor drift merges and tail decisions]
K --> L{Assumptions still hold?}
L -->|yes| K
L -->|no| I
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,F navy;
class C,D,E purple;
class G,J,K teal;
class H,I,L crimson;
Percentiles at Production Scale: KLL Compaction & Rank Guarantees
Scenario: an observability platform receives \(2\times10^8\) latency measurements per hour across 40 regions. It needs p50, p90, and p99 with absolute rank error at most 0.5% and audited failure below 0.1%.
- Translate the requirement to \(\varepsilon=0.005,\delta=0.001\); choose a production KLL implementation whose documented parameters meet that contract.
- Version the value type, microsecond unit, ordering, NaN policy, schedule, random-source policy, serialization, and query convention.
- Build compatible regional sketches and merge levels centrally. Never average regional p99 values.
- For 30 representative windows, retain an exact sample or replayable truth set. Measure maximum rank error over a grid of quantiles, tail-specific errors, retained items, update latency, and partition/merge sensitivity.
- Stress duplicates, empty and singleton windows, a large distribution gap, monotone input, and one extreme outlier.
- Decision: deploy only if mass is exact, empirical failures respect the envelope, merge metadata rejects mismatches, and business decisions remain stable across the allowed rank interval. Otherwise enlarge the sketch or use a tail-focused alternative.
Implement and Audit KLL Compaction
Mastery begins with tracing weight, not merely retained values. After every compaction, verify \(\sum_h2^h|L_h|=n\). For several thresholds, compute exact rank, weighted estimated rank, and a ledger of compaction charges. Explain why only one adjacent pair can straddle a fixed threshold in a sorted compaction.
Implementation audits should test fair parity, fresh randomness, odd-buffer handling, cascaded compactions, duplicates, infinities or NaNs, numeric ordering, serialization, and compatible merge. A readable equal-capacity prototype is useful for these invariants, but its \(O(k\log n)\) storage is not the near-optimal KLL theorem. Production claims must be tied to the exact schedule and version actually deployed.
For extension, compare absolute-rank KLL with relative-error quantile sketches, deterministic GK, and reservoir sampling. Investigate weighted updates and sliding windows only through variants with explicit proofs. This bridges ordinary streaming quantiles to mergeable summaries, tail-aware monitoring, and distributed analytics.
Practice: Implement and Audit KLL Compaction
Use stream \([9,1,7,3,8,2,6,4,5,0]\), level capacity four, and supplied parity sequence even, odd, even.
- Recall (2 points): define level weight, compaction, parity, schedule, rank error, and mergeability.
- Trace (5): show every level after each update and compaction; verify represented mass after every step.
- Calculate (4): query thresholds \(2,5,8\); report exact rank, weighted rank, signed error, and responsible compaction.
- Proof (5): prove mass preservation and the per-compaction \(\{-2^h,0,+2^h\}\) error bound.
- Debug (3): always retain even positions on repeated ascending blocks and demonstrate directional error.
- Verify (4): run 100 deterministic seeds on flat, duplicate-heavy, monotone, gapped, and outlier data; report maximum normalized rank error.
- Stretch (4): merge four partition summaries in different tree orders and compare distributions; explain which differences are allowed by randomized guarantees.
Completion criteria: exact mass, explicit rank convention, auditable parity sequence, no incompatible merge, and no claim that the educational constant-capacity code has full KLL space. Rubric: 24–27 professional mastery; 18–23 sound with minor proof gaps; 12–17 revisit weighted ranks; below 12 redo the hand trace.
Choose KLL when mergeable, randomized absolute-rank quantiles and compact memory match the requirement. Audit exact represented mass, fair compaction, the deployed capacity schedule, rank—not value—error, duplicate/NaN conventions, and merge metadata; use a tail-focused or deterministic alternative when those semantics better match the decision.