Approximate Quantile Sketches Over Unbounded Streams
Hard · Statistics & Math · Machine Learning Engineer · Technical Screen
Prompt
Numeric observations arrive sequentially on an unbounded stream, and your system must answer quantile queries for any q (0 <= q <= 1) using sublinear memory rather than storing the full history. Assume queries are issued only after at least one item has arrived, 0 < epsilon < 1, and queries at q = 0 and q = 1 must return the exact minimum and maximum seen so far.
First, define rigorously what a ± epsilon error contract guarantees—distinguishing rank error from numeric value error (and explaining why rank accuracy alone cannot bound value error without distributional assumptions). Then design and compare two streaming quantile estimators:
- Deterministic rank-bounded summary: a single-stream data structure guaranteeing that after
Nobservations, the returned value's rank lies withinepsilon * Nof the target rank across every possible input sequence. - Tail-focused centroid sketch: a clustering summary such as a t-digest that allocates high resolution near
q = 0andq = 1.
Contrast both designs across memory growth, per-element update latency, behavior on heavy skew and duplicate values, distributed merging across independent workers, and the strength of guarantee each can legitimately claim (in particular, why concatenating and recompressing deterministic rank summaries loses the single-stream epsilon * N bound, and why empirical t-digest tail accuracy is not a worst-case guarantee).
Scope & Expectations
- Precise error semantics: Formulate
± epsilonrank bounds cleanly in the presence of duplicate values, contrast additive rank error against relative-tail rank error and numeric value error, and preserve exact endpoints atq = 0andq = 1. - Single-stream mechanics: Explain how a deterministic rank-interval summary (such as Greenwald-Khanna) maintains worst-case
epsilon * Nrank error, and derive how a t-digest scale function bounds centroid weights near the tails within fixed centroid memory. - Workload trade-offs & distributed merging: Compare skew, point-mass duplicates, CPU/memory costs, and multi-worker merge invariants—stating clearly which guarantees survive distributed aggregation and which sketch families (such as KLL, ReqSketch, or log-bucket histograms) provide formal mergeable bounds.
Step-by-step walkthrough
Define what a ± epsilon rank bound guarantees
An exact streaming percentile algorithm must remember up to
O(N)values: if you discard distinct middle values from the first half of a stream, the second half could consist entirely of tiny numbers (or huge numbers), shifting the true median right into the gap you threw away. Approximation lets us trade tiny rank uncertainty for bounded memory—provided we state precisely what"± epsilon"promises.Sort the
Nobservations seen so far in non-decreasing order (x_1 <= x_2 <= ... <= x_N), breaking ties by arrival order so every observation has a unique rank in1..N. For0 < q < 1, define the 1-based target rankr = ceil(q * N)(forq = 0andq = 1, return the exact minimumx_1and maximumx_N).When a value
vrepeats in the stream (or sits between two stream values), letfirst = #{x < v} + 1andlast = #{x <= v}. On the sorted rank line, an answervsatisfies additive rank errorepsilonwhen its rank span comes withineps * Nofr:Sorted ranks: 1 ............ [r - eps*N ........... r ........... r + eps*N] ............ N Acceptable v: #{x < v} + 1 <= r + eps*N AND #{x <= v} >= r - eps*NConcrete example: after
N = 1,000,000requests witheps = 0.001, the budget iseps * N = 1,000ranks. Forp99(q = 0.99),r = 990,000, so any value covering a rank in989,000..991,000(p98.9throughp99.1) is a completely legal answer.State three immediate consequences up front:
- Rank error does NOT bound numeric value error: If
p98.9is180 msandp99.1is2,400 ms(a timeout cliff), returning2,400 mshas0.1%rank error yet1,233%value error. Bounding value error requires either assumptions on probability density or value-bucketed histograms. - Additive
eps * Nrank error washes out extreme tails: Atq = 0.999(r = 999,000) witheps = 0.001,r + eps * N = 1,000,000, so returning the global maximumx_Nlegally satisfies± eps * N! Tail monitoring instead wants relative-to-tail rank error, such as|rank(v) - r| <= eps * min(q, 1 - q) * N. - Strength of guarantee varies by family: A deterministic summary holds on every stream and arrival order; a randomized sketch holds with probability
>= 1 - p_fail; an empirical summary (like t-digest) is accurate on smooth distributions in practice but has no universal worst-case bound.
- Rank error does NOT bound numeric value error: If
Target 1: How the Greenwald-Khanna (GK) rank-interval invariant works
The Greenwald-Khanna (GK) summary keeps a sorted subset of actual stream values
v_0 <= v_1 <= ... <= v_{s-1}. Instead of knowing each stored item's exact rank among allnobservations seen so far, GK tracks a guaranteed[r_min(i), r_max(i)]rank bracket via two integers per tuple(v_i, g_i, delta_i):g_i = r_min(i) - r_min(i - 1) # count of stream items absorbed in the gap ending at v_i delta_i = r_max(i) - r_min(i) # uncertainty width between v_i's lowest and highest possible rank r_min(i) = g_0 + g_1 + ... + g_i (and g_0 + g_1 + ... + g_{s-1} == n always!) r_max(i) = r_min(i) + delta_i GK Invariant: for every tuple i, g_i + delta_i <= max(1, floor(2 * eps * n))See how insert, compress, and query preserve and exploit this invariant with zero hand-waving:
- Insert
vati = bisect_right(values, v)(after any stored copies ofv, matching arrival-order tie-breaking):- New minimum (
i == 0) or new maximum (i == s): its true rank is known exactly (1orn + 1), so insert(v, g=1, delta=0). - Interior (
0 < i < s):vcomes after at leastr_min(i - 1)items (so its rank is>= r_min(i - 1) + 1) and strictly beforev_i(whose rank before this insert was at mostr_min(i - 1) + g_i + delta_i, sov's rank is<= r_min(i - 1) + g_i + delta_i). Inserting(v, g=1, delta = g_i + delta_i - 1)givesr_min_new = r_min(i - 1) + 1andr_max_new = r_min(i - 1) + g_i + delta_i, while1 + delta_new = g_i + delta_iautomatically satisfies the invariant because tupleialready did!
- New minimum (
- Compress periodically (every
1 / (2 * eps)inserts): walk interior tuples (1 <= i <= s - 2, never touching the exact minimum at0or maximum ats - 1). Whenever(g_i + g_{i+1}) + delta_{i+1} <= floor(2 * eps * n), delete tupleiand setg_{i+1} += g_i. Notice that no surviving tuple'sr_minorr_maxchanges at all, because prefix sums afteriadd the exact same total! - Why a stored value within
eps * nof targetrALWAYS exists: Letibe the first tuple withr_max(i) > r + eps * n. (If none exists, the last tuple has exact rankn, which sits in[r - eps * n, r + eps * n]; andi > 0because tuple0hasr_max(0) = 1 <= r.) By choice ofi, tuplei - 1satisfiesr_max(i - 1) <= r + eps * n, and usingr_min(i) = r_max(i) - delta_iplus the GK invariant on tuplei:
r_min(i - 1) = r_min(i) - g_i = r_max(i) - (g_i + delta_i) > (r + eps * n) - 2 * eps * n = r - eps * nBecause
[r_min(i - 1), r_max(i - 1)]lies completely inside[r - eps * n, r + eps * n], picking the tuple minimizingmax(|r - r_min(j)|, |r_max(j) - r|)is guaranteed to have rank error<= eps * nfor any distribution, skew, or duplicates!- Insert
Implement and trace the deterministic GK summary
import bisect import math class GKSummary: """Deterministic single-stream quantile summary with worst-case rank error <= eps * n.""" def __init__(self, eps: float): self.eps = eps self.n = 0 self.values = [] # sorted subset of observed stream values self.g = [] # g[i] = r_min(i) - r_min(i - 1) self.delta = [] # delta[i] = r_max(i) - r_min(i) def insert(self, v: float) -> None: i = bisect.bisect_right(self.values, v) if i == 0 or i == len(self.values): d = 0 # Exact minimum (rank 1) or maximum (rank n + 1) else: d = self.g[i] + self.delta[i] - 1 self.values.insert(i, v) self.g.insert(i, 1) self.delta.insert(i, d) self.n += 1 step = max(1, int(1.0 / (2.0 * self.eps))) if self.n % step == 0: self.compress() def compress(self) -> None: cap = math.floor(2.0 * self.eps * self.n) i = len(self.values) - 2 # Never delete index 0 (exact min) or the final element (exact max) while i >= 1: if self.g[i] + self.g[i + 1] + self.delta[i + 1] <= cap: self.g[i + 1] += self.g[i] del self.values[i], self.g[i], self.delta[i] i -= 1 def query(self, q: float) -> float: if q <= 0.0: return self.values[0] if q >= 1.0: return self.values[-1] r = min(self.n, max(1, math.ceil(q * self.n))) best_val, best_err = self.values[0], math.inf r_min = 0 for val, g_i, d_i in zip(self.values, self.g, self.delta): r_min += g_i r_max = r_min + d_i err = max(abs(r - r_min), abs(r_max - r)) if err < best_err: best_val, best_err = val, err return best_val def exact_rank_error(sorted_stream, candidate, q: float) -> int: """Exact rank distance from ceil(q * N) to candidate's rank range [first, last].""" n = len(sorted_stream) r = min(n, max(1, math.ceil(q * n))) first = bisect.bisect_left(sorted_stream, candidate) + 1 last = bisect.bisect_right(sorted_stream, candidate) return max(0, first - r, r - last)Mini-trace on
[5, 1, 9, 3, 7, 3, 8, 2, 6, 4]witheps = 0.2(compress every2inserts,cap = floor(0.4 * n)):After [5, 1, 9, 3, 7, 3] (n=6, cap=2): tuples (v, g, delta): (1, 1, 0) (3, 1, 0) (5, 2, 0) (9, 2, 0) [r_min..r_max]: [1..1] [2..2] [4..4] [6..6] Insert 8 (n=7): 8 lands before (9, 2, 0) -> delta = 2 + 0 - 1 = 1 tuples: (1, 1, 0) (3, 1, 0) (5, 2, 0) (8, 1, 1) (9, 2, 0) 8's bracket is [5..6]; in sorted [1, 3, 3, 5, 7, 8, 9], 8 is indeed rank 6! After [2, 6, 4] (n=10, cap=4): tuples: (1, 1, 0) (2, 1, 0) (5, 4, 0) (9, 4, 0) (ranks 1, 2, 6, 10) Query q=0.75 -> target r = ceil(7.5) = 8, budget eps*n = 2: Returns 5 (rank 6, error |8 - 6| = 2 <= 2; true 8th item in 1..9 with two 3s is 7).Complexity & space nuance: With
sstored tuples, binary search + tree insert isO(log s)(O(s)array shift in plain Python lists) andcompressisO(s)every1/(2*eps)items (O(eps * s)amortized). Greenwald & Khanna's band-treeCOMPRESSprovess = O((1 / eps) * log(eps * N))worst-case—matching the proven comparison-based lower bound—whereas the greedy adjacentcompressabove preserves the exacteps * Nerror proof while its tuple count varies with input order (e.g., onN = 100,000ateps = 0.01:74tuples on random input vs496on alternating0, N, 1, N-1, ..., with worst error<= 1,000on all of them).Target 2: Derive the t-digest scale function for tail accuracy
A t-digest takes a completely different trade-off: instead of keeping individual samples under a uniform rank budget, it clusters nearby observations into centroids
(mean, weight)sorted bymean(plus exactminandmax), using a steep scale functionk(q)to force tiny centroids nearq = 0andq = 1and allow huge centroids nearq = 0.5.Using the standard
k_1(arcsine) scale function with compression parameterdelta(typically100to500):k(q) = (delta / (2 * pi)) * asin(2q - 1) for q in [0, 1] Size rule: a centroid spanning quantile range [q_left, q_right] must satisfy k(q_right) - k(q_left) <= 1Differentiate
k(q)step by step to see how much stream weightdq = q_right - q_leftone centroid can absorb nearq: 1. Letu = 2q - 1, sodu/dq = 2and1 - u^2 = 1 - (4q^2 - 4q + 1) = 4q(1 - q). 2. By the chain rule,d/dq [asin(2q - 1)] = 2 / sqrt(4q(1 - q)) = 1 / sqrt(q(1 - q)). 3. Thereforedk/dq = delta / (2 * pi * sqrt(q(1 - q))). Settingdk ≈ (dk/dq) * dq <= 1gives:Max fraction of stream in one centroid near q: dq <= (2 * pi * sqrt(q * (1 - q))) / delta delta = 100: at median q = 0.5 -> dq <= 3.14% of all points (~3,140 points out of 100,000) at tail q = 0.999 -> dq <= 0.20% of all points (~200 points) delta = 1000: at tail q = 0.999 -> dq <= 0.02% of all points (~20 points) at extreme q -> 0,1 -> weight shrinks to 1 (exact observations at the tips!)Notice two crucial facts straight from that algebra: - Sharp resolution limit: at
delta = 100, a centroid atq = 0.999can still hold0.2%of the stream—twice the entire0.1%tail abovep99.9—so sharpp99.9estimates requiredelta >= 300(or steeper scale functionsk_2, k_3). -O(delta)memory independent ofN: Fromq = 0toq = 1,k(1) - k(0) = (delta / (2*pi)) * (pi/2 - (-pi/2)) = delta / 2. After a greedy left-to-right merge sweep, every pair of adjacent centroids(c_0, c_1), (c_2, c_3), ...together spans strictly more than1unit ofk(otherwise the sweep would have merged them!). Sofloor(C / 2) < delta / 2, bounding the compressed centroid countC <= ceil(delta)for anyN.Implement the merging t-digest
Incoming values append to a small buffer in
O(1)time. Whenever the buffer fills (bitems),flush()sorts theCexisting centroids plusbbuffer items together and sweeps left to right inO((b + C) log(b + C))time (O(log(b + C))amortized per insert whenb >= C). Queries linearly interpolate across(0, min), each centroid's midpoint(before + w / 2, mean), and(n, max).import math class TDigest: """Merging t-digest using the k1 (arcsine) scale function.""" def __init__(self, compression: float = 100.0, buffer_size: int = 500): self.compression = compression self.buffer_size = buffer_size self.means = [] self.weights = [] self.buffer = [] self.n = 0 self.min_val = math.inf self.max_val = -math.inf def k_scale(self, q: float) -> float: clamped = max(-1.0, min(1.0, 2.0 * q - 1.0)) return (self.compression / (2.0 * math.pi)) * math.asin(clamped) def add(self, x: float) -> None: self.buffer.append(x) self.n += 1 if x < self.min_val: self.min_val = x if x > self.max_val: self.max_val = x if len(self.buffer) >= self.buffer_size: self.flush() def flush(self) -> None: items = list(zip(self.means, self.weights)) for x in self.buffer: items.append((x, 1)) self.buffer.clear() if not items: return items.sort(key=lambda pair: pair[0]) total = float(self.n) self.means, self.weights = [], [] weight_before = 0.0 cur_mean, cur_w = items[0] for mean, w in items[1:]: k_left = self.k_scale(weight_before / total) k_right = self.k_scale((weight_before + cur_w + w) / total) if k_right - k_left <= 1.0: cur_w += w cur_mean += (mean - cur_mean) * (w / cur_w) else: self.means.append(cur_mean) self.weights.append(cur_w) weight_before += cur_w cur_mean, cur_w = mean, w self.means.append(cur_mean) self.weights.append(cur_w) def quantile(self, q: float) -> float: self.flush() if q <= 0.0: return self.min_val if q >= 1.0: return self.max_val target = q * self.n prev_pos, prev_val = 0.0, self.min_val weight_before = 0.0 for mean, w in zip(self.means, self.weights): center = weight_before + w / 2.0 if target <= center: frac = (target - prev_pos) / (center - prev_pos) return prev_val + frac * (mean - prev_val) prev_pos, prev_val = center, mean weight_before += w frac = (target - prev_pos) / (self.n - prev_pos) return prev_val + frac * (self.max_val - prev_val) def merge_digests(left: TDigest, right: TDigest) -> TDigest: """Combine two t-digests by concatenating centroids and re-running the k-sweep.""" left.flush() right.flush() merged = TDigest(left.compression, left.buffer_size) merged.n = left.n + right.n merged.min_val = min(left.min_val, right.min_val) merged.max_val = max(left.max_val, right.max_val) merged.means = left.means + right.means merged.weights = left.weights + right.weights merged.flush() return mergedHead-to-head comparison: skew, duplicates, memory, and guarantees
Evaluating both summaries on
N = 100,000observations highlights every practical trade-off:Heavy-tailed stream: lognormal(0, 2), true p99.9 = 470.86, max = 3,582.19 Summary Stored items Rank error (p50 / p99 / p99.9) Returned p99.9 ------------------ ------------- -------------------------------- ---------------------------- GK (eps = 0.01) 75 766 / 217 / 100 (bound <= 1000) 3,582.19 (max! 7.6x truth) GK (eps = 0.001) 759 41 / 28 / 59 (bound <= 100) 349.77 (-26% value) t-digest (d = 100) 59 55 / 56 / 43 (no bound) 660.71 (+40% value) t-digest (d = 300) 185 13 / 5 / 5 (no bound) 504.54 (+7% value)- Skew & tails: GK obeys
<= eps * Nstrictly, yet ateps = 0.01100ranks of slack legally returns the global maximum forp99.9. On smooth random streams,t-digest(d = 300)achieves5-rank tail accuracy in just185centroids—however, never claim empirical t-digest numbers as a worst-case bound: constructed adversarial arrival orders force asymmetric centroid growth and large rank errors. - Duplicates & point masses: On
100,000discrete values (~25%each of1, 2, 3, 100plus97copies of1,000, truep50 = 3, truep99 = 100),t-digest(d = 100)linearly interpolates across step jumps and outputs2.46and154.2—numbers that never occurred in the data (904ranks off atp99). GK always returns an observed stream value insideeps * Nranks (though duplicate blocks can use more tuples). When distinct values are few, an exactvalue -> countmap beats both.
Dimension Deterministic GK Merging t-digest (k1) ----------------- -------------------------------------------- -------------------------------------------- Error guarantee Worst-case |rank err| <= eps*N on ALL inputs Empirical only; NO worst-case rank/val bound Memory O((1/eps) log(eps*N)) with band-compress <= ceil(delta) centroids + buffer (O(delta)) Amortized update O(log s + eps*s) with balanced tree O(1) buffer append; O(log(b+C)) per flush Duplicates Bound holds; returns actual observed values Linear interpolation invents unseen values Tail resolution Coarse unless eps << 1 - q Concentrates centroids near q = 0 and q = 1 Distributed merge Cannot merge+recompress to 1-stream size Concatenate + flush in O(delta log delta); without losing eps*N; side-by-side keeps it order-dependent, no formal bound- Skew & tails: GK obeys
Distributed merging across workers: what survives and what breaks
Be crystal clear about distributed merging—this is where imprecise claims fail interviews:
- Why naive GK merging fails: Interleaving tuples
(v, g, delta)from worker A and worker B is invalid because A'sgcounts only A's items, making prefix sums meaningless. And if you merge rank intervals and then recompress back down to single-stream size, each level of a merge tree injects fresh compression error (growing error with tree depth unlessepsis shrunk upfront). - Exact GK invariant that DOES survive: Suppose
Kworkers each runGKSummary(eps)with the sameeps, maintainingg + delta <= max(1, floor(2 * eps * n_k))on their localn_kitems (sum n_k = N). For any thresholdv, workerkgiveslo_k(v) <= #{x in worker k : x <= v} <= hi_k(v), wherelo_k(v)isr_minof its last stored value<= v(0if none) andhi_k(v)isr_max(next) - 1(n_kifv >= max_k). Every worker satisfieshi_k(v) - lo_k(v) <= max(0, floor(2 * eps * n_k) - 1). Summinglo(v) = sum_k lo_k(v)across allKsummaries kept side-by-side at the coordinator and returning the smallest stored valueuwithlo(u) >= r - eps * Npreserves the exacteps * Nrank bound on the union—at the cost of holdingO(K)summaries (sum_k s_ktuples) at the coordinator rather than single-stream space!
import bisect import math def worker_count_lower_bound(summary: GKSummary, v: float) -> int: """Lower bound on #{x <= v} inside one worker's GK summary.""" idx = bisect.bisect_right(summary.values, v) - 1 if idx < 0: return 0 return sum(summary.g[: idx + 1]) def query_across_workers(summaries, q: float) -> float: """Return a value with global rank error <= eps * N from same-eps GK summaries.""" active = [s for s in summaries if s.n > 0] if q <= 0.0: return min(s.values[0] for s in active) if q >= 1.0: return max(s.values[-1] for s in active) n_total = sum(s.n for s in active) target_r = min(n_total, max(1, math.ceil(q * n_total))) threshold = target_r - active[0].eps * n_total candidates = sorted({v for s in active for v in s.values}) for candidate in candidates: lo_total = sum(worker_count_lower_bound(s, candidate) for s in active) if lo_total >= threshold: return candidate return candidates[-1]- When full mergeability + formal bounds are required: Choose a sketch designed for tree merges from day one:
- KLL sketch (randomized): fully mergeable in
O((1/eps) * sqrt(log(1/p_fail)))/ small poly-log space witheps * Nadditive rank error with probability>= 1 - p_fail. - ReqSketch (randomized): mergeable relative-error quantile sketch whose rank error shrinks proportionally to
1 - qin the tail. - DDSketch / log-bucket histograms (deterministic on positive values): bucket
ispans(gamma^(i-1), gamma^i]withgamma = (1 + alpha) / (1 - alpha); merging simply adds integer bucket counts (100% associative and order-independent!) and guarantees<= alpharelative value error (~1,100buckets cover1 usto1 houratalpha = 1%).
- KLL sketch (randomized): fully mergeable in
- Why naive GK merging fails: Interleaving tuples
Intuition & how it works
Estimating percentiles on an endless stream of numbers with tiny RAM is like tracking finishing-time percentiles at a million-runner marathon using a 100-line clipboard. You cannot write down every runner, so two classic designs make opposite promises: Greenwald-Khanna (GK) acts like a strict auditor who saves evenly spaced checkpoint runners along with exact [lowest_possible_rank, highest_possible_rank] brackets so every percentile answer is guaranteed within ± eps * N places, whereas a t-digest acts like a fisheye lens that merges middle-of-the-pack runners into large centroids ((mean, count) cluster summaries) so it can spend fine-grained resolution on the extreme p0.1 and p99.9 tails.
Obvious shortcuts break down quickly. Keeping every observation in a sorted array or heap takes O(N) memory, crashing on unbounded production streams, while uniform random reservoir sampling (keeping k random items with equal probability) needs O(1 / eps^2) space and still gives only a probabilistic bound that routinely misses p99.9 tail spikes. Distributed shortcuts fail too: averaging each worker's local p99 gives a mathematically wrong answer whenever traffic or skew differs across servers, and naively concatenating and recompressing GK summaries breaks GK's error bound.
Walk through N = 1,000,000 API latencies at eps = 0.001 (eps * N = 1,000 ranks) to see how both estimators behave:
1. Query p99 (r = 990,000): GK keeps every stored tuple's g_i + delta_i <= 2 * eps * N = 2,000, guaranteeing a stored value whose true rank lies inside 989,000..991,000 (p98.9 to p99.1) regardless of arrival order or duplicates.
2. Query p99.9 (r = 999,000): GK's ± 1,000-rank window reaches rank 1,000,000, so GK can legally return the single slowest outlier (max) as p99.9!
3. t-digest (delta = 300) on p99.9: Its arcsine scale function (a monotonic curve mapping quantile q to centroid budget units) caps centroid weight near q = 0.999 to ~0.07% of the stream and 1 point at the extreme tips, empirically landing within a few ranks on smooth data—while trading away any worst-case adversarial bound.
Key points
- Exact definition of
± epsilonrank error: Given1-based target rankr = ceil(q * N)(and exactmin/maxatq = 0, 1), a returned valueviseps-approximate when its rank interval[#{x < v} + 1, #{x <= v}]overlaps[r - eps * N, r + eps * N], i.e.,#{x < v} + 1 <= r + eps * Nand#{x <= v} >= r - eps * N. - Rank error is NOT value error, and additive error is weak in tails: A tiny rank gap across a latency cliff (
180 msto2,400 ms) produces a giant value jump without density assumptions, and when1 - q <= eps, additive± eps * Nerror covers the entire upper tail up tomax. - Greenwald-Khanna (GK) deterministic guarantee: Storing
(v_i, g_i, delta_i)under the invariantg_i + delta_i <= max(1, floor(2 * eps * n))proves every query has rank error<= eps * non all inputs and duplicates; GK's band-awareCOMPRESSachieves optimalO((1 / eps) * log(eps * N))deterministic space, while greedy adjacent compression keeps the exact error bound with order-dependent space. - t-digest tail focus and honest limits: Mapping quantiles via
k(q) = (delta / (2 * pi)) * asin(2q - 1)shrinks centroid capacity proportional tosqrt(q * (1 - q)) / delta, bounding memory at<= ceil(delta)centroids independent ofN; it excels empirically on smooth tails, yet carries no worst-case guarantee and can interpolate values that never occurred on discrete data. - Distributed merge invariants: GK tuples cannot be interleaved or recompressed back to single-stream size without losing the original
eps * Nbound, though summing per-worker count bounds side-by-side across same-epsGK summaries keeps<= eps * Nrank error atO(K)coordinator space; if compact associative merges with proofs are required, use KLL or ReqSketch (randomized rank bounds) or DDSketch log-bucket histograms (deterministic relative value error).
Common mistakes
- Saying "
± 1%percentile error" without specifying the axis:± 1%additive rank (p99could bep98..p100),± 1%relative tail rank (p99isp98.99..p99.01), and± 1%numeric value (200 ms ± 2 ms) are completely different guarantees. - Presenting empirical t-digest benchmarks as a mathematical guarantee: Adversarial insertion orders (such as carefully ordered or alternating bursts) violate t-digest's implicit smoothness assumptions and produce much larger rank errors.
- Concatenating or interleaving GK
(v, g, delta)tuples across workers: Each worker'sg_imeasures rank gaps inside its own substream only, and recompressing merged summaries back toO((1/eps) log(eps*N))accumulates extra rank error per merge level. - Averaging per-shard
p99numbers on a dashboard: The average (or weighted average) of 16 workers' localp99s can be arbitrarily far from the globalp99when one shard experiences a latency spike. - Extrapolating past
[min, max]or ignoring point masses: Always track exactminandmaxforq = 0andq = 1, clamp interpolated estimates to[min, max], and watch for t-digest returning fractional phantom values on integer/categorical streams.
Follow-up questions
- If multiple shards process disjoint substreams, what concrete designs keep a rigorous global error guarantee at query time? Three clean options preserve strict guarantees depending on your contract: (1) Exact distributed selection (if workers retain raw window data) binary-searches the value range over
O(log(range / precision))coordinator rounds asking each worker for#{x <= mid}; (2) Deterministiceps * Nrank bound keeps oneGKSummary(eps)per worker (each maintainingg + delta <= max(1, floor(2 * eps * n_k))at the sameeps), ships allKsummaries to the coordinator, sums per-worker lower boundslo(v) = sum_k lo_k(v), and returns the smallest storeduwithlo(u) >= r - eps * N—since the stored predecessorp < uhaslo(p) < r - eps * Nand summed uncertaintyhi(p) - lo(p)is either0(exact) or<= 2 * eps * N - 1,u's ranks[#{x < u} + 1, #{x <= u}]are guaranteed to overlap[r - eps * N, r + eps * N], trading onlyO(K)coordinator space; (3) Deterministic relative value bound uses identical logarithmic buckets (DDSketch) on every worker, where summing bucket counts equals the single-stream sketch identically. - How would you adapt your quantile estimator if queries only cover a moving time-based or count-based window rather than all history? Comparison-based summaries like GK cannot delete arbitrary old items (
g_imerges erase which timestamps fell in a gap), so split time or count into tumbling sub-buckets (for instance, 60 one-minute buckets for a 1-hour sliding window), maintain an independent summary per bucket, drop expired buckets inO(1), and query active buckets side-by-side usingquery_across_workers. For a time-aligned window, zero partial-bucket error is added (<= eps * N_window); for a count-based window ofWitems split into blocks of sizeb = eps * W / 4with per-blockeps_block = eps / 3, at mostb - 1expired items in the oldest active block shift ranks by< 2b, keeping total rank error<= (eps / 3) * (W + b) + 2b <= 0.92 * eps * Wacross~4 / epsactive blocks. If positive relative value error suffices, log-bucket histograms are even simpler because expiring a 1-minute bucket just subtracts its integer count vector. - Why must your test harness vary both stream arrival patterns and multi-shard merge topologies when benchmarking these sketches? GK's rank-error bound holds under every insertion order, whereas its tuple count varies up to ~7x between sorted/random streams and adversarial zigzag streams (
0, N, 1, N-1, ...); meanwhile, t-digest's accuracy itself shifts across both insertion orders and merge-tree topologies (for example, single-stream vs sequential left-fold merge vs balanced binary tree over 16 shards). A trustworthy validation suite must therefore test a full matrix of arrival orders (random i.i.d., sorted ascending/descending, alternating extremes, heavy duplicate cliffs, diurnal bursts) crossed with merge shapes (single stream, skewed 90%-on-one-shard, range-partitioned shards, left-deep chain, balanced tree), assertingexact_rank_error <= eps * Non every GK run and tracking p50/p99/p99.9 error distributions against your budget for t-digest. - How can you audit production tail-quantile accuracy online without retaining the unbounded raw event stream? Compute exact upper tails over bounded tumbling audit windows (say 5-minute slices on a sampled host) using a min-heap (a binary tree that pops the smallest stored element in
O(log m)time) holding only the topmlargest values: forq = 0.999onn <= 10,000,000events per window, keeping just them = 10,001largest floats (~80 KBof RAM!) gives the exactp99.9throughp100when the window closes and is immediately freed. To also measure exact rank error of the production sketch's returned valuev_eston that window without storing allnvalues, either run a second high-precision referenceGKSummary(eps_ref = 1e-5)alongside it (boundingv_est's true rank within± 10^-5 * n) or replay a two-pass shadow ring buffer on 1% of windows, logging only scalar tail error metrics afterward.
Follow-up questions
- If multiple shards process disjoint substreams, what concrete designs keep a rigorous global error guarantee at query time?
- How would you adapt your quantile estimator if queries only cover a moving time-based or count-based window rather than all history?
- Why must your test harness vary both stream arrival patterns and multi-shard merge topologies when benchmarking these sketches?
- How can you audit production tail-quantile accuracy online without retaining the unbounded raw event stream?
Similar questions
- Pairwise Dot-Product Contrastive Loss
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations
- Impact of Dataset Duplication on OLS and Large-Sample Inference