Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Uniform Streaming Telemetry
Sampler Without Reservoir Bias.

Naively taking k items from every shard gives low-traffic shards equal weight to high-traffic shards, destroying global uniformity.
Start the journey3 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Merge distributed reservoirs by attaching a random priority key u ~ Uniform(0,1) (or weighted key u^(1/w) for forward time decay) to each item and taking the global top-k.

TL;DR30-second simplified summary
▾

Replace unweighted per-shard k-merging with Efraimidis-Spirakis priority keys (or exact shard-count proportional merge) + forward-decay timestamps.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Vitter's Algorithm L
Fast O(k(1 + log(N/k))) single-stream reservoir sampling.
Order Statistics & Min-Heaps
Maintaining the top-k largest random keys in O(log k) per accepted item.
Full walkthrough · 3 stages
01
L4 · FUNDAMENTALS

R & E — Diagnosing the Three Production Biases.

Biased Shard Merge vs. Global Priority-Key Merge

Before · Naive Union of k-Reservoirs
After · Efraimidis-Spirakis Priority Keys

Three distinct bugs cause the analyst complaints:

  1. Equal-Quota Shard Merge: Shard A processes 100k spans/s while Shard B (a quiet region) processes 1k spans/s. Merging k=1,000 from each gives Shard B's spans a 100x higher inclusion probability.
  2. Identical PRNG Seeds: Pods seeded with hash(deploy_timestamp) or a static seed execute identical skip sequences.
  3. No Time Decay: Uniform sampling over an unbounded stream keeps t=0 items with probability k/N, starving recent incidents.
02
L4 · FUNDAMENTALS

H & D — Forward-Decay Weighted Distributed Sampling.

Unbiased Multi-Shard Telemetry Sampling Pipeline

Multi-RegionIngress64 Worker ShardsGlobal Top-k MergerClickHouse OLAPskewed trafficlocal top-k + priorityexact global top-k
Engineering Decision Framework
Problem
How should 64 unevenly loaded telemetry shards merge samples into one unbiased global reservoir?
Naive Solution
Have each shard run Algorithm L independently and concatenate or randomly subsample the 64 reservoirs.
Why It Fails
Without weighting by each shard's exact stream count N_i, low-volume shards are massively over-represented.
Alternatives
Efraimidis-Spirakis priority keys (global top-k merge),Two-phase merge weighted by shard count N_i,Centralize all 2M spans/sec into a single sampler
Engineering Decision
Use Efraimidis-Spirakis log-space priority keys with forward time-decay and per-pod CSPRNG seeding.
Trade-Offs
Uses a min-heap (O(log k) on acceptance) instead of O(1) array swap, but guarantees exact mergeability across arbitrary shard skew.
Decision Exercise · Make the Call

Why does forward decay (t - t0) avoid rewriting existing heap keys as time advances?

To achieve both exact global uniformity across uneven shards and recency weighting, assign each span at timestamp t a forward-decay weight w(t) = exp(lambda * (t - t0)) and a priority key log(u) / w(t) (working in log-space prevents u^(1/w) overflow).

import heapq
import math
import random
from typing import List, Tuple

class DistributedWeightedReservoir:
    def __init__(self, k: int, decay_lambda: float, t0: float, rng: random.Random) -> None:
        self.k = k
        self.decay_lambda = decay_lambda
        self.t0 = t0
        self.rng = rng
        self.heap: List[Tuple[float, str]] = []

    def observe(self, span_id: str, event_ts: float) -> None:
        u = max(self.rng.random(), 1e-16)
        log_weight = self.decay_lambda * (event_ts - self.t0)
        # Equivalent to log(u^(1/w)) = log(u) / exp(log_weight)
        priority = math.log(u) * math.exp(-log_weight)
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, (priority, span_id))
        elif priority > self.heap[0][0]:
            heapq.heapreplace(self.heap, (priority, span_id))
03
L5 · APPLIED DESIGN

E & D — Landmark Overflow & Clock Skew.

Landmark Rebase Lifecycle

t - t0 > 6hRescale k keysWindow tickACTIVE_SAMPLINGREBASE_T0_LANDMARKEMIT_TO_OLAP

If t0 is fixed at cluster boot and lambda = 0.001 / sec, after 9 days lambda * (t - t0) > 709, causing math.exp() to overflow IEEE-754 float64. Rebase t0 every 6 hours by multiplying all k heap priorities by exp(lambda * (t0_new - t0_old)) in O(k) time.

Recommended Learning Flow