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/p99latencies, failure spikes, and spend or error threshold alerts. - Throughput & payload profile: Handle
50,000spans/sec at peak (~500Mspans/day), where typical spans weigh20 KBand long multi-turn or multimodal spans reach5 MB. - Latency & retention SLOs: Acknowledge ingested batches in
< 50 ms, serve trace detail lookups in< 200 msatp95, answer dashboard aggregation queries in< 1 satp95, and retain traces cost-effectively in object storage for90 days.
Scope & Expectations
- Ingestion API & write decoupling: Define the collection endpoints, SDK batching contracts, and buffering architecture that meet
< 50 msdurable 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/GETbills. - 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
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 sharedtrace_idto 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
startandendevents 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 childrun_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/sat peak (~500M spans/day);20 KBaverage payload, up to5 MBfor multi-turn or multimodal spans;90-dayretention backed by cloud object storage (S3/GCS). - Latency SLOs: Return ingest receipts in< 50 ms, serverun_idtrace views in< 200 msat p95, and answer dashboard rollups in< 1 sat p95. - What "ack" promises: A202 Acceptedresponse 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 sfreshness 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-reportedusagefields; fall back to server-side tokenization flaggedusage_estimated = truewhen omitted.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 msat1 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.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_idandtrace_idinside the SDK before the first send guarantees retries carry the exact same IDs for deduplication, and lets the server extracttrace_datedirectly fromtrace_ideven 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 referencesblob_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.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/filterTier 3 — Fast Point-Lookup Index (
run_indexin ScyllaDB / DynamoDB) & PostgreSQL Ledger: - Because ClickHouse'sspanstable is sorted by(tenant_id, trace_id, ...), looking up an arbitrary childrun_idwhen the caller only knowsrun_id(nottrace_id) would otherwise scan every partition. A compact KV tablerun_indexmapping(tenant_id, run_id) -> (trace_id, trace_date, path)(45B rows × ~100 B ≈ 4.5 TBacross 90 days) resolves anyrun_idin one2–5 msO(1) read. - PostgreSQL stores relational control-plane entities (tenants, API keys, versioned model price tables, alert rules) and the transactionalusage_hourlybilling ledger.How trailing-slash materialized paths solve
< 200 mssubtree 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 thespanssorting key ensures ClickHouse'sReplacingMergeTree—an engine that asynchronously collapses duplicate rows sharing the same sorting key during background compactions—deduplicates retriedstarts without overwritingends. At read time, the query service mergesstart+endrows byspan_idin memory so out-of-order arrivals and uncompacted duplicates never produce wrong trees.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 GETsMeeting the
< 50 msack 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/scompressed 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 KBvia/v1/blobs; if an older client sends a 4 MB inline JSON span, the ingest node strips the largest fields intoblobs/before appending the slimmed record to Kafka. - Durability over availability at the ack boundary: If a tenant exceeds its rate quota, return
429immediately so noisy neighbors stay isolated. If Kafka itself cannot reach a 2-of-3 replica quorum, return503rather than faking a202backed by volatile local disk—SDKs buffer and retry safely.
- Why partition Kafka by
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
.segcontainer every2 secondsor8 MBcompressed:+-------------------------------------------------------------------------+ | 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
zstdcompression 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 KBoccupy a single frame (~5 KB compressed—one tiny network packet burst). Spans> 64 KB(up to5 MB) split top-levelinputs,outputs, and 10-message chat chunks into separate frames, recording[(field_path, offset, length)]inside ClickHouse'sfield_framescolumn. 3. Crash-safe 3-step write order (no distributed locks needed): - Step 1:PUTthe.segfile 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 (passingsegment_keyas ClickHouse's native insert-deduplication token) andrun_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 viaReplacingMergeTree.Fetching only
outputsof 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
.segframe files for low-latency point/field reads, and reserve Parquet for nightly metadata exports powering 30-day batch analytics.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 asGET /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 averages25–45 msbut occasionally exhibits200+ mstail hiccups. We tame that tail with hedged requests: if the first S3 rangeGEThas not returned its first byte within60 ms(the observed p95), fire a second parallel rangeGETand take whichever finishes first. Firing hedges on only 5% of2,000 reads/sadds100 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,192by default), meaning every point lookup decompresses at least one whole granule: - Onspans(point/tree lookups), tuneindex_granularity = 1024so each trace read decompresses8×less data (~200 KB instead of ~1.6 MB), trading an8×larger—but still easily RAM-resident—primary index. - Onspans_by_time(time-range scans), keepindex_granularity = 8192and attach lightweight bloom-filter data-skipping indexes ontagsandmetadatakeys sofilter=tag:prodskips 95%+ of granules without maintaining giant B-tree secondary indexes. Full-text inverted indexing over prompt text is strictly opt-in per project.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_idnever changes. 2. Stateful stream deduplication: Flink partitions theusagestream by(tenant_id, span_id)and checks an embedded RocksDB state table with a48-hour TTL(~15 GBtotal state). Duplicate arrivals with identical token counts are dropped immediately; duplicates reporting different token counts route to an auditusage_conflictstable. 3. Ingest-hour attribution (no late-data drift): Usage is booked to the UTC hour the ingest server accepted the span, rather than client clockstart_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—nevertokens + 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-upsertinginput_tokens = 142500overwrites142500harmlessly, whereasinput_tokens = input_tokens + deltawould double-charge customers! 5. Reconciliation & fast quotas: Store raw token counts as ground truth and join against a versionedmodel_pricingtable at invoice time. A nightly ClickHouse batch job (SELECT uniqExact(span_id), sum(...)grouped by deduped spans) reconciles againstusage_hourlyto catch even> 48hretries. Meanwhile, Flink pushes month-to-date tenant totals to Redis every10 sfor ingest quota enforcement (bounding quota overshoot to~20 s).Sub-second dashboards (
< 1 s) & alerting: - ClickHouse Materialized Views roll incomingend/completespans intometrics_1mandmetrics_1h(AggregatingMergeTreekeyed 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 (720rows) in< 50 ms. - An Alert Evaluator queriesmetrics_1mevery 60 s across active rules (requiringmin_eventsto prevent noisy 1-of-1 error pages), tracks state transitions (OK -> FIRING -> RESOLVED) with hysteresis, and sends webhook notifications carrying deterministic idempotency keys.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
zstdframe segments cuts S3PUTbills ~90× ($75k/mo → ~$830/mo) and moves days 31–90 to Infrequent Access (~$3,600/mototal), adding2–5 sof 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 with1,024-row granules onspansand8,192-row granules + bloom filters onspans_by_timeachieves< 200 mssubtrees and< 1 sdashboards 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 Acceptedright 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 a2–5 sindexing 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 MBsegment 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
zstdcompression 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-trainedzstddictionaries. - Dual metadata sort orders & granule density vs. storage/RAM footprint. Storing compact metadata (
~4%of compressed payload volume) in two ClickHouse tables—spanswith small1,024-row granules (index blocks) sorted by(tenant_id, trace_id, path)for fast subtree reads, andspans_by_timewith8,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_1hwith mergeable t-digest percentile sketches) skip per-span stateful lookups keeps dashboard queries well under< 1 seven if retry storms briefly nudge chart counts by< 0.1%. - Durability over availability at the ack boundary, plus storage tiering by age. Returning
503if 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 msack SLO, hits S3 per-prefix request limits, and creates a$75,000/monthPUT 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_idinstead oftenant_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 ofLIKE 'root/7f1/%'), which corrupts subtree queries by matching unrelated sibling IDs likeroot/7f10. - Billing tokens with incremental SQL updates (
SET tokens = tokens + delta) or deduplicating only by batchIdempotency-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-digestorDDSketch).
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 batchIdempotency-Key, because an SDK often splits or merges spans into a different batch on retry. At the edge, a short 10-minute Redis cache ofIdempotency-Keycan short-circuit exact whole-batch repeats cheaply, while partitioning Kafka bytenant_id:trace_idroutes 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'sReplacingMergeTreeplus 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 msingest 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$0egress 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-rangeGETs against the immutable.segfiles—and because.segfiles sit across date/hour/partition prefixes in S3/GCS, parallel batch reads never contend with live dashboard rollups.
Follow-up questions
- How do you prevent duplicate spans and double-counted tokens when SDKs retry timed-out batch uploads?
- Where in the pipeline would you scrub leaked secrets and sensitive PII from prompts and outputs without violating the 50 ms ingest target?
- How can customers run offline evaluations or anomaly scans across a full month of archived traces without slowing interactive queries and dashboards?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System