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:

  1. Deterministic rank-bounded summary: a single-stream data structure guaranteeing that after N observations, the returned value's rank lies within epsilon * N of the target rank across every possible input sequence.
  2. Tail-focused centroid sketch: a clustering summary such as a t-digest that allocates high resolution near q = 0 and q = 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 ± epsilon rank 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 at q = 0 and q = 1.
  • Single-stream mechanics: Explain how a deterministic rank-interval summary (such as Greenwald-Khanna) maintains worst-case epsilon * N rank 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

  1. 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 N observations 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 in 1..N. For 0 < q < 1, define the 1-based target rank r = ceil(q * N) (for q = 0 and q = 1, return the exact minimum x_1 and maximum x_N).

    When a value v repeats in the stream (or sits between two stream values), let first = #{x < v} + 1 and last = #{x <= v}. On the sorted rank line, an answer v satisfies additive rank error epsilon when its rank span comes within eps * N of r:

    Sorted ranks:  1 ............ [r - eps*N ........... r ........... r + eps*N] ............ N
    Acceptable v:  #{x < v} + 1 <= r + eps*N     AND     #{x <= v} >= r - eps*N
    

    Concrete example: after N = 1,000,000 requests with eps = 0.001, the budget is eps * N = 1,000 ranks. For p99 (q = 0.99), r = 990,000, so any value covering a rank in 989,000..991,000 (p98.9 through p99.1) is a completely legal answer.

    State three immediate consequences up front:

    1. Rank error does NOT bound numeric value error: If p98.9 is 180 ms and p99.1 is 2,400 ms (a timeout cliff), returning 2,400 ms has 0.1% rank error yet 1,233% value error. Bounding value error requires either assumptions on probability density or value-bucketed histograms.
    2. Additive eps * N rank error washes out extreme tails: At q = 0.999 (r = 999,000) with eps = 0.001, r + eps * N = 1,000,000, so returning the global maximum x_N legally satisfies ± eps * N! Tail monitoring instead wants relative-to-tail rank error, such as |rank(v) - r| <= eps * min(q, 1 - q) * N.
    3. 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.
  2. 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 all n observations 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 v at i = bisect_right(values, v) (after any stored copies of v, matching arrival-order tie-breaking):
      • New minimum (i == 0) or new maximum (i == s): its true rank is known exactly (1 or n + 1), so insert (v, g=1, delta=0).
      • Interior (0 < i < s): v comes after at least r_min(i - 1) items (so its rank is >= r_min(i - 1) + 1) and strictly before v_i (whose rank before this insert was at most r_min(i - 1) + g_i + delta_i, so v's rank is <= r_min(i - 1) + g_i + delta_i). Inserting (v, g=1, delta = g_i + delta_i - 1) gives r_min_new = r_min(i - 1) + 1 and r_max_new = r_min(i - 1) + g_i + delta_i, while 1 + delta_new = g_i + delta_i automatically satisfies the invariant because tuple i already did!
    • Compress periodically (every 1 / (2 * eps) inserts): walk interior tuples (1 <= i <= s - 2, never touching the exact minimum at 0 or maximum at s - 1). Whenever (g_i + g_{i+1}) + delta_{i+1} <= floor(2 * eps * n), delete tuple i and set g_{i+1} += g_i. Notice that no surviving tuple's r_min or r_max changes at all, because prefix sums after i add the exact same total!
    • Why a stored value within eps * n of target r ALWAYS exists: Let i be the first tuple with r_max(i) > r + eps * n. (If none exists, the last tuple has exact rank n, which sits in [r - eps * n, r + eps * n]; and i > 0 because tuple 0 has r_max(0) = 1 <= r.) By choice of i, tuple i - 1 satisfies r_max(i - 1) <= r + eps * n, and using r_min(i) = r_max(i) - delta_i plus the GK invariant on tuple i:
    r_min(i - 1) = r_min(i) - g_i
                 = r_max(i) - (g_i + delta_i)
                 > (r + eps * n) - 2 * eps * n
                 = r - eps * n
    

    Because [r_min(i - 1), r_max(i - 1)] lies completely inside [r - eps * n, r + eps * n], picking the tuple minimizing max(|r - r_min(j)|, |r_max(j) - r|) is guaranteed to have rank error <= eps * n for any distribution, skew, or duplicates!

  3. 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] with eps = 0.2 (compress every 2 inserts, 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 s stored tuples, binary search + tree insert is O(log s) (O(s) array shift in plain Python lists) and compress is O(s) every 1/(2*eps) items (O(eps * s) amortized). Greenwald & Khanna's band-tree COMPRESS proves s = O((1 / eps) * log(eps * N)) worst-case—matching the proven comparison-based lower bound—whereas the greedy adjacent compress above preserves the exact eps * N error proof while its tuple count varies with input order (e.g., on N = 100,000 at eps = 0.01: 74 tuples on random input vs 496 on alternating 0, N, 1, N-1, ..., with worst error <= 1,000 on all of them).

  4. 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 by mean (plus exact min and max), using a steep scale function k(q) to force tiny centroids near q = 0 and q = 1 and allow huge centroids near q = 0.5.

    Using the standard k_1 (arcsine) scale function with compression parameter delta (typically 100 to 500):

    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) <= 1
    

    Differentiate k(q) step by step to see how much stream weight dq = q_right - q_left one centroid can absorb near q: 1. Let u = 2q - 1, so du/dq = 2 and 1 - 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. Therefore dk/dq = delta / (2 * pi * sqrt(q(1 - q))). Setting dk ≈ (dk/dq) * dq <= 1 gives:

    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 at q = 0.999 can still hold 0.2% of the stream—twice the entire 0.1% tail above p99.9—so sharp p99.9 estimates require delta >= 300 (or steeper scale functions k_2, k_3). - O(delta) memory independent of N: From q = 0 to q = 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 than 1 unit of k (otherwise the sweep would have merged them!). So floor(C / 2) < delta / 2, bounding the compressed centroid count C <= ceil(delta) for any N.

  5. Implement the merging t-digest

    Incoming values append to a small buffer in O(1) time. Whenever the buffer fills (b items), flush() sorts the C existing centroids plus b buffer items together and sweeps left to right in O((b + C) log(b + C)) time (O(log(b + C)) amortized per insert when b >= 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 merged
    
  6. Head-to-head comparison: skew, duplicates, memory, and guarantees

    Evaluating both summaries on N = 100,000 observations 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 * N strictly, yet at eps = 0.01 100 ranks of slack legally returns the global maximum for p99.9. On smooth random streams, t-digest(d = 300) achieves 5-rank tail accuracy in just 185 centroids—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,000 discrete values (~25% each of 1, 2, 3, 100 plus 97 copies of 1,000, true p50 = 3, true p99 = 100), t-digest(d = 100) linearly interpolates across step jumps and outputs 2.46 and 154.2—numbers that never occurred in the data (904 ranks off at p99). GK always returns an observed stream value inside eps * N ranks (though duplicate blocks can use more tuples). When distinct values are few, an exact value -> count map 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
    
  7. 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's g counts 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 unless eps is shrunk upfront).
    • Exact GK invariant that DOES survive: Suppose K workers each run GKSummary(eps) with the same eps, maintaining g + delta <= max(1, floor(2 * eps * n_k)) on their local n_k items (sum n_k = N). For any threshold v, worker k gives lo_k(v) <= #{x in worker k : x <= v} <= hi_k(v), where lo_k(v) is r_min of its last stored value <= v (0 if none) and hi_k(v) is r_max(next) - 1 (n_k if v >= max_k). Every worker satisfies hi_k(v) - lo_k(v) <= max(0, floor(2 * eps * n_k) - 1). Summing lo(v) = sum_k lo_k(v) across all K summaries kept side-by-side at the coordinator and returning the smallest stored value u with lo(u) >= r - eps * N preserves the exact eps * N rank bound on the union—at the cost of holding O(K) summaries (sum_k s_k tuples) 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 with eps * N additive rank error with probability >= 1 - p_fail.
      • ReqSketch (randomized): mergeable relative-error quantile sketch whose rank error shrinks proportionally to 1 - q in the tail.
      • DDSketch / log-bucket histograms (deterministic on positive values): bucket i spans (gamma^(i-1), gamma^i] with gamma = (1 + alpha) / (1 - alpha); merging simply adds integer bucket counts (100% associative and order-independent!) and guarantees <= alpha relative value error (~1,100 buckets cover 1 us to 1 hour at alpha = 1%).

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 ± epsilon rank error: Given 1-based target rank r = ceil(q * N) (and exact min/max at q = 0, 1), a returned value v is eps-approximate when its rank interval [#{x < v} + 1, #{x <= v}] overlaps [r - eps * N, r + eps * N], i.e., #{x < v} + 1 <= r + eps * N and #{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 ms to 2,400 ms) produces a giant value jump without density assumptions, and when 1 - q <= eps, additive ± eps * N error covers the entire upper tail up to max.
  • Greenwald-Khanna (GK) deterministic guarantee: Storing (v_i, g_i, delta_i) under the invariant g_i + delta_i <= max(1, floor(2 * eps * n)) proves every query has rank error <= eps * n on all inputs and duplicates; GK's band-aware COMPRESS achieves optimal O((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 to sqrt(q * (1 - q)) / delta, bounding memory at <= ceil(delta) centroids independent of N; 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 * N bound, though summing per-worker count bounds side-by-side across same-eps GK summaries keeps <= eps * N rank error at O(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 (p99 could be p98..p100), ± 1% relative tail rank (p99 is p98.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's g_i measures rank gaps inside its own substream only, and recompressing merged summaries back to O((1/eps) log(eps*N)) accumulates extra rank error per merge level.
  • Averaging per-shard p99 numbers on a dashboard: The average (or weighted average) of 16 workers' local p99s can be arbitrarily far from the global p99 when one shard experiences a latency spike.
  • Extrapolating past [min, max] or ignoring point masses: Always track exact min and max for q = 0 and q = 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) Deterministic eps * N rank bound keeps one GKSummary(eps) per worker (each maintaining g + delta <= max(1, floor(2 * eps * n_k)) at the same eps), ships all K summaries to the coordinator, sums per-worker lower bounds lo(v) = sum_k lo_k(v), and returns the smallest stored u with lo(u) >= r - eps * N—since the stored predecessor p < u has lo(p) < r - eps * N and summed uncertainty hi(p) - lo(p) is either 0 (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 only O(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_i merges 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 in O(1), and query active buckets side-by-side using query_across_workers. For a time-aligned window, zero partial-bucket error is added (<= eps * N_window); for a count-based window of W items split into blocks of size b = eps * W / 4 with per-block eps_block = eps / 3, at most b - 1 expired items in the oldest active block shift ranks by < 2b, keeping total rank error <= (eps / 3) * (W + b) + 2b <= 0.92 * eps * W across ~4 / eps active 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), asserting exact_rank_error <= eps * N on 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 top m largest values: for q = 0.999 on n <= 10,000,000 events per window, keeping just the m = 10,001 largest floats (~80 KB of RAM!) gives the exact p99.9 through p100 when the window closes and is immediately freed. To also measure exact rank error of the production sketch's returned value v_est on that window without storing all n values, either run a second high-precision reference GKSummary(eps_ref = 1e-5) alongside it (bounding v_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

Similar questions

More Exa interview questions

All 2 Exa questions →