ClickHouse vs Postgres for AI Agent Observability: Storing 100M+ LLM Trace Spans & Token Telemetry at Sub-Second Query Speed
When Postgres Stops Scaling for Agent Traces
PostgreSQL is unbeatable for transactional agent state (users, sessions, billing_meters). However, teams frequently also dump every raw OpenTelemetry LLM span (including 30KB prompt bodies and JSON tool results) into a single Postgres agent_spans table.
By month 3 (~15 million spans):
- Storage balloons past 450 GB (row-oriented storage compresses repetitive JSON poorly).
- Simple dashboard queries (
SUM(input_tokens)over the last 7 days per tenant) trigger multi-second sequential scans. VACUUMcompetes with high-throughputINSERTstreams from worker pods.
Architecture: Columnar ClickHouse + Materialized Rollups
Offloading append-only trace telemetry to ClickHouse gives 8x–12x ZSTD compression on repetitive system prompts and sub-100ms analytical aggregations across 100M+ spans:
text[FastAPI / Agent Workers] ──► [Async Batch Buffer (1,000 spans or 2s)] │ ▼ [ClickHouse: agent_otel_spans (MergeTree)] ├── ORDER BY (tenant_id, timestamp, trace_id) ├── ZSTD(3) on prompt/completion columns (~10x smaller!) └── Materialized View ──► hourly_token_cost_mv (instant UI!)
Production ClickHouse DDL (MergeTree + Materialized View)
sqlCREATE TABLE agent_otel_spans ( tenant_id LowCardinality(String), trace_id String, span_id String, model LowCardinality(String), tool_name LowCardinality(String), input_tokens UInt32, output_tokens UInt32, cache_read_tokens UInt32, latency_ms Float32, is_error UInt8, prompt_payload String CODEC(ZSTD(3)), response_payload String CODEC(ZSTD(3)), timestamp DateTime64(3, 'UTC') ) ENGINE = MergeTree() PARTITION BY toYYYYMM(timestamp) ORDER BY (tenant_id, timestamp, trace_id) TTL toDateTime(timestamp) + INTERVAL 90 DAY DELETE; -- Pre-aggregated Materialized View for instant sub-10ms dashboard charts CREATE MATERIALIZED VIEW hourly_token_cost_mv ENGINE = SummingMergeTree() ORDER BY (tenant_id, model, hour_bucket) AS SELECT tenant_id, model, toStartOfHour(timestamp) AS hour_bucket, sum(input_tokens) AS total_input_tokens, sum(output_tokens) AS total_output_tokens, sum(cache_read_tokens) AS total_cache_hits, count() AS total_spans FROM agent_otel_spans GROUP BY tenant_id, model, hour_bucket;
Benchmarks (50M Spans)
- PostgreSQL
JSONBTable: 192 GB disk,4.8sfor 30-day tenant token rollup. - ClickHouse
MergeTree+ZSTD(3): 18.4 GB disk (10.4x compression),14msviahourly_token_cost_mv.
Keep transactional state in Postgres, and move high-volume agent telemetry to ClickHouse.