Object-Storage LLM Tracing and Token Metering Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Production AI agent and LLM workloads generate deep, nested execution trees—combining router prompts, vector retrievals, external tool calls, and model completions—on every end-user request. Architect a multi-tenant LLM tracing, analytics, and token-metering platform that uses cloud object storage (S3 or GCS) as its primary raw-payload store while sustaining both heavy write bursts and low-latency interactive reads.

Your platform must satisfy the following functional and operational targets:

  • Span capture & tree inspection: Accept execution spans containing prompts, completions, tool inputs/outputs, durations, and tags, and serve full runs or arbitrary subtrees by run_id. Inspecting an individual span or field must not download or parse an entire multi-megabyte archive blob.
  • Exact token metering & live monitoring: Maintain accurate token totals grouped by tenant, project, and model for customer invoicing and usage quotas, while tracking p50 / p95 / p99 latencies, failure spikes, and spend or error threshold alerts.
  • Throughput & payload profile: Handle 50,000 spans/sec at peak (~500M spans/day), where typical spans weigh 20 KB and long multi-turn or multimodal spans reach 5 MB.
  • Latency & retention SLOs: Acknowledge ingested batches in < 50 ms, serve trace detail lookups in < 200 ms at p95, answer dashboard aggregation queries in < 1 s at p95, and retain traces cost-effectively in object storage for 90 days.

Scope & Expectations

  • Ingestion API & write decoupling: Define the collection endpoints, SDK batching contracts, and buffering architecture that meet < 50 ms durable acknowledgments without synchronous object-store writes.
  • Storage tiering & partial-read layout: Separate searchable metadata from raw JSON payloads and specify how archive files and byte-offset indexes enable targeted partial reads (such as framed segments or HTTP byte-range slices) without full-object scans or excessive PUT/GET bills.
  • Exact billing & streaming rollups: Detail how stream consumers deduplicate retried submissions for exact-once token accounting alongside sub-second latency and error aggregations.
  • Architectural trade-offs: Weigh freshness vs. cloud storage and request costs, consistency vs. availability under traffic spikes, and metadata index granularity.

Step-by-step walkthrough

  1. Clarify requirements, trace terminology, and SLAs

    In an LLM application, a single user message often triggers a deep execution graph: a router prompt, a vector-database retrieval, two tool calls, and a final synthesis LLM call. Observability SDKs record each step as a span (one timed unit of work carrying span_id, parent_span_id, inputs, outputs, status, latency, and token counts), and group all spans from one root invocation under a shared trace_id to form a trace (an execution tree).

    Start by confirming functional scope and pinning down exact durability and freshness guarantees:

    Functional requirements: - Ingestion: Collect spans in batches (either once on completion, or as separate start and end events for long-running chains) with prompts, completions, tool arguments, multimodal attachments, tags, and token counts. - Interactive trace & subtree retrieval: Fetch an entire run—or only the subtree rooted at any child run_id—and inspect specific span fields without downloading multi-megabyte blobs. - Search & filtering: Query runs by tenant, project, time window, status, duration, model, and custom metadata tags purely from indexed metadata. - Exact token billing & real-time dashboards: Meter exact token usage per (tenant, project, model) for monthly invoices and live quotas, while serving p50/p95/p99 latency, error-rate, and cost dashboards plus threshold alerts.

    Non-functional targets & key assumptions: - Scale: 50,000 spans/s at peak (~500M spans/day); 20 KB average payload, up to 5 MB for multi-turn or multimodal spans; 90-day retention backed by cloud object storage (S3/GCS). - Latency SLOs: Return ingest receipts in < 50 ms, serve run_id trace views in < 200 ms at p95, and answer dashboard rollups in < 1 s at p95. - What "ack" promises: A 202 Accepted response guarantees the span is replicated to durable disk across availability zones and will never be lost—even if indexing lags by a few seconds (~2–5 s freshness target). - Safety for host apps: SDKs batch asynchronously in background threads with a bounded memory ring buffer so observability hiccups never slow or crash a customer's production app. - Token source of truth: Prefer provider-reported usage fields; fall back to server-side tokenization flagged usage_estimated = true when omitted.

  2. Back-of-the-envelope numbers and why naive S3 writes fail

    1. Ingestion bandwidth & 90-day storage footprint:
       Average rate          = 500,000,000 spans / 86,400 s         = ~5,800 spans/s (peak 50k is ~8.6x avg)
       Peak raw throughput   = 50,000 spans/s x 20 KB               = 1.0 GB/s uncompressed (~250 MB/s zstd)
       Daily raw payloads    = 500M x 20 KB                         = 10 TB/day uncompressed
       Compressed (zstd ~4x) = ~2.5 TB/day -> x 90 days             = ~225 TB total in object storage
    
    2. Compact searchable metadata vs. bulky payload gap:
       Searchable row / span = ~1 KB raw (IDs, timings, tags, tokens, two 256-byte text previews)
       Columnar compressed   = ~200 B/row -> 500M x 200 B           = ~100 GB/day (~9 TB / replica for 90 days)
       Key insight: Metadata is 25x smaller than compressed payloads (100 GB vs. 2.5 TB/day)!
    
    3. The $75,000/month object-storage PUT trap (reference S3 pricing: $0.005 / 1,000 PUTs):
       NAIVE (1 S3 object per span):
         500M PUTs/day x ($0.005 / 1,000) = $2,500/day = ~$75,000/month JUST in PUT fees!
         Worse: 50,000 PUT/s hits per-prefix limits (3,500 PUT/s) and adds 50-150 ms tail latency.
       BUNDLED SEGMENTS (128 Kafka partitions, flush every 2 s OR at 8 MB compressed):
         <= 128 / 2 = 64 PUT/s -> <= 5.5M PUTs/day = ~$28/day (~90x cheaper!)
       90-day byte storage bill (30d Standard @ $0.023/GB + 60d Infrequent Access @ $0.0125/GB):
         (75,000 GB x $0.023) + (150,000 GB x $0.0125) = $1,725 + $1,875 = ~$3,600/month.
    
    4. Billing stream state size:
       Assume 30% of spans are billable LLM calls = 150M/day (~15,000/s peak).
       Keeping 48 hours of seen (tenant_id, span_id) keys (~50 B each) = 300M x 50 B = ~15 GB total state.
    

    Three architectural rules fall straight out of this math: 1. Ack from a replicated append-only log (Kafka), never from S3 or a database, to hit < 50 ms at 1 GB/s. 2. Pack thousands of spans into multi-megabyte segment objects with byte-offset indexes instead of writing one object per span. 3. Split compact searchable metadata (100 GB/day) onto fast SSDs while leaving bulky JSON payloads (2.5 TB/day) in cheap object storage.

  3. Ingestion and query APIs

    Ingestion API (authenticated by project API key; zstd-compressed request bodies)
      POST /v1/spans:batch
           Idempotency-Key: <batch_uuid>
           { spans: [ { span_id, trace_id, parent_span_id,     // Client-generated UUIDv7 IDs
                        path: "0193.../0193.../",              // Root-to-self slash-terminated path
                        event: "start" | "end" | "complete",
                        project_id, name, kind: "llm" | "chain" | "tool" | "retriever",
                        start_time, end_time?, status?, error_type?,
                        model?, usage?: { input_tokens, output_tokens, cached_tokens },
                        inputs?, outputs?, tags, metadata,
                        blob_refs?: [ { field: "inputs.image_0", blob_id } ] } ] }
        -> 202 Accepted { accepted_ids: [...], rejected: [ { span_id, reason } ] }
        -> 429 Too Many Requests { retry_after_ms }
    
      POST /v1/blobs     { sha256, size_bytes, content_type }
        -> 200 OK        { blob_id, presigned_put_url }   // Or { blob_id, exists: true } if uploaded today
    
    Query & Analytics API
      GET  /v1/runs/{run_id}?scope=subtree                // Metadata + 256-B previews ONLY (0 S3 reads)
      GET  /v1/runs/{run_id}/payload?field=outputs        // Single HTTP byte-range slice from object store
      GET  /v1/projects/{id}/runs?filter=status:error AND latency_ms>3000&from=&to=&cursor=
      GET  /v1/metrics?project_id=&metric=p95_latency|error_rate|cost&group_by=model&interval=1h
      GET  /v1/usage?group_by=project_id,model&month=2026-11
      POST /v1/alerts    { project_id, metric, window: "5m", threshold, min_events: 50, webhook_url }
    

    Why each API detail matters: - Client-generated UUIDv7 IDs: A UUIDv7 is a 128-bit unique identifier whose leading 48 bits store a Unix millisecond timestamp. Creating span_id and trace_id inside the SDK before the first send guarantees retries carry the exact same IDs for deduplication, and lets the server extract trace_date directly from trace_id even when a child span arrives before its root parent! - Per-span partial acceptance (202): One malformed span in a 100-span batch is rejected individually without poisoning the other 99 spans, preventing endless batch retry loops. - Direct-to-object-storage attachments (/v1/blobs): Multi-megabyte base64 images or PDFs never clog the ingest servers or Kafka; the SDK uploads them straight to object storage via a presigned URL and references blob_id. - Two-step trace UI loading: GET /v1/runs/{run_id} returns the entire execution tree plus 256-byte input/output previews from fast metadata alone; full multi-megabyte fields load lazily via /payload?field=... only when a developer clicks a node.

  4. Storage tiering and metadata data model

    Tier 1 — Cloud Object Storage (raw payloads, 90-day lifecycle):

    segments/{yyyy-mm-dd}/{hh}/part-{partition}/{first_offset}-{last_offset}-{uuid}.seg
    blobs/{yyyy-mm-dd}/{tenant_id}/{sha256}
    

    Notice why blobs/ includes {yyyy-mm-dd} in its key (deduplicating repeated multimodal images within each day rather than forever): cloud object lifecycle rules delete files purely by creation age (90 days). If a day-89 span pointed to a blob created on day 1, a 90-day rule would delete that blob tomorrow and break the day-89 trace! Scoping content-addressed keys by date lets simple, zero-cost S3 lifecycle expiration clean up segments and blobs together without distributed reference counting.

    Tier 2 — ClickHouse (columnar SSD metadata store): Columnar storage compresses repetitive strings (model, project_id, status) by ~5× and scans millions of rows per second for filtered lists and dashboards without ever touching S3.

    Table: spans  (engine = ReplicatedReplacingMergeTree(ingested_at), PARTITION BY trace_date)
      Sorting key: (tenant_id, trace_id, path, span_id, event)
      Columns:     project_id, parent_span_id, name, kind, model, status, error_type,
                   start_time, end_time, latency_ms, input_tokens, output_tokens, usage_estimated,
                   tags Array(String), metadata Map(String, String),
                   input_preview String, output_preview String,      // First 256 bytes each
                   segment_key String, frame_offset UInt64, frame_length UInt32,
                   field_frames Array(Tuple(field_path String, offset UInt64, length UInt32))
    
    Table: spans_by_time  (populated via Materialized View from "end" and "complete" events)
      Sorting key: (tenant_id, project_id, start_time, span_id)      // Powers < 1 s project search/filter
    

    Tier 3 — Fast Point-Lookup Index (run_index in ScyllaDB / DynamoDB) & PostgreSQL Ledger: - Because ClickHouse's spans table is sorted by (tenant_id, trace_id, ...), looking up an arbitrary child run_id when the caller only knows run_id (not trace_id) would otherwise scan every partition. A compact KV table run_index mapping (tenant_id, run_id) -> (trace_id, trace_date, path) (45B rows × ~100 B ≈ 4.5 TB across 90 days) resolves any run_id in one 2–5 ms O(1) read. - PostgreSQL stores relational control-plane entities (tenants, API keys, versioned model price tables, alert rules) and the transactional usage_hourly billing ledger.

    How trailing-slash materialized paths solve < 200 ms subtree queries: A materialized path stores the chain of ancestor IDs from the root down to the current span, always ending with /. Look at what happens if you omit the trailing slash versus including it:

    Trace tree:
      root/
       +-- 7f1/          (Retriever sub-chain we want to fetch)
       |    +-- a42/     (Vector DB call inside 7f1)
       +-- 7f10/         (Unrelated sibling tool call!)
    
    BUG without trailing slash:  path LIKE 'root/7f1%'   matches 'root/7f10' by mistake!
    SAFE with trailing slash:    path LIKE 'root/7f1/%'  matches 'root/7f1/' and 'root/7f1/a42/' ONLY,
                                 as one contiguous range scan inside (tenant_id, trace_id)!
    

    Including event ("start" vs. "end") in the spans sorting key ensures ClickHouse's ReplacingMergeTree—an engine that asynchronously collapses duplicate rows sharing the same sorting key during background compactions—deduplicates retried starts without overwriting ends. At read time, the query service merges start + end rows by span_id in memory so out-of-order arrivals and uncompacted duplicates never produce wrong trees.

  5. High-level architecture and the < 50 ms durable ack path

      Customer App + SDK (async batch every 1 s or 100 spans; UUIDv7 IDs; 50 MB ring buffer)
              |  HTTPS + zstd                                   > 256 KB attachments
              v                                                 | presigned PUT
      [ L7 Load Balancer ] -> [ Stateless Ingest API ] ---------+----------------> [ Object Store: blobs/ ]
                                auth (60s cache), tenant token bucket,
                                extract 200-B usage event, Kafka produce (acks=all) -> 202 (< 50 ms)
                                          |
                                          v
                 [ Kafka (RF=3 across 3 AZs, min.insync.replicas=2, 72h retention) ]
                   |-- spans topic (128 partitions, key = tenant_id:trace_id)
                   |-- usage topic (key = tenant_id:span_id)
                            |                                           |
                            v                                           v
                [ Segment Writers ]                         [ Flink Billing Stream ]
                  parse JSON, redact, build zstd frames,      48h RocksDB dedup by (tenant, span_id),
                  1) PUT 8 MB .seg  2) insert ClickHouse      idempotent total upserts + live quotas
                  3) commit Kafka offsets                               |
                    |                     |                             v
                    v                     v                 [ Postgres: usage_hourly ] -> Invoices
      [ Object Store: segments/ ]  [ ClickHouse: spans,     [ Redis: tenant quotas ]   -> Ingest 429s
      [ KV Store: run_index ]        spans_by_time, metrics_* ]
             ^                            ^            ^
             +------ [ Query API ] -------+      [ Alert Evaluator (1m) ] -> Webhooks / Pager
                       NVMe frame cache + p95 hedged Range GETs
    

    Meeting the < 50 ms ack budget:

    TLS termination + cached API-key lookup + local token-bucket check   ~3 ms
    Decompress batch, validate schema, extract ~200-B LLM usage events   ~5 ms
    Kafka batch append (linger.ms=5, zstd, acks=all across 3 local AZs)  ~10 - 20 ms
    Total ingest latency                                                 ~18 - 28 ms (well under 50 ms)
    
    • Why partition Kafka by tenant_id:trace_id: Every span belonging to the same trace lands in the same partition and is buffered by the same segment writer, packing an entire trace into 1–2 segment files (huge read locality!), while still spreading a massive single tenant evenly across all 128 partitions (~2 MB/s compressed per partition at peak).
    • Handling rare 5 MB inline payloads: Kafka performs poorly on multi-megabyte messages (default limit ~1 MB). Modern SDKs offload fields > 256 KB via /v1/blobs; if an older client sends a 4 MB inline JSON span, the ingest node strips the largest fields into blobs/ before appending the slimmed record to Kafka.
    • Durability over availability at the ack boundary: If a tenant exceeds its rate quota, return 429 immediately so noisy neighbors stay isolated. If Kafka itself cannot reach a 2-of-3 replica quorum, return 503 rather than faking a 202 backed by volatile local disk—SDKs buffer and retry safely.
  6. Deep dive: segment files, field-level offsets, and HTTP byte-range reads

    So queries can read a single span or output field without pulling an entire multi-megabyte archive object, each segment writer flushes an immutable .seg container every 2 seconds or 8 MB compressed:

    +-------------------------------------------------------------------------+
    | Frame 0 (offset 0, len 4,820):       zstd(span_1 full 18 KB JSON)       |
    | Frame 1 (offset 4,820, len 610,200): zstd(span_2.inputs  [3.8 MB raw])  |
    | Frame 2 (offset 615,020, len 52,256):zstd(span_2.outputs [190 KB raw])  |
    | ...                                                                     |
    | Self-describing Footer: [ span metadata + (field_path, offset, length) ]|
    | Footer byte length (8 bytes) | Magic bytes "LSEG1"                      |
    +-------------------------------------------------------------------------+
    

    Three design choices make partial reads fast and cheap: 1. Per-frame zstd compression with trained dictionaries: Compressing an entire 8 MB file as one stream would force decompressing from byte 0 on every read. Instead, each frame is compressed independently so any byte range decompresses standalone, using a per-tenant zstd dictionary (a small pre-trained lookup table of common prompt keys and system boilerplate) so even 5 KB frames achieve strong ~4× compression. 2. Adaptive field splitting above 64 KB: Spans <= 64 KB occupy a single frame (~5 KB compressed—one tiny network packet burst). Spans > 64 KB (up to 5 MB) split top-level inputs, outputs, and 10-message chat chunks into separate frames, recording [(field_path, offset, length)] inside ClickHouse's field_frames column. 3. Crash-safe 3-step write order (no distributed locks needed): - Step 1: PUT the .seg file to object storage (including the self-describing footer so ClickHouse can be completely rebuilt from S3 in a disaster). - Step 2: Batch-insert metadata + byte offsets into ClickHouse (passing segment_key as ClickHouse's native insert-deduplication token) and run_index. - Step 3: Commit Kafka consumer offsets. If a writer crashes after Step 1, replay writes a fresh segment and the unreferenced orphan ages out at 90 days; if it crashes after Step 2, replay writes identical span data whose duplicate metadata rows collapse via ReplacingMergeTree.

    Fetching only outputs of a 5 MB span requires a single HTTP byte-range request (Range: bytes=start-end, inclusive):

    def build_range_header(
        frame_offset: int,
        frame_length: int,
        field_frames: list[tuple[str, int, int]],
        requested_field: str | None = None,
    ) -> str:
        """Return an inclusive HTTP Range header for either one split field or the whole span."""
        if requested_field is not None:
            for field_path, sub_offset, sub_length in field_frames:
                if field_path == requested_field:
                    end_byte = sub_offset + sub_length - 1
                    return f"bytes={sub_offset}-{end_byte}"
    
        # Fallback for spans <= 64 KB (stored as a single frame) or full-span reads.
        end_byte = frame_offset + frame_length - 1
        return f"bytes={frame_offset}-{end_byte}"
    

    Why custom frame segments instead of Parquet for raw payloads? Apache Parquet excels at scanning flat columns across thousands of rows, but requires buffering large row groups (tens of megabytes) for efficiency—clashing with our 2-second freshness flush—and struggles with deeply nested, schema-less JSON tool payloads. We use .seg frame files for low-latency point/field reads, and reserve Parquet for nightly metadata exports powering 30-day batch analytics.

  7. Deep dive: < 200 ms trace retrieval, tail hedging, and index density

    Latency walk for GET /v1/runs/{run_id}?scope=subtree:

    1. Point read in run_index: (tenant_id, run_id) -> (trace_id, trace_date, path)   ~3 ms
    2. ClickHouse range read on single partition `trace_date`:
         WHERE tenant_id = ? AND trace_id = ? AND path LIKE 'root/7f1/%'              ~25 - 55 ms
    3. Merge start/end rows by span_id in memory, assemble JSON tree + 256-B previews ~3 ms
    Total p95 server time                                                             ~35 - 65 ms (< 200 ms!)
    

    Latency walk when the user clicks a span (GET /v1/runs/{run_id}/payload?field=outputs): - Query nodes maintain a sharded local NVMe read-through cache keyed by (segment_key, offset, length), plus background prefetching (as soon as GET /v1/runs/{run_id} serves a tree, a background task warms the root span and LLM spans into NVMe cache before the human clicks—cache hit takes ~2 ms). - On a cold cache miss, cloud object storage averages 25–45 ms but occasionally exhibits 200+ ms tail hiccups. We tame that tail with hedged requests: if the first S3 range GET has not returned its first byte within 60 ms (the observed p95), fire a second parallel range GET and take whichever finishes first. Firing hedges on only 5% of 2,000 reads/s adds 100 GET/s (~8.6M GETs/day × $0.0004/1k ≈ $3.50/day) while cutting p99 latency under 150 ms.

    Index density trade-offs in ClickHouse: ClickHouse uses a sparse primary index, storing one index mark per granule (a compressed block of rows, 8,192 by default), meaning every point lookup decompresses at least one whole granule: - On spans (point/tree lookups), tune index_granularity = 1024 so each trace read decompresses 8× less data (~200 KB instead of ~1.6 MB), trading an 8× larger—but still easily RAM-resident—primary index. - On spans_by_time (time-range scans), keep index_granularity = 8192 and attach lightweight bloom-filter data-skipping indexes on tags and metadata keys so filter=tag:prod skips 95%+ of granules without maintaining giant B-tree secondary indexes. Full-text inverted indexing over prompt text is strictly opt-in per project.

  8. Deep dive: exact-once token billing, metric rollups, and alerting

    Customer invoices demand exact token totals even during heavy client retries, whereas interactive charts prioritize sub-second rollups—so we split them across two dedicated consumers.

    Exact token billing pipeline (Apache Flink -> PostgreSQL): 1. Client-anchored idempotency key: Every billable LLM span emits a 200-byte usage event keyed by (tenant_id, span_id). Even if an SDK times out and re-packs that span into a brand-new batch UUID, span_id never changes. 2. Stateful stream deduplication: Flink partitions the usage stream by (tenant_id, span_id) and checks an embedded RocksDB state table with a 48-hour TTL (~15 GB total state). Duplicate arrivals with identical token counts are dropped immediately; duplicates reporting different token counts route to an audit usage_conflicts table. 3. Ingest-hour attribution (no late-data drift): Usage is booked to the UTC hour the ingest server accepted the span, rather than client clock start_time. Closed hourly windows never mutate retroactively from delayed client uploads (edge spans crossing midnight bill to the next hour, documented in billing terms). 4. Idempotent total upserts—never tokens + delta: Flink maintains running totals per (tenant_id, project_id, model, accept_hour) in checkpointed state and periodically upserts absolute totals into PostgreSQL: text INSERT INTO usage_hourly (tenant_id, project_id, model, hour, input_tokens, output_tokens, spans) VALUES (:tenant, :proj, :model, :hour, :total_in, :total_out, :total_spans) ON CONFLICT (tenant_id, project_id, model, hour) DO UPDATE SET input_tokens = EXCLUDED.input_tokens, output_tokens = EXCLUDED.output_tokens, spans = EXCLUDED.spans; If Flink crashes and replays from its last Kafka/state checkpoint, re-upserting input_tokens = 142500 overwrites 142500 harmlessly, whereas input_tokens = input_tokens + delta would double-charge customers! 5. Reconciliation & fast quotas: Store raw token counts as ground truth and join against a versioned model_pricing table at invoice time. A nightly ClickHouse batch job (SELECT uniqExact(span_id), sum(...) grouped by deduped spans) reconciles against usage_hourly to catch even > 48h retries. Meanwhile, Flink pushes month-to-date tenant totals to Redis every 10 s for ingest quota enforcement (bounding quota overshoot to ~20 s).

    Sub-second dashboards (< 1 s) & alerting: - ClickHouse Materialized Views roll incoming end/complete spans into metrics_1m and metrics_1h (AggregatingMergeTree keyed by (tenant_id, project_id, model, bucket_ts)). Store latency distributions as mergeable t-digest quantile sketches—compact summaries of value distributions—because averaging 24 hourly p95 numbers is mathematically wrong; merging 24 t-digest sketches yields an accurate 24-hour p95 over 30 days (720 rows) in < 50 ms. - An Alert Evaluator queries metrics_1m every 60 s across active rules (requiring min_events to prevent noisy 1-of-1 error pages), tracks state transitions (OK -> FIRING -> RESOLVED) with hysteresis, and sends webhook notifications carrying deterministic idempotency keys.

  9. Scaling bottlenecks, failure handling, and key trade-offs

    Component / Failure scenario           System behavior & recovery
    -------------------------------------  -------------------------------------------------------------------
    Ingest node crashes before 202         Client receives timeout/reset, retries with identical UUIDv7 IDs;
                                           downstream Flink & ReplacingMergeTree deduplicate cleanly.
    Single AZ or Kafka broker lost         RF=3 + min.insync.replicas=2 continues acking in < 50 ms, 0 loss.
    Kafka cluster loses quorum             Ingest returns 503 (never fake-acks); SDK buffers up to 50 MB.
    Object store throttles (503 Slow Down) Segment writers back off; 72-hour Kafka log buffers the backlog.
    ClickHouse down or wiped in disaster   Freshness lags during outage; full metadata is rebuildable by
                                           scanning self-describing footers in object-storage .seg files.
    Tenant early trace deletion (GDPR)     Delete ClickHouse + run_index rows immediately; encrypt frames with
                                           per-tenant KMS data keys for cryptographic erasure or bg rewrite.
    

    Summary of the three core trade-offs: 1. Latency vs. storage & request cost: Bundling spans into 2-second / 8 MB zstd frame segments cuts S3 PUT bills ~90× ($75k/mo → ~$830/mo) and moves days 31–90 to Infrequent Access (~$3,600/mo total), adding 2–5 s of search freshness lag while NVMe caching + p95 hedged byte-range GETs keep trace reads < 200 ms. 2. Consistency & durability vs. availability during spikes: Refusing to acknowledge when Kafka quorum is down (503) and shedding per-tenant spikes (429) guarantees zero silent data loss on acked spans and exact billing, while SDK ring buffers protect customer apps. 3. Index density vs. write & RAM overhead: Storing compact metadata (4% of raw size) in two ClickHouse sort orders with 1,024-row granules on spans and 8,192-row granules + bloom filters on spans_by_time achieves < 200 ms subtrees and < 1 s dashboards without the massive cost of full-text indexing 10 TB/day of prompts.

Intuition & how it works

Imagine running a massive research library archive paired with a digital card catalog and an auditor's ledger. Every second, couriers drop off 50,000 folders (execution spans—single timed steps like an LLM call, retriever query, or tool run), ranging from short index cards (20 KB) to 500-page illustrated transcripts (5 MB). Instead of making each courier wait while a librarian walks into a warehouse to shelve every single folder individually, an entrance drop-box (replicated Kafka log) stamps the courier's receipt in ~20 milliseconds. Behind the scenes, archivist workers bind hundreds of folders together into numbered anthology volumes (8 MB segment files) in cheap warehouse storage (S3/GCS) with an exact page-and-byte table of contents, file compact 200-byte summary cards into a fast SSD card catalog (ClickHouse), and hand tiny token slips to a billing clerk (Flink stream processor) who checks every slip's serial number (span_id) so retried deliveries are never billed twice.

A naive architecture breaks on latency, cloud bills, and billing accuracy all at once. Waiting on an S3 upload plus a database insert before acknowledging blows past the < 50 ms ingest target, and writing 500 million separate S3 objects per day racks up ~$75,000/month in S3 PUT request fees alone—more than 14× the cost of storing the actual bytes! On the read and billing paths, downloading and parsing a whole 5 MB JSON blob just to view a 2 KB final answer violates < 200 ms retrieval, while updating usage with relative increments (tokens = tokens + delta) double-charges customers whenever SDKs retry timed-out batches.

Walk through four concrete steps on a 3-span agent trace (root_agent -> vector_retriever -> synthesis_llm, 4 MB prompt context, 600 tokens) to see how the design works end to end: 1. Durable < 50 ms ack: The SDK generates UUIDv7 IDs (time-ordered unique IDs embedding a millisecond timestamp), uploads a 3 MB image directly to blobs/ via a presigned URL, and sends the batch with slash-terminated paths ("root/llm/"). The stateless ingest server validates the batch, appends the spans and a 200-byte usage event to 3-zone Kafka (acks=all), and returns 202 Accepted in ~22 ms. 2. Exact-once retry handling: Suppose a network blip drops the 202 response, so the SDK retries the batch. The Flink billing job hashes (tenant_A, span_llm) against its 48-hour RocksDB state, sees the ID was already counted, and upserts (inserts or overwrites) the unchanged hourly total into PostgreSQL—guaranteeing zero double-billing. 3. Framed segment indexing: A segment writer packs the trace's spans into one 8 MB .seg object with independently zstd-compressed frames for inputs and outputs, then inserts 200-byte metadata rows (including exact (segment_key, offset, length) byte pointers and 256-byte text previews) into ClickHouse. 4. Zero-scan < 200 ms read: When a developer opens run_id, the Query API looks up (trace_id, trace_date, path) in run_index (3 ms) and fetches the subtree + previews from ClickHouse via path LIKE 'root/%' in 40 ms—zero S3 calls. Clicking outputs triggers a single HTTP byte-range read (Range: bytes=615020-667275) that fetches and decompresses only those 52 KB in ~35 ms.

Key trade-offs

  • Acknowledging at the replicated log vs. synchronous storage writes. Returning 202 Accepted right after a 3-replica Kafka append achieves ~20 ms p95 ingest latency and insulates customer apps from ClickHouse or S3 slowdowns, trading immediate read-after-write visibility for a 2–5 s indexing delay and requiring every downstream consumer to tolerate replays and duplicates.
  • Multi-span segment files vs. one object per span. Buffering spans per partition into 2 s / 8 MB segment files slashes object-storage PUT costs ~90× ($2,500/day → ~$28/day) and avoids per-prefix rate limits, at the cost of storing (segment_key, frame_offset, frame_length) pointers in metadata and leaving harmless temporary orphan segments if a writer crashes mid-flush.
  • Per-frame zstd compression vs. whole-segment compression. Compressing each span (or large field > 64 KB) as an independent frame enables single-field HTTP byte-range reads without scanning from byte 0, sacrificing a bit of cross-span compression ratio that we largely recover using per-tenant pre-trained zstd dictionaries.
  • Dual metadata sort orders & granule density vs. storage/RAM footprint. Storing compact metadata (~4% of compressed payload volume) in two ClickHouse tables—spans with small 1,024-row granules (index blocks) sorted by (tenant_id, trace_id, path) for fast subtree reads, and spans_by_time with 8,192-row granules sorted by (tenant_id, project_id, start_time) for filtered scans—doubles metadata disk to ~18 TB per replica while keeping the 225 TB payload tier single-copy and avoiding costly default full-text prompt indexes.
  • Exact stateful billing vs. fast approximate dashboard rollups. Routing LLM token records through stateful Flink deduplication + total upserts + nightly reconciliation guarantees cent-accurate invoices, while letting ClickHouse materialized views (metrics_1m, metrics_1h with mergeable t-digest percentile sketches) skip per-span stateful lookups keeps dashboard queries well under < 1 s even if retry storms briefly nudge chart counts by < 0.1%.
  • Durability over availability at the ack boundary, plus storage tiering by age. Returning 503 if Kafka loses quorum (rather than buffering on volatile single-node disks) honors the rule that an acknowledged span is never lost, while moving segments older than 30 days to Infrequent Access storage cuts the 90-day storage bill ~30% (~$5,200 → ~$3,600/mo) in exchange for slightly slower cold reads on month-old traces.

Common mistakes

  • Writing one S3/GCS object per span or waiting on S3/DB writes before returning 202, which simultaneously breaks the < 50 ms ack SLO, hits S3 per-prefix request limits, and creates a $75,000/month PUT bill.
  • Compressing an entire 8 MB segment file as a single gzip/zstd stream, which forces every byte-range read of a single span at offset 7 MB to download and decompress all preceding 7 MB from byte 0.
  • Pushing raw 5 MB multimodal spans straight through Kafka, exceeding default ~1 MB broker message limits and causing head-of-line blocking for thousands of small spans behind them (and checking only single fields misses spans where five 900 KB fields sum to 4.5 MB).
  • Partitioning Kafka by span_id instead of tenant_id:trace_id, scattering a 40-span trace across 40 different segment files so opening one trace triggers 40 separate S3 reads.
  • Omitting the trailing / on materialized paths (LIKE 'root/7f1%' instead of LIKE 'root/7f1/%'), which corrupts subtree queries by matching unrelated sibling IDs like root/7f10.
  • Billing tokens with incremental SQL updates (SET tokens = tokens + delta) or deduplicating only by batch Idempotency-Key, which double-bills customers on stream-processor crash recovery or whenever an SDK re-packs timed-out spans into a new batch.
  • Averaging pre-computed p95 or p99 latencies across minutes or servers, which is mathematically invalid when traffic varies; always store and merge quantile sketches (t-digest or DDSketch).

Follow-up questions

  • How do you prevent duplicate spans and double-counted tokens when SDKs retry timed-out batch uploads? Anchor identity on the client-generated span_id (assigned by the SDK before the first network attempt), never solely on the HTTP batch Idempotency-Key, because an SDK often splits or merges spans into a different batch on retry. At the edge, a short 10-minute Redis cache of Idempotency-Key can short-circuit exact whole-batch repeats cheaply, while partitioning Kafka by tenant_id:trace_id routes every retry of a span to the same segment writer (which drops back-to-back repeats via a small in-memory LRU set). Downstream, each tier enforces the exactness it requires: Flink billing deduplicates (tenant_id, span_id) over 48 hours of RocksDB state backed by idempotent total upserts and a nightly ClickHouse reconciliation query, while ClickHouse's ReplacingMergeTree plus in-memory read merging collapse duplicate (span_id, event) metadata rows cleanly.
  • Where in the pipeline would you scrub leaked secrets and sensitive PII from prompts and outputs without violating the 50 ms ingest target? Never run heavy regex or ML redaction before the < 50 ms ingest ack. First provide synchronous SDK masking hooks so security-conscious tenants can scrub secrets in-process before data ever leaves their VPC; second, run server-side redaction asynchronously inside the segment writers (after Kafka ack, before bytes touch S3 or ClickHouse previews). Every writer runs a compiled linear-time multi-pattern scanner (such as RE2 / Aho-Corasick) plus Luhn and high-entropy token checks to mask API keys, JWTs, emails, and credit cards ([REDACTED:API_KEY]) in under a millisecond per 20 KB span, while projects opting into heavier ML-based Named Entity Recognition route through an autoscaled GPU/CPU NER worker pool prior to segment flush. Because unredacted bytes exist briefly in Kafka, encrypt the Kafka topic at rest and in transit, restrict ACLs solely to segment writers, and cap topic retention to 24–72 hours.
  • How can customers run offline evaluations or anomaly scans across a full month of archived traces without slowing interactive queries and dashboards? Isolate batch analytics completely from the serving ClickHouse nodes and Query API caches. A nightly background pipeline exports each closed day's deduplicated span metadata into partitioned Apache Parquet files in object storage (analytics_meta/{tenant_id}/{date}/), allowing ephemeral autoscaled engines (Spark, Trino, or DuckDB workers running in the same cloud region for $0 egress fees) to filter 30 days of traces using Parquet column projection and row-group min/max statistics without sending a single query to ClickHouse. Only after filtering narrows 15 billion spans down to the specific target subset (for example, failed RAG calls on a specific prompt tag) do workers issue throttled, per-tenant-capped HTTP byte-range GETs against the immutable .seg files—and because .seg files sit across date/hour/partition prefixes in S3/GCS, parallel batch reads never contend with live dashboard rollups.

Follow-up questions

Similar questions

More Langchain interview questions

All 1 Langchain questions →