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

Design a 1M-Span/Sec Distributed
Tail-Based Trace Sampling Pipeline.

Stateless Tier 1 trace_id routers feed 16 stateful Tier 2 collectors (30s buffer + 80% memory_limiter) and a Kafka -> ClickHouse sink, saving 95% storage while keeping errors.
Start the journey7 stages· Last modified Nov 25, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, pair trace_id consistent hashing with per-service error-storm caps, 1 KB attribute trimming, and 35s preStop draining.

TL;DR30-second simplified summary
▾

At 1,000,000 spans/second (~1.5 GB/s raw OTLP, ~130 TB/day), storing every span in ClickHouse or Tempo is financially prohibitive, yet 1% head-based sampling blinds on-call engineers during Sev-1 incidents. Designing a 1M-Span/Sec Distributed Tail-Based Sampling Pipeline requires solving stateful trace assembly at scale without OOMKilling collectors or impacting live microservice latency.

The architecture splits ingestion into four stages: (1) non-blocking OTel SDKs in microservices propagating W3C traceparent; (2) stateless Tier 1 Edge Collectors that strip oversized payload attributes and route spans via consistent hashing on trace_id; (3) Tier 2 Stateful Tail-Sampling Collectors (16 pods x 4 GB RAM) holding a 30-second trace buffer with 80% memory_limiter breakers, evaluating 100% errors + p99 > 500 ms + VIP debug tenants + 1% healthy; and (4) a Kafka shock-absorber topic feeding batched 100K-row inserts into ClickHouse—cutting storage by 95% (~6.5 TB/day) while preserving 100% incident visibility.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
OpenTelemetry Tail-Based Trace Sampling & Span Context Propagation
Tail-based sampling routes all spans of a trace by trace_id to one stateful collector, waits 30s, and keeps 100% of errors and slow traces while dropping 95%+ of healthy noise.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Full walkthrough · 7 stages
01
STAGE 01 · CAPACITY & STORAGE MATHfoundation

Sizing 1M Spans/Sec, 45 GB Collector RAM & 95% Storage Savings.

Why this matters: Size raw OTLP ingress (1.5 GB/s), 30s Tier 2 RAM buffers (~45 GB), and post-sampling ClickHouse storage.

1,000,000 spans/sec at ~1.5 KB/span = 1.5 GB/s raw ingress (~130 TB/day un-sampled).

Buffering 30 seconds (decision_wait) requires 30M spans x 1.5 KB = ~45 GB active RAM across 16 Tier 2 pods (~4 GB RAM each with headroom).

STAGE 01 · CAPACITY & STORAGE MATH

Sizing 1M Spans/Sec, 45 GB Collector RAM & 95% Storage Savings

1M Spans / SecRaw OTLP Ingress30s Tier 2 BufferStateful RAM5% Policy KeepSampling Funnel6.5 TB / Day StoreCost & Signal SLAevaluates

1.130 TB -> 6.5 TB/Day: Tail sampling cuts daily ClickHouse ingest by 20x without losing a single error trace.

2.RAM Sizing Formula: Collector RAM = (spans_per_sec * decision_wait_s * bytes_per_span) * 1.4 headroom.

3.Attribute Stripping: Dropping >2 KB stack/body tags at Tier 1 shrinks 45 GB buffer requirements further.

16 Tier 2 pods (4 GB each) buffer 30s of 1M spans/sec and reduce ClickHouse ingest from 130 TB/day to 6.5 TB/day.

02
STAGE 02 · TWO-TIER PIPELINEfoundation

Stateless Tier 1 Trace-ID Routers -> Stateful Tier 2 Collectors -> Kafka.

Why this matters: Separate stateless OTLP ingestion/routing from stateful 30s trace assembly and decoupled Kafka -> ClickHouse persistence.

Apps export OTLP/gRPC to local node DaemonSets or Tier 1 stateless collectors, never blocking request threads.

Tier 1 hashes trace_id onto a consistent-hash ring of Tier 2 pods. Tier 2 buffers spans, evaluates rules at t + 30s, and publishes kept traces to Kafka.

STAGE 02 · TWO-TIER PIPELINE

Stateless Tier 1 Trace-ID Routers -> Stateful Tier 2 Collectors -> Kafka

Microservice SDKsApp ExportTier 1 LoadBalanceStateless TierTier 2 Tail PoolStateful TierKafka -> ClickHouseDurable Sinkpins trace_id

1.Zero App Coupling: Application pods never wait on Tier 2 or ClickHouse; full SDK buffers drop telemetry silently.

2.Tier 1 Stateless Scale: Autoscale Tier 1 freely on CPU without disrupting Tier 2 trace_id affinity.

3.Kafka Buffer: Absorbs ClickHouse maintenance or bursty incident error-storms cleanly.

Two-tier trace_id routing plus a Kafka buffer isolates app latency, preserves trace assembly, and protects ClickHouse.

Engineering Decision Framework
Problem
How to implement Design a 1M-Span/Sec Distributed Tail-Based Trace Sampling Pipeline without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, pair trace_id consistent hashing with per-service error-storm caps, 1 KB attribute trimming, and 35s preStop draining.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a 1M-Span/Sec Distributed Tail-Based Trace Sampling Pipeline experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

Consistent-Hash Trace Router & Bounded Memory Tail Buffer.

Why this matters: Implement trace_id consistent-hash routing with unhealthy-node failover and bounded trace eviction.

Use Jump Consistent Hash or Ketama virtual nodes so adding/removing a Tier 2 collector remaps only 1/N traces.

import hashlib

class TraceRingRouter:
    def __init__(self, pods: list[str], vnodes: int = 100) -> None:
        if not pods:
            raise ValueError('At least one Tier 2 pod is required')
        self.ring: list[tuple[int, str]] = []
        for pod in pods:
            for v in range(vnodes):
                h = int(hashlib.md5(f'{pod}#{v}'.encode()).hexdigest()[:8], 16)
                self.ring.append((h, pod))
        self.ring.sort()

    def route_trace(self, trace_id: str) -> str:
        if not trace_id:
            raise ValueError('trace_id cannot be empty')
        h = int(hashlib.md5(trace_id.encode()).hexdigest()[:8], 16)
        for ring_h, pod in self.ring:
            if h <= ring_h:
                return pod
        return self.ring[0][1]
STAGE 03 · SAFE IMPLEMENTATION

Consistent-Hash Trace Router & Bounded Memory Tail Buffer

Validate trace_idInput Check100 Vnodes / PodRing Topologybisect_left(hash)Fast RouteTarget Tier 2 PodTrace Assemblysearches

1.100 Virtual Nodes: 100 vnodes per collector pod keep span distribution within ~5% variance across the ring.

2.1/N Remapping: Scaling from 16 to 17 pods only splits ~6% of active 30s traces instead of 94% with modulo.

3.Health-Check Skip: If a Tier 2 pod fails readiness probes, walk clockwise to the next healthy pod.

100-vnode consistent hashing keeps trace routing O(log V) and limits ring churn during autoscaling.

04
STAGE 04 · SCALING & HOT-TRACE SHEDDINGintermediate

Handling 500K-Span Mega-Traces & Error-Storm Surges.

Why this matters: Prevent Sev-1 error storms (when kept rate jumps from 5% to 80%) from overwhelming Kafka and ClickHouse.

During a major database outage, error rate jumps from 1% to 80%—causing tail sampling to keep 16x more traces than normal!

Apply a per-policy rate-limiting sampler (rate_limiting / probabilistic cap inside and composite policy) so error traces are capped at e.g. 50,000 spans/sec per service during a Sev-1 storm—still plenty for debugging without melting ClickHouse.

STAGE 04 · SCALING & HOT-TRACE SHEDDING

Handling 500K-Span Mega-Traces & Error-Storm Surges

Sev-1 Error Storm16x Keep SurgeError Rate-LimiterStorm Shield10K Span/Trace CapHeap ProtectionHealthy Kafka/CHUsable Under Firepaired with

1.Error-Storm Trap: Keeping 100% of errors unconditionally during a 100%-error outage turns tail sampling into 100% ingestion.

2.Per-Service Error Cap: Capping kept errors per service ensures 1 failing service doesn't crowd out other services' traces.

3.Debuggable Volume: 50,000 error spans/sec still gives on-call engineers thousands of full examples per minute.

Per-service error rate caps and 10K-span trace limits keep ClickHouse queryable during Sev-1 error storms.

05
STAGE 05 · FAULT ISOLATIONadvanced

Memory_Limiter Circuit Breakers & Per-Tenant Span Quotas.

Why this matters: Enforce 80% memory_limiter breakers and Tier 1 tenant quotas so noisy services never OOM collectors.

A single buggy tenant logging 50 KB payloads in span attributes can exhaust Tier 2 RAM.

Configure Tier 1 transform processor to truncate attributes >1 KB and enforce per-tenant token buckets; configure Tier 2 memory_limiter at 80% hard limit.

STAGE 05 · FAULT ISOLATION

Memory_Limiter Circuit Breakers & Per-Tenant Span Quotas

Tier 1 AttributeTrimPayload GuardPer-Tenant QuotaFairness CapTier 2memory_limiterZero OOMKillIsolated AppTrafficApp Safetyprotected by

1.Attribute Bloat Prevention: Truncating oversized SQL/JSON tags at Tier 1 keeps span size predictable (~1.5 KB).

2.Noisy-Neighbor Isolation: Per-service span quotas prevent one chatty microservice from starving the entire company's traces.

3.Graceful Refusal: Refusing spans at 80% RAM preserves already-buffered traces instead of losing all 30s on OOMKill.

Tier 1 attribute truncation, per-service quotas, and 80% memory_limiter breakers prevent collector OOMKills.

06
STAGE 06 · RECOVERY & DEPLOYSadvanced

Two-Phase Ring Draining & Kafka Replay Safety.

Why this matters: Drain Tier 2 collectors cleanly over decision_wait during upgrades and replay Kafka batches idempotently.

Rolling updates on Tier 2 must not drop 30 seconds of in-flight traces.

Remove the pod from Tier 1 service endpoints, sleep decision_wait + 5s (35s) in preStop while evaluating remaining traces, and flush to Kafka before SIGTERM.

STAGE 06 · RECOVERY & DEPLOYS

Two-Phase Ring Draining & Kafka Replay Safety

Pod UnregisterDrain Start35s preStop SleepZero Split TraceKafka Offset CommitAt-Least-OnceClean RolloutProduction Safeflushes to

1.35s Graceful Drain: 5s buffer over 30s decision_wait guarantees the last buffered trace evaluates and exports.

2.Kafka Retention: 72-hour Kafka retention lets ClickHouse survive multi-hour schema migrations without losing traces.

3.Slow HPA Cooldown: Use 5-10 minute scale-in cooldowns on Tier 2 to avoid frequent hash-ring churn.

35s preStop ring draining and post-ACK Kafka offset commits guarantee zero trace loss during deploys.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Synthetic Error Canaries, Rootless-Trace Alerts & FinOps Caps.

Why this matters: Verify end-to-end pipeline health continuously with synthetic error traces and FinOps daily ingest budgets.

You must know immediately if tail sampling stops saving error traces or if ClickHouse storage spikes.

Inject a synthetic canary-error trace every 60s and alert if it isn't queryable in ClickHouse within 45s. Monitor otelcol_processor_refused_spans, rootless_trace_pct, and clickhouse_ingest_gb_per_hour.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Synthetic Error Canaries, Rootless-Trace Alerts & FinOps Caps

60s Error CanaryE2E Livenessrefused_spans > 0Capacity KPIrootless_trace > 5%Affinity KPIKept Ratio > 10%Budget Guardrailcorrelates

1.End-to-End Canary: Proves SDK -> Tier 1 -> Tier 2 -> Kafka -> ClickHouse works end-to-end every single minute.

2.Rootless-Trace Ratio: A jump in orphan child spans flags Tier 1 endpoint-discovery mismatches immediately.

3.Debug-Flag Guardrail: Catches accidental global debug=true flags before daily storage bills explode.

60s synthetic error canaries, rootless-trace alerts, and kept-ratio FinOps caps keep the pipeline reliable.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

During a Sev-1 database outage, 80% of all 1M spans/sec are HTTP 500 error traces. Without a safeguard, what happens to the tail-sampling pipeline?

Recommended Learning Flow