Kafka Consumer Architecture for Distributed Trace Grouping

Medium · System Design · Backend Engineer · Onsite

Prompt

Architect a distributed stream-processing service that reads distributed tracing events from Apache Kafka, collects every event associated with a given traceId, and passes each assembled trace to an existing downstream handler process_trace(trace_id, events).

Keep the following system rules and operating conditions in mind:

  • Incoming span events arrive over Kafka, and all events belonging to a logical trace carry the same traceId.
  • Active trace lifespans span several orders of magnitude: interactive requests finish within seconds, whereas background workflows can remain active for multiple hours.
  • Treating process_trace(trace_id, events) as an already-implemented black box, focus strictly on ingestion, grouping, state storage, completion detection, and delivery guarantees.
  • Event volume, trace cardinality, payload sizes, and processing latency targets are intentionally left open—begin by clarifying key assumptions (such as Kafka topic partitioning, whether any explicit root/end signal exists, out-of-order and straggler behavior, and whether process_trace is idempotent).

Walk your design through three progressive stages:

  1. In-consumer memory grouping: Route every event of a traceId to a single consumer instance (including what changes if the source topic uses a different partition key), hold open traces in worker RAM, and evaluate memory pressure, Kafka offset checkpointing, crash recovery, and consumer-group rebalances when traces run for hours.
  2. Externalized trace storage: Offload per-trace payloads from consumer RAM into an external database keyed by traceId with duplicate-safe writes, explain how consumer memory stays bounded and how offset commits coordinate with durable writes, detail how large traces are streamed into process_trace, and weigh the added infrastructure and latency costs.
  3. Completion detection and execution: Define how the service decides a trace is ready across both sub-minute requests and multi-hour jobs (combining completion markers, idle windows, hard duration caps, and optional periodic partial emissions), surface due traces efficiently without scanning all active state, coordinate single-worker execution with retries, and handle straggler events arriving after emission.

Scope & Expectations

  • Establish realistic throughput, trace-size, and completion-latency numbers, and explain how partition keys, consumer rebalances, and Kafka offset commits interact with multi-hour open traces.
  • Justify why pure in-memory buffering breaks down at multi-hour horizons, then specify an external storage schema, bounded-memory write pipeline, and paginated read path for oversized traces.
  • Combine completion heuristics that work for both fast requests and multi-hour workflows, pair them with sub-linear timer scheduling, and enforce single-claim execution across retries and late arrivals.

Step-by-step walkthrough

  1. Clarify requirements and scale assumptions

    In distributed tracing, a trace is the record of one end-to-end workflow (such as an HTTP checkout request or a multi-hour batch pipeline), and each individual unit of work inside it is an event called a span (for example, one database query or microservice call). Every span carries the same traceId.

    Grouping events by a key is easy when every group finishes within a few seconds. This problem is challenging because a single trace can stay open for several hours, which puts three things under stress at the same time: consumer memory, Kafka recovery position (offsets), and the rule that decides "this trace is finally complete."

    Functional requirements

    • Consume span events from a Kafka topic where every event carries a traceId.
    • Gather all events sharing a traceId and invoke process_trace(trace_id, events) once the trace is complete.
    • Handle out-of-order events, duplicate deliveries, and late-arriving stragglers gracefully.
    • Support both fast request traces (lasting seconds) and long background traces (lasting up to several hours).

    Non-functional requirements

    • Throughput: 400,000 events/s on average, 1,000,000 events/s at peak, with roughly 1 million traces open simultaneously.
    • Latency: Short traces processed within 60 seconds of their last event (99th percentile, or p99); multi-hour traces emitted within a few minutes of finishing, with optional periodic updates along the way.
    • Bounded memory: Consumer RAM must stay small and predictable regardless of how many hours a trace runs.
    • Durability and correctness: No event written to Kafka is silently lost, and each trace produces one final result in effect (effectively-once processing), surviving consumer crashes, group rebalances, and temporary datastore outages.

    Clarifying questions and assumed answers

    • How big is a trace? Median 10 events, average 25 events, p99 300 events (~1 KB per event). Rare runaway batch jobs can emit millions of spans, so we enforce a safety cap of 1,000,000 events (or 1 GB) per trace and flag anything larger as truncated.
    • Is the Kafka topic already partitioned by traceId? Assume collectors set the Kafka message key to traceId. Below we also cover re-keying when the source topic uses another partition key (such as service name).
    • Can we rely on a dedicated closing event? Usually the top-level span (root span) finishes last, but we cannot rely on it alone: asynchronous child jobs can finish after the root span, events arrive out of order, and a crashed service may never emit its root span.
    • Is process_trace safe to call more than once? Assume process_trace writes its output keyed by trace_id as an upsert (an insert that overwrites any prior result for that key), making re-runs with the same or a more complete set of events safe. We also note how to handle non-idempotent side effects.
    • What happens to multi-hour traces and late events? Emit a partial result every 15 minutes for long-running traces plus a final result when complete. If a late event arrives after completion while the trace's events are still in storage (within 8 hours), re-run process_trace up to 3 times; beyond that, count and drop it.
  2. Back-of-the-envelope capacity estimates

    Before choosing an architecture, we size the data rate, the number of open traces, and the stark difference between trace metadata (tiny) and raw event payloads (huge). We use Little's Law, which says the average number of items concurrently open equals the arrival rate multiplied by the average time each item stays open (open = arrival_rate * time_open).

    1. Kafka ingestion
       Event rate            400,000 events/s avg, 1,000,000/s peak (~1 KB per event)
       Byte rate             400 MB/s avg, 1 GB/s peak
       Partitions            256 partitions -> ~1.56 MB/s avg, ~4 MB/s (~4,000 events/s) peak each
       Consumer instances    64 assembler workers -> 4 partitions per worker
       Kafka retention       24 hours -> 400 MB/s x 86,400 s = ~35 TB raw (~105 TB with 3x replication)
    
    2. Concurrent open traces (Little's Law)
       New traces/s          400,000 events/s / 25 events per trace = 16,000 traces/s
       Short traces (99.5%)  15,920/s x (~10 s active + ~30 s quiet wait) = ~637,000 open
       Long traces  (0.5%)       80/s x ~3,600 s (1 hour avg, up to 6 h)  = ~288,000 open
       Total open traces     ~925,000 globally -> ~3,600 open traces per partition
    
    3. Cost of naive in-memory buffering (RAM baseline)
       Assume long traces average 250 events -> 80/s x 250 = 20,000 events/s (20 MB/s, or 5% of volume)
       Short-trace payload   380 MB/s x ~35 s avg wait in RAM  = ~13.3 GB raw
       Long-trace payload     20 MB/s x ~3,600 s avg wait      = ~72.0 GB raw
       Total raw bytes       ~85 GB raw -> ~170-250 GB actual JVM/Python heap with object overhead!
       Kafka offset lag      ~1,125 open long traces per partition -> oldest open trace is ~6 h old
                             crash replay per partition = 6 h x 1.56 MB/s = ~34 GB (~136 GB per worker!)
    
    4. External datastore sizing
       Write rate            400,000 rows/s avg, 1,000,000/s peak; replication factor (RF) = 3
                             -> 1.2M replica writes/s avg, 3M replica writes/s peak
       Store cluster         at ~100,000 replica writes/s per node -> 30 nodes for peak, 45 with 1.5x headroom
       Disk (8 h retention)  400 MB/s x 28,800 s = ~11.5 TB raw -> x3 replicas = ~34.5 TB -> ~12 TB compressed
       Read rate             ~400 MB/s (read once on completion) + ~100 MB/s for 15-min partial runs
    
    5. Per-trace completion metadata (tiny!)
       ~925,000 open traces x ~200 bytes = ~185 MB total (~740 KB per partition)
    

    Three design lessons jump right out of the numbers:

    • Completion metadata and raw events differ in size by ~500x. Deciding when a trace is done takes less than 1 MB of state per partition, while storing the raw events takes ~12 TB on disk. They belong in different places.
    • In-memory buffering fails on recovery time even more than on RAM. Even if we bought 250 GB of RAM, one 6-hour trace pins its Kafka partition's recovery checkpoint 6 hours in the past, forcing 34 GB of replay per partition on every restart.
    • The external store is write-heavy, read-once, and short-lived. Every event is written once, read sequentially by traceId a few minutes or hours later, and discarded after 8 hours.
  3. Interfaces and contracts

    This is a backend pipeline service, so its interfaces are the incoming Kafka event schema, the contract with process_trace, an internal trace-ready notification topic, and a small operator API.

    1. Input Kafka topic: "spans" (256 partitions, key = traceId bytes)
       Value (~1 KB):
         { trace_id, span_id, parent_span_id, service, operation,
           start_ts_ms, end_ts_ms, is_root, status, attributes: {...} }
       Kafka record timestamp: LogAppendTime (broker arrival clock, not emitter clock)
    
    2. Processing contract
       process_trace(trace_id: str, events: Iterator[SpanEvent]) -> None
       - events are streamed in (start_ts_ms, span_id) order with duplicates removed
       - idempotent by trace_id (a later run overwrites an earlier partial or incomplete run)
    
    3. Internal Kafka topic: "trace-ready" (256 partitions, key = traceId bytes)
       Value:
         { trace_id, kind: "PARTIAL" | "FINAL" | "REOPEN",
           reason: "ROOT_END" | "IDLE_TIMEOUT" | "MAX_DURATION",
           last_offset, shard_count, expected_events, emitted_at_ms }
    
    4. Operator control API
       GET  /v1/traces/{trace_id}/state  -> inspect live state, event count, and due time
       PUT  /v1/policies/{root_service}  -> override { idle_timeout_s, max_duration_s, partial_every_s }
       POST /v1/replays                  -> { from_ts, to_ts, mode: "RECOVER" | "RECOMPUTE" }
    

    Two choices in these contracts prevent headaches later:

    • events is a lazy iterator, not an in-memory list. Streaming events page by page lets a worker process a 500 MB trace without holding all 500,000 objects in memory at once (if legacy process_trace code requires a list, we route huge traces to a dedicated high-RAM worker pool).
    • We use Kafka's broker append timestamp (LogAppendTime) as our clock. Application servers often have skewed system clocks. Stamping each event when Kafka receives it gives monotonic, trustworthy timestamps that stay identical if we ever replay the topic.
  4. Route by traceId and evaluate in-memory buffering

    How events of one trace reach one consumer. In Kafka, a topic is split into ordered logs called partitions, and within a consumer group, Kafka assigns each partition to at most one consumer instance at a time. Producers pick a partition by hashing the message key modulo the partition count (hash(traceId) % 256). As long as every producer uses the exact same hash algorithm, all spans for a traceId land in the same partition and arrive at the same consumer.

    Production gotcha on hash functions: Java Kafka clients default to murmur2, while C/Go/Python clients built on librdkafka historically defaulted to crc32. Mixing them splits one trace across two partitions! Every producer must standardize on murmur2_random. Also, never change the partition count (256) on a live topic, because changing the modulus changes hash(traceId) % N and splits currently open traces across two owners.

    What if the input topic is NOT keyed by traceId? 1. Best fix: Update the upstream trace collectors to set key = traceId (zero extra infrastructure). 2. Fallback if producers cannot be changed: Run a lightweight, stateless re-keying consumer group that reads the unkeyed source topic and immediately publishes each event to an internal spans-by-trace topic with key = traceId. That doubles Kafka network and disk throughput (+400 MB/s in and out) and adds ~5–10 ms of latency, but restores single-consumer ownership cleanly.

    How the naive in-memory design works — and why offset commits get stuck. Suppose each consumer buffers open_traces[trace_id] -> list_of_events in RAM. In Kafka, committing an offset X means telling Kafka: "Every message before position X is completely finished; never send them again after a crash." Because an event at offset 200 is not finished until its entire trace calls process_trace, the consumer can only commit up to the first offset of its oldest still-open trace:

    Partition 4 log:
    offset:  200            201           202 ... 9,200,000    9,200,001
    trace:   [tr_batch_01]  [tr_web_88]   [tr_web_88]          [tr_web_99]
              ^              \________closed at t=12s______/
              |
         tr_batch_01 is a 6-hour batch job (still OPEN!)
         Safe committed offset is stuck at 200 for 6 full hours!
    
    def safe_commit_offset(open_traces: dict, next_poll_offset: int) -> int:
        """Return the highest Kafka offset safe to commit for one partition.
        Every event strictly before this offset belongs to an already-processed trace."""
        # If no traces are open, every consumed event so far is safe to commit.
        oldest_unprocessed_offset = next_poll_offset
    
        for trace_meta in open_traces.values():
            # Pin the commit point at the earliest event of any still-open trace.
            if trace_meta.first_offset < oldest_unprocessed_offset:
                oldest_unprocessed_offset = trace_meta.first_offset
    
        return oldest_unprocessed_offset
    

    Clear verdict on in-memory grouping: It works well when traces last at most 30–60 seconds, because RAM stays ~15 GB and crash replay is under a minute. When traces last hours, pure in-memory grouping does not scale for three reasons: 1. Unbounded, skewed RAM: Heap usage reaches ~170–250 GB, and one partition unlucky enough to receive three huge batch traces crashes with an Out-Of-Memory error, triggering a rebalance cascade. 2. Stalled Kafka offsets: With ~1,125 multi-hour traces open per partition, the safe commit offset is permanently ~6 hours behind. Every crash or deploy replays ~34 GB per partition (~136 GB per worker). 3. Destructive rebalances: Whenever a partition moves to a new consumer during a deploy or scale-out, all RAM state on the old owner is lost. While replaying 6 hours of data, short traces that already finished 5 hours ago get processed a second time, and traces that started before the 6-hour commit point get re-processed with only their second half — overwriting a good result with a partial fragment!

  5. External datastore schema and state separation

    To decouple memory and offset commits from trace duration, we separate our data by size and access pattern into three purpose-built stores:

    1. Raw event payloads -> Wide-column LSM store (Apache Cassandra or ScyllaDB). An LSM-tree (Log-Structured Merge-tree) database turns random writes into fast sequential disk appends, making 1,000,000 writes/s routine. Each row carries an 8-hour TTL (time-to-live, an automatic expiration timestamp). Using TimeWindowCompactionStrategy groups disk files into 1-hour buckets and drops whole expired files at once — avoiding per-row DELETE statements, which in Cassandra create slow deletion markers called tombstones.

    CREATE TABLE trace_events (
      trace_id    blob,
      shard       smallint,    -- 0 for normal traces; 0..63 once a trace exceeds 10,000 spans
      start_ts_ms bigint,
      span_id     blob,        -- unique within trace (or SHA-256 hash of payload if missing)
      payload     blob,
      PRIMARY KEY ((trace_id, shard), start_ts_ms, span_id)
    ) WITH CLUSTERING ORDER BY (start_ts_ms ASC, span_id ASC)
      AND default_time_to_live = 28800
      AND compaction = {
        'class': 'TimeWindowCompactionStrategy',
        'compaction_window_unit': 'HOURS',
        'compaction_window_size': 1
      };
    
    • Why writes tolerate duplicates (idempotent writes): Re-sending the exact same span writes the exact same primary key ((trace_id, shard), start_ts_ms, span_id), harmlessly overwriting identical bytes.
    • Why shard prevents hot partitions: Wide-column databases struggle when one partition exceeds ~100 MB. Every trace starts writing to shard = 0. If event_count crosses 10,000 (~10 MB), the assembler flips shard_count = 64 in metadata and routes subsequent spans to shard = hash(span_id) % 64, spreading a 1 GB trace into ~16 MB slices across the cluster.

    2. Per-trace completion metadata -> Consumer RAM backed by a compacted Kafka changelog (trace-meta). Only the single consumer owning a partition updates its traces' metadata, and ~3,600 open traces × 200 bytes is under 1 MB per partition! We keep TraceMeta in consumer RAM for zero-latency updates and back it up to a log-compacted Kafka topic trace-meta (256 partitions, co-partitioned with spans). Log compaction is a Kafka background cleanup mode that keeps only the most recent value for each trace_id key, and deletes a key completely when given a null value (a Kafka tombstone). Using 10-minute log segments ensures a crashed consumer can restore a partition's entire metadata in a couple of seconds (~8 MB of live state).

    TraceMeta ( ~200 bytes in RAM, backed by compacted topic "trace-meta" )
      trace_id          bytes
      state             "OPEN" | "EMITTED"
      first_seen_ms     broker timestamp of first span seen
      last_seen_ms      broker timestamp of latest span seen
      last_offset       highest Kafka offset folded into this trace so far
      max_gap_s         longest quiet gap observed between consecutive spans of this trace
      root_end_ms       broker timestamp when the root span arrived (or null)
      event_count       spans seen so far
      shard_count       1 (default) or 64 (after 10,000 spans)
      last_partial_ms   when the most recent 15-min PARTIAL run was triggered
      reopen_count      how many times late events reopened this trace (capped at 3)
    

    3. Processing ledger -> Key-value table with conditional writes (DynamoDB or sharded PostgreSQL). To guarantee two workers never process the same trace state concurrently or repeat work, we keep one small ledger row per trace (~35,000 conditional writes/s: 16,000 traces/s × 2 transitions claim + done, plus partials). Keeping this out of Cassandra avoids Cassandra's expensive multi-round Paxos transactions on the high-volume event cluster.

    trace_ledger (key = trace_id, TTL = 7 days)
      status            "PROCESSING" | "DONE"
      generation        integer incremented on every claim (fencing token against slow workers)
      covered_offset    highest Kafka offset included in the last completed run
      covered_events    number of events processed in the last completed run
      shard_count       max shard_count ever seen for this trace (1 or 64)
      worker_id         ID of worker currently holding the lease
      lease_until_ms    when the current worker's lease expires if it crashes
    
  6. End-to-end architecture and bounded-memory write path

    Separating Assemblers (fast, stateful per-partition ingestion and timer tracking) from Processors (stateless workers that stream events from the store and run process_trace) ensures a slow 1 GB process_trace call never stalls Kafka consumption.

     Emitting services / collectors (key = traceId, murmur2 hash)
          |
          v
     Kafka "spans" (256 partitions, retention 24 h)
          |
          v
     Assembler Consumer Group (64 workers, 4 partitions each)
       In RAM per partition: TraceMeta dict (~8 MB) + Due-Time Min-Heap
          |                                         ^
          | (1) Async batched QUORUM writes         | restore on startup /
          v                                         v commit every 2 s (Kafka txn)
     Cassandra / ScyllaDB                 Kafka "trace-meta" (compacted changelog)
     "trace_events" (RF=3, TTL=8h)              +
          ^                               Kafka "trace-ready" (completion jobs)
          |                                         |
          | (3) Paged read (5,000 rows/page)        | (2) Consume ready jobs
          +-----------------------------------------+
                                                    v
                               Processor Worker Pool (autoscaled; dedicated pool for >100 MB traces)
                                    |                        |
                         conditional claim / done       process_trace(trace_id, event_iterator)
                                    v
                             "trace_ledger" (DynamoDB)
    

    How the write path keeps RAM bounded and offsets fresh (every 2 seconds): 1. Poll and write: Every ~200 ms, an assembler polls a batch of spans, groups them by (trace_id, shard), fires async batched writes to Cassandra at LOCAL_QUORUM (meaning at least 2 of the 3 replicas confirm the write on disk), and updates TraceMeta in RAM. In-flight unacknowledged bytes are capped at 64 MB per worker; if Cassandra slows down, the worker calls Kafka's pause() on its partitions while continuing empty poll() heartbeats so it stays alive in the group without growing memory. 2. Wait for durability, then commit atomically: Every 2 seconds, the assembler waits for all prior Cassandra writes to succeed, then executes one Kafka transaction that atomically writes: - dirty TraceMeta updates (plus null tombstones for EMITTED markers older than 30 minutes) to trace-meta, - any newly triggered completion messages to trace-ready, and - the consumed spans offsets (sendOffsetsToTransaction).

    Because offsets only advance after Cassandra confirms the event writes, no event is ever lost. Because TraceMeta, trace-ready, and offsets commit in one atomic Kafka transaction, a crash replays at most 2 seconds of events (~3 MB per partition instead of 34 GB!), and event_count is never double-counted.

    How processors stream huge traces without running out of memory: A processor reads shard_count (1 or 64), opens one paginated query (5,000 rows per page at LOCAL_QUORUM) per shard, and merges the already-sorted shard iterators using a min-heap (k-way merge). Memory usage is 64 shards × 5,000 rows × 1 KB ≈ 320 MB worst case (or 5 MB for 1-shard traces), never the full 1 GB trace!

    import heapq
    from typing import Iterable, Iterator
    
    
    def stream_merged_events(shard_iterators: list[Iterable]) -> Iterator:
        """Stream all events of a trace in (start_ts_ms, span_id) order without duplicates.
        Each shard_iterator pages rows from Cassandra already sorted by (start_ts_ms, span_id)."""
        # heapq.merge pulls the smallest next item across all shards, holding 1 page per shard.
        merged_stream = heapq.merge(
            *shard_iterators,
            key=lambda event: (event.start_ts_ms, event.span_id),
        )
    
        previous_key = None
        for event in merged_stream:
            current_key = (event.start_ts_ms, event.span_id)
            # Skip adjacent duplicates caused by at-least-once retries or shard transitions.
            if current_key != previous_key:
                yield event
                previous_key = current_key
    

    Cost vs. in-memory (and an optional hybrid optimization): Externalizing events adds a 45-node database cluster, ~12 TB of SSD storage, and two extra network hops per event (+10–50 ms processing latency). If cost is tight, notice that 99.5% of traces finish within 60 seconds: a hybrid assembler can buffer traces in RAM for their first 60 seconds (or up to 256 KB) and spill to Cassandra only when a trace exceeds 60 seconds or 256 KB, cutting database writes by ~90% while keeping Kafka replay under ~60 seconds. In an interview, present the clean external-store design first and offer the 60-second RAM tier as a cost optimization.

  7. Completion signals, stream time, and lazy min-heap timers

    No single completion rule works for both a 200 ms web request and a 4-hour Spark batch job:

    Completion signal Strengths How it misfires alone
    Explicit root-span end Closes synchronous requests fast (~10 s) Async background spans can arrive after the root; lost or sampled roots leave traces open forever
    Inactivity timeout Closes any trace even if the root span is lost A short 30 s timeout slices a batch job in half during a quiet step; a 30 min timeout delays every web trace by 30 min
    Hard max duration (6 h) Guarantees every trace eventually closes Cuts genuinely longer workflows at 6 hours

    Combining all three with an adaptive gap timeout: We trigger completion at the earliest of: 1. Root span + short grace period (10 s) after both the root span and the latest span seen (so async children arriving right after the root extend the 10 s grace window), 2. Adaptive inactivity timeout: starts at 30 seconds for fast traces, and scales up to 3 * max_gap_s (capped at 30 minutes) if a trace has already demonstrated long quiet pauses (operators can also configure per-service timeouts via /v1/policies), 3. Maximum duration (6 hours) from first_seen_ms.

    ROOT_GRACE_MS = 10 * 1000
    BASE_IDLE_MS = 30 * 1000
    MAX_IDLE_MS = 30 * 60 * 1000
    MAX_DURATION_MS = 6 * 3600 * 1000
    
    
    def compute_idle_timeout_ms(meta) -> int:
        """Adapt the quiet timeout to the longest gap this trace has already survived."""
        learned_timeout_ms = 3 * meta.max_gap_s * 1000
        bounded_timeout_ms = max(BASE_IDLE_MS, learned_timeout_ms)
        return min(MAX_IDLE_MS, bounded_timeout_ms)
    
    
    def compute_due_time_ms(meta) -> int:
        """Return the broker timestamp (ms) when this trace should be declared complete."""
        # Rule 1: Inactivity timeout after the most recent span.
        due_ms = meta.last_seen_ms + compute_idle_timeout_ms(meta)
    
        # Rule 2: Once the root span arrives, wait only 10 s after the latest activity.
        if meta.root_end_ms is not None:
            latest_activity_ms = max(meta.root_end_ms, meta.last_seen_ms)
            due_ms = min(due_ms, latest_activity_ms + ROOT_GRACE_MS)
    
        # Rule 3: Never stay open past the 6-hour hard ceiling.
        hard_cap_ms = meta.first_seen_ms + MAX_DURATION_MS
        return min(due_ms, hard_cap_ms)
    

    Stream time vs. wall-clock time: Instead of comparing due_ms against time.time(), each partition tracks stream time — the largest broker LogAppendTime read from that partition so far. Why? Suppose an assembler falls 5 minutes behind (or replays old data): wall-clock time is 12:05, while the events being read are from 12:00. Using wall-clock time would prematurely fire every timer before reading the 12:01 events sitting right behind them in Kafka! Stream time advances naturally with the data; only when consumer lag is near zero (< 5 s) and a partition goes completely quiet do we advance stream time using wall-clock time so the last few traces still close.

    Finding due traces in O(log N) without scanning 925,000 open traces: Scanning all open traces every second wastes CPU. Instead, each partition keeps a min-heap (a priority queue whose smallest due_ms always sits at index 0). Pushing a new heap entry on every span would bloat the heap 25x; instead, we use lazy re-arming — we push when a trace opens (or when root_end_ms pulls its due time earlier), and if a trace pops early because newer spans pushed last_seen_ms later, we recompute compute_due_time_ms(meta) and push it back!

    import heapq
    
    
    def schedule_trace(due_heap: list, meta) -> None:
        """Push (due_time_ms, trace_id) onto the partition's min-heap."""
        heapq.heappush(due_heap, (compute_due_time_ms(meta), meta.trace_id))
    
    
    def pop_completed_traces(due_heap: list, traces_by_id: dict, stream_time_ms: int) -> list:
        """Pop all traces due at or before stream_time_ms without scanning open traces."""
        completed = []
    
        while due_heap and due_heap[0][0] <= stream_time_ms:
            scheduled_ms, trace_id = heapq.heappop(due_heap)
            meta = traces_by_id.get(trace_id)
    
            # Skip traces already emitted (e.g. if root_end added a second heap entry).
            if meta is None or meta.state != "OPEN":
                continue
    
            actual_due_ms = compute_due_time_ms(meta)
            if actual_due_ms > stream_time_ms:
                # Newer spans arrived since this heap entry was pushed; re-schedule lazily.
                heapq.heappush(due_heap, (actual_due_ms, trace_id))
            else:
                # Mark EMITTED immediately so any duplicate heap entry is ignored.
                meta.state = "EMITTED"
                completed.append(meta)
    
        return completed
    

    Handling multi-hour workflows cleanly: - Periodic partial results: Any trace still OPEN after 15 minutes enters a small secondary min-heap (~1,125 long traces per partition) that emits a PARTIAL ready message every 15 minutes whenever last_offset has advanced. To bound read amplification, traces above 100,000 spans emit partials at most once per hour. - Adaptive gap learning + service policies: Batch workflows keep OPEN across quiet stages via max_gap_s or explicit /v1/policies/{root_service} settings, and hit MAX_DURATION cleanly at 6 hours.

  8. Claiming traces once, retries, and late-event reopening

    Because Kafka delivers trace-ready messages at-least-once (a message can be delivered again after a processor restart), processors coordinate through conditional writes on trace_ledger:

    Processor handling ready message m = { trace_id, last_offset, shard_count, kind }:
    
    1. Conditional CLAIM on trace_ledger[m.trace_id]:
         Condition: row does not exist
                    OR (row.covered_offset < m.last_offset
                        AND (row.status == "DONE" OR row.lease_until_ms < now_ms))
         Update:    status = "PROCESSING",
                    generation = coalesce(row.generation, 0) + 1,
                    shard_count = max(coalesce(row.shard_count, 1), m.shard_count),
                    worker_id = my_id, lease_until_ms = now_ms + 60_000
    
       - If claim fails because row.covered_offset >= m.last_offset:
           Already processed at least this much data -> commit Kafka offset and skip!
       - If claim fails because another worker holds an unexpired lease:
           Route to delayed retry queue.
    
    2. Stream events across 0..effective_shard_count-1 and call process_trace(trace_id, events),
       renewing lease_until_ms every 20 s while running.
    
    3. Conditional MARK DONE on trace_ledger[m.trace_id]:
         Condition: worker_id == my_id AND generation == claimed_generation
         Update:    status = "DONE", covered_offset = m.last_offset, covered_events = count_read
       Commit "trace-ready" offset.
    
    • Why generation and covered_offset matter: covered_offset deduplicates replays and redundant FINAL messages when no spans arrived after the last PARTIAL (because all spans of a trace live on one input partition, offsets strictly increase with new data). generation acts as a fencing token (a monotonically increasing number that invalidates stale workers): if Worker 1 freezes during garbage collection past its 60 s lease and Worker 2 takes over at generation = 2, Worker 1's late MARK DONE with generation = 1 is rejected.
    • What if process_trace is NOT idempotent? If process_trace triggers an external side effect that cannot simply overwrite a row, process_trace must write its output and the trace_ledger DONE state inside the same database transaction (or pass (trace_id, covered_offset) as an idempotency key to the downstream service).
    • Non-blocking retries and Dead-Letter Queue (DLQ): Transient store timeouts retry 3 times in memory with jittered backoff (1 s, 2 s, 4 s). If still failing, the processor releases the lease and publishes the job to a trace-ready-retry-5m topic instead of sleeping on its main partition (sleeping 5 minutes in place would block thousands of healthy traces behind it and trip Kafka's max.poll.interval.ms rebalance timer). After 5 total failures, the job lands in trace-ready-dlq for operator inspection; out-of-memory failures route to the high-memory processor pool.
    • Late events after a trace was already EMITTED:
      1. Within 30 minutes of emission: The assembler still holds the compact EMITTED marker in RAM. It writes the late span to Cassandra, checks reopen_count < 3, increments reopen_count, updates max_gap_s (so the trace learns from this late gap!), flips state back to OPEN, and schedules a REOPEN run that re-reads the complete trace (old spans + late spans) from Cassandra.
      2. Between 30 minutes and 8 hours (after the RAM marker was evicted): The assembler treats the span as a new trace with shard_count = 1. When the processor claims trace_ledger, it sees an existing DONE row! It uses max(row.shard_count, m.shard_count) so all 64 shards are still queried if the original trace was large, counts the events fetched from Cassandra, and verifies fetched_count > row.covered_events before calling process_trace — guaranteeing that if the earlier spans already expired past the 8-hour Cassandra TTL, we drop the straggler fragment instead of overwriting a complete 500-span result with 1 late span!
  9. Scaling bottlenecks, failure modes, and monitoring

    Bottlenecks and how the design scales: - Hot traces in Kafka and Cassandra: A runaway trace emitting 50,000 spans/s hits one Kafka partition (~12x normal peak). Our 1,000,000-event cap truncates it after ~20 seconds (~1 GB total) and notifies collectors to drop further spans for that traceId. In Cassandra, switching to 64 shards at 10,000 spans spreads those writes across the entire cluster. (If the business ever needs uncapped 50,000-span/s traces, see Follow-up 1 on key salting.) - Large-trace isolation: Ready messages with expected_events > 100,000 are published to a dedicated trace-ready-large topic served by high-RAM workers so multi-minute traces never starve fast traces.

    Failure modes: - Assembler crash or rolling deploy: Static consumer group membership (group.instance.id) avoids unnecessary partition shuffles on quick restarts. If a worker truly dies, another worker reads its compacted trace-meta partition (~8 MB + ~10 min active tail, taking ~2–3 seconds), rebuilds the min-heap, and replays ~2 seconds of spans. - Cassandra unavailable for several minutes: Unacknowledged write bytes hit the 64 MB cap, so assemblers pause() consumption while keeping group heartbeats alive. Kafka buffers up to 24 hours of spans on disk. Crucially, because completion timers run on stream time (which pauses when consumption pauses!), traces about to complete are not closed early with missing events. Once Cassandra recovers, the 1.5x write headroom drains a 5-minute backlog in ~2–10 minutes.

    Key metrics to monitor: - Consumer lag in seconds (not just message count) on spans and trace-ready. - End-to-end latency from a trace's final span timestamp to process_trace completion (60 s p99 target). - Completion reason breakdown (ROOT_END vs. IDLE_TIMEOUT vs. MAX_DURATION): a sudden spike in IDLE_TIMEOUT after a release immediately flags a microservice that stopped emitting root spans. - Late-event reopen rate, truncated trace count, Cassandra pause duration, and trace-ready-dlq depth.

Intuition & how it works

Imagine an airport baggage-claim office that assembles all suitcases belonging to the same family booking (traceId) before loading their shuttle van (process_trace). Most families' bags arrive within two minutes, so holding bags right next to the conveyor belt (in consumer RAM) feels tempting. The trap is a Kafka rule: a conveyor belt has one sequential checkpoint bookmark (committed offset), meaning you can only sign off "everything before bag #100 is completely done" once every family that had a bag before #100 has driven away. If just one family is on a 6-hour layover waiting for a delayed connecting bag, your bookmark is frozen 6 hours in the past — and if the clerk goes home sick, the replacement clerk must re-read 6 hours of conveyor history (tens of gigabytes) from scratch!

The naive approach — keeping raw span events inside Kafka consumer memory until each trace finishes — fails at multi-hour durations because heap RAM balloons to ~200 GB, a single partition with several huge traces crashes out of memory, and every restart or rebalance (when Kafka shifts partition ownership between workers) replays hours of data and re-emits half-missing traces.

Our design fixes this by splitting heavy event payloads from tiny completion metadata: 1. Route by traceId: Hashing traceId as the Kafka message key sends every span of one trace to the same partition and single owning Assembler worker. 2. Offload payloads immediately, keep tiny timers in RAM: The assembler writes the ~1 KB span payloads immediately to an external LSM-tree datastore (a write-optimized database like Cassandra or ScyllaDB where rows automatically expire after an 8-hour TTL, or time-to-live), while keeping only ~200 bytes of summary metadata per open trace in RAM (backed up every 2 seconds to a log-compacted Kafka topic, which retains only the latest metadata snapshot per traceId). 3. Stream and claim once on completion: A min-heap (a priority queue keeping the earliest due timestamp on top) tracks when each trace finishes using stream time (the Kafka broker's arrival timestamp rather than wall-clock time). When due, the assembler emits a tiny trace-ready job; a separate Processor worker claims the trace in a conditional ledger table, streams the sorted spans from Cassandra page by page, and calls process_trace.

Tiny concrete walkthrough: Suppose Partition 4 receives four spans across two traces — tr_batch_01 (a 6-hour batch job) and tr_web_88 (a quick web checkout): - offset 200 (t = 0 s): tr_batch_01 span 1 arrives -> written to Cassandra; TraceMeta[tr_batch_01] created in RAM (due = 30 s); min-heap holds [(30 s, tr_batch_01)]. - offset 201 (t = 1 s): tr_web_88 child span arrives -> written to Cassandra; TraceMeta[tr_web_88] created (due = 31 s). - offset 202 (t = 2 s): tr_web_88 root span (is_root = true) arrives -> written to Cassandra; root-end rule pulls tr_web_88's due time earlier to 2 s + 10 s grace = 12 s. At the 2-second checkpoint, Cassandra confirms offsets 200..202, and the assembler atomically commits Kafka offset 203 even though tr_batch_01 will stay open for 6 hours! - offset 203 (t = 13 s): A new span advances partition stream time to 13 s -> tr_web_88 (due = 12 s <= 13 s) pops from the min-heap, emits trace-ready(tr_web_88, last_offset=202), and a processor streams tr_web_88's two sorted spans from Cassandra into process_trace.

Key trade-offs

  • External event store vs. pure in-memory buffering. Buffering spans in consumer RAM is the fastest, cheapest option when all traces close within seconds. Once traces span hours, externalizing payloads to Cassandra/ScyllaDB bounds consumer RAM to ~8 MB per partition and shrinks crash replay from 6 hours (~34 GB/partition) to 2 seconds (~3 MB/partition), at the cost of a ~45-node database cluster, ~12 TB of SSDs, and two extra network hops per span.
  • Optional 60-second hybrid RAM tier vs. writing every span to the store. Keeping traces younger than 60 seconds (and under 256 KB) in RAM before spilling to Cassandra eliminates ~90% of database writes because 99.5% of traces are short. The trade-off is maintaining two code paths, replaying ~60 seconds on crash instead of 2 seconds, and losing the ability to reprocess a short trace if a late span arrives 5 minutes later (since its early spans were never persisted).
  • Compacted Kafka changelog vs. external Redis/KV for TraceMeta. Keeping the 200-byte TraceMeta in the owning consumer's RAM backed by a compacted Kafka topic makes per-span updates zero-network-hop and lets TraceMeta, trace-ready jobs, and input offsets commit atomically in a single Kafka transaction (an all-or-nothing multi-topic write). Storing metadata in Redis makes external inspection easier, but adds a network hop per batch and requires manual offset-deduplication logic on crash recovery.
  • Combined completion heuristics vs. a single timeout. Waiting for the root span (+10 s grace) closes web requests quickly; an adaptive inactivity timeout (max(30 s, 3 * max_gap_s), capped at 30 min) protects multi-stage batch jobs without delaying fast traces; a 6-hour hard ceiling prevents leaked state. Because no heuristic is 100% clairvoyant, supporting bounded reopen on late events (up to 3 times) turns rare early closures into recoverable updates rather than permanent data loss.
  • Stream time vs. wall-clock time. Driving completion timers from Kafka's LogAppendTime ensures consumer lag, datastore pauses, and historical replays never prematurely close traces whose remaining spans are already sitting unread in Kafka. Its only wrinkle is needing a wall-clock fallback when consumer lag is near zero and a partition goes completely idle.
  • Effectively-once ledger + idempotent process_trace vs. distributed two-phase commit. Using a conditional trace_ledger lease plus an idempotent process_trace (one where repeating a call overwrites the same trace_id result cleanly) delivers one accurate output per trace without slow cross-system transactions.

Common mistakes

  • Committing Kafka offsets immediately while spans are still buffered only in RAM, which permanently loses every open trace whenever a consumer pod restarts or crashes.
  • Adding partitions to the live spans topic to scale up, forgetting that hash(traceId) % num_partitions changes for almost every key and splits open traces across two different consumers.
  • Assuming differing language clients hash keys identically, when Java defaults to murmur2 and librdkafka defaults to crc32, silently scattering spans of the same traceId across partitions.
  • Relying solely on the root span to close traces, which leaks memory forever whenever a root span is dropped or sampled out, and misses asynchronous child spans that finish after the root.
  • Scanning all ~1 million open traces every second to find expired ones, burning CPU instead of popping due traces from a per-partition min-heap in O(log N) time.
  • Evaluating inactivity timeouts against wall-clock now() during consumer lag, causing a recovering consumer to close thousands of traces prematurely before reading their next spans from Kafka.
  • Running process_trace synchronously inside the Kafka consumer loop, allowing one 1 GB trace to stall partition polling past max.poll.interval.ms and trigger endless consumer group rebalances.
  • Issuing DELETE WHERE trace_id = ? in Cassandra after processing, flooding the LSM storage engine with tombstones that degrade read latency instead of letting rows expire cleanly via TTL and TimeWindowCompactionStrategy.

Follow-up questions

  • Suppose a tiny fraction of runaway traces contain millions of spans—how do you prevent partition skew in Kafka and hot-key bottlenecks in storage? First, the 1,000,000-span (1 GB) safety cap stops runaway traces after ~20 seconds even at 50,000 spans/s and tells collectors to drop further spans for that traceId. In Cassandra, switching a trace from 1 shard to 64 shards (hash(span_id) % 64) once it crosses 10,000 spans spreads writes and reads across 64 storage partitions (~16 MB each for a 1 GB trace), while routing its trace-ready job to a high-memory processor pool prevents head-of-line blocking. If the business must support uncapped 50,000-span/s traces without truncating them, collectors that detect a single traceId exceeding ~2,000 spans/s add a random suffix (key salting, traceId#0..7) to spread Kafka ingestion across 8 assemblers; those 8 sub-assemblers write spans to Cassandra as usual and forward lightweight count/timestamp summaries to the single plain-traceId owner on a metadata topic, using broker timestamps rather than single-partition offsets to track coverage.
  • After deploying a bug fix, engineers rewind the Kafka consumer to an earlier offset—how do you prevent duplicate executions or incomplete half-traces from overwriting valid outputs? Launch the replay as an isolated consumer group with its own temporary trace-meta and trace-ready topics, starting MAX_DURATION (6 hours) earlier than the target replay window [T_start, T_end] in warm-up mode. During the 6-hour warm-up before T_start, assemblers populate metadata and idempotent Cassandra rows (primary-key overwrites) without emitting trace-ready jobs, guaranteeing that any trace completing at or after T_start has 100% of its opening spans present and is never processed as a partial fragment. Because timers run on Kafka's LogAppendTime stream clock, traces close at the exact same points as live traffic. Finally, in RECOVER mode (recovering missed runs), processors check trace_ledger.covered_offset >= m.last_offset and automatically skip traces already processed; in RECOMPUTE mode (re-running fixed process_trace code), processors write against a fresh ledger namespace (or bump a logic_version column) so each trace inside [T_start, T_end] runs exactly once with the bug fix.
  • What changes would you make if critical signals, such as error-span alerts, must fire within a few seconds while the parent trace remains open? Keep the full-trace assembly pipeline unchanged for process_trace, and add a fast streaming rule path alongside it (either a lightweight hook inside the assembler or an independent Kafka consumer group reading spans). Whenever an incoming span matches a real-time rule — such as status == "ERROR" on a payment service — it fires an alert within 1–2 seconds without waiting for the rest of the trace. If the alert needs root-level context (like tenant ID or HTTP route), the assembler caches those few bytes inside the in-memory TraceMeta as soon as the root span arrives (or buffers the error alert briefly until it does), and once the full trace finishes later, process_trace links the complete trace view to the alert.
  • Walk through how Kafka consumption and nearly finished traces behave when the external storage cluster suffers a multi-minute outage. When Cassandra stops acknowledging writes, unconfirmed in-flight bytes on each assembler quickly reach the 64 MB backpressure cap, causing assemblers to call pause() on their Kafka partitions while continuing empty poll() calls so they stay in the consumer group without rebalancing or running out of RAM. Kafka safely retains up to 24 hours of incoming spans on disk. Crucially, because completion timers compare due_ms against partition stream time — which stops advancing while spans consumption is paused — traces that were 1 second away from completing freeze in place rather than closing early with missing spans stuck in Kafka. Meanwhile, processors that fail Cassandra reads release their ledger leases without marking traces DONE and push jobs to the delayed retry topic; once Cassandra recovers, the 1.5x provisioned write headroom drains a 5-minute backlog in roughly 2 minutes at average load (or ~10 minutes at peak load) in exact stream-time order.

Follow-up questions

Similar questions

More New Relic interview questions

All 3 New Relic questions →