Building a Metrics Platform for a Conversational AI Service
System DesignModel answerLast updated
Design a scalable analytics backend that ingests events from production systems, computes real-time and historical metrics, and serves aggregated data to dashboards.
You're tasked with architecting a metrics and analytics platform for a large-scale conversational AI service. This platform will power internal dashboards used by product teams and engineers to monitor service health and understand user behavior.
The LLM inference infrastructure and dashboard frontend are already built. Your job is to design the middle layer: the data infrastructure that pulls information from production systems, transforms it into useful metrics, and exposes those metrics through an API.
Your design should cover:
- Data collection strategy – how to extract data from live services and databases without impacting performance
- Schema design – what event structures and data models you'll use to represent activity
- Dual-path processing – supporting both quick approximate insights (1-2 minutes) and precise historical analysis
- Metric computation – calculating indicators like daily active users, conversation counts, throughput, latency distributions, token consumption, failure rates, and feature usage
- Dimensional analysis – enabling breakdowns by time period, model variant, geographic region, client platform, and user cohort
- Data quality – ensuring accuracy through deduplication, handling late-arriving data, and supporting historical corrections
- Security and governance – access controls, privacy protections, and system observability
- Query interface – what APIs or query patterns the dashboard will use to retrieve metrics
Assume you're operating at significant scale with requirements for multi-month data retention.
Hints
Hint 1
Consider how to extract operational data without adding load to transaction-processing systems
Hint 2
Think about which metric types can be combined across time windows and which cannot
Hint 3
Separate the path for immediate operational visibility from the path for accurate historical reporting
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Building a Metrics Platform for Conversational AI
This problem tests your ability to design a data-intensive system that balances speed, accuracy, and operational safety. Strong candidates recognize this as a data platform challenge requiring careful choices around extraction methods, aggregation techniques, and the tension between real-time approximations and batch correctness.
1. Establish Scope and Scale
Begin by quantifying the problem:
- User base: 50M daily active users generating approximately 500M AI interactions per day (average 6K requests/sec, peak 20K)
- Event volume: Assuming 4 events per interaction (request initiated, response generated, user feedback, client telemetry), that's roughly 2B events daily at 1KB each—about 2TB raw or 300GB compressed in columnar format. One year of retention means approximately 120TB stored.
- Latency requirements:
- Operational metrics (errors, latency) visible within 1-2 minutes
- Product metrics (user counts, adoption) approximate within an hour, finalized next day
- Query load: Hundreds of internal users, tens of queries per second, targeting sub-2-second response for pre-computed views and under 30 seconds for ad-hoc historical queries
- Out of scope: Not storing raw conversation content in analytics; no real-time per-user personalization
2. Architecture Overview
The system follows a dual-path architecture where a single event stream feeds both real-time and batch pipelines:
Production Sources:
├─ Application servers (structured logs)
├─ Client SDKs (telemetry)
└─ Primary databases (CDC streams)
↓
Message Bus (Kafka, 7-day retention)
↓
┌───────┴───────┐
↓ ↓
Stream Processor Long-term Storage
(Flink) (S3 + Iceberg)
├─ validation ↓
├─ deduplication Batch Engine
├─ 1-min windows (Spark/dbt)
↓ ├─ deduplication
Real-time Store ├─ sessionization
(ClickHouse/Druid) └─ daily rollups
↓ ↓
└─► Query Service ◄┘
(caching, authz)
↓
Dashboard API
The streaming path provides fast visibility with acceptable approximation. The batch path over the data lake is authoritative and eventually overwrites streaming results for completed time periods.
3. Data Extraction Without Impacting Production
Never query primary transaction databases for analytics. Instead:
-
Change Data Capture for entities: Use CDC tools (like Debezium) reading from database replication logs to capture changes to users, conversations, subscriptions, and configuration. This runs against replicas and adds minimal overhead while capturing every modification including deletions.
-
Direct emission for request telemetry: The AI gateway emits structured events asynchronously to local collection agents (Fluent Bit, Vector) that buffer and forward to Kafka. The critical path never blocks on analytics—if buffers fill, events drop with alerting rather than slowing user requests.
-
Outbox pattern for transactional consistency: When a business event must be atomically consistent with a database write (like "conversation created"), write it to an outbox table in the same transaction, then stream from there.
-
Initial backfill: For historical data, export from a database backup or read replica to object storage, then begin streaming from a known log position.
4. Event and Metric Schema Design
Define a versioned canonical event schema (using Avro or Protobuf in a schema registry):
event_id: UUID (idempotency key from source)
event_type: request_completed | message_sent | feedback_received | feature_activated
event_timestamp: source system time (UTC)
ingestion_timestamp: collection time
user_pseudonym: hashed identifier (not reversible to actual user_id)
organization_id, conversation_id, request_id
dimensions: {
model_variant, geographic_region, client_platform,
application_version, user_tier
}
metrics: {
duration_ms, time_to_first_token_ms,
input_tokens, output_tokens,
http_status, error_category, feature_identifier
}
schema_version
In the warehouse, use a dimensional model:
- Fact tables:
fact_ai_request,fact_user_message,fact_feature_event - Dimension tables:
dim_user(slowly changing type 2 to preserve historical segment membership),dim_model,dim_feature
Pre-aggregated metric tables at multiple granularities:
metric_summary(
time_window [1min | 1hour | 1day],
model_variant, region, platform, user_tier,
-- additive metrics
request_count, error_count, input_token_sum, output_token_sum,
-- sketch-based metrics
latency_sketch BLOB,
unique_users_sketch BLOB,
unique_conversations_sketch BLOB
)
5. Computing Metrics: The Mergeability Principle
Dashboards aggregate across time and dimensions, so stored aggregates must be algebraically mergeable:
| Metric | Storage Approach | Rationale |
|---|---|---|
| Volume, token counts, errors | Simple counters | Directly additive |
| Error rate, success rate | Store numerator and denominator separately | Cannot average percentages—must recompute from component counts |
| Latency percentiles (p50, p95, p99) | T-digest or DDSketch | Percentiles don't average; sketches merge with ~1% error |
| Unique users/conversations (DAU, MAU) | HyperLogLog sketches | Set cardinality with ~0.8% error; streaming uses HLL, batch computes exact counts daily |
| Feature adoption rates | Ratio of HLL sketches | Can compute adoption = users_with_feature / total_active_users |
The stream processor (Flink) computes 1-minute tumbling windows keyed by dimension combinations, using event-time semantics with watermarks allowing 5 minutes of lateness. It writes sketch-based aggregates to the real-time store. The batch pipeline recomputes hourly and daily rollups from raw events in the lake for accuracy.
6. Dimensional Slicing and Cardinality Management
-
Pre-aggregate low-cardinality dimensions only: model_variant (~20 values), region (~15), platform (~5), user_tier (~5), plus time. This produces roughly 50K dimension combinations per minute—manageable for real-time stores.
-
High-cardinality analysis goes to the warehouse: Queries by organization, application version, or other high-cardinality attributes query the data lake directly via Trino or BigQuery over Iceberg tables partitioned by date and clustered by common filter columns (model, region).
-
Multi-resolution retention: Store 1-minute rollups for 14 days, 1-hour for 90 days, 1-day indefinitely. This controls storage costs while preserving granularity where it matters.
7. Data Quality: Deduplication, Lateness, and Backfills
-
Deduplication strategy:
- Event producers use at-least-once semantics (duplicates possible)
- Stream processor deduplicates on
event_idusing keyed state with 1-hour TTL - Batch pipeline performs exact deduplication:
ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY ingestion_timestamp) = 1 - Sink operations are idempotent (upsert keyed by time bucket + dimensions)
-
Handling late data:
- Streaming watermarks allow 5 minutes of lateness before closing windows
- Very late events (beyond watermark) route to a side output for batch reconciliation
- Batch processing uses event timestamp (not ingestion time) and fully replaces streaming data for closed days
-
Backfill process:
- Reprocess historical partitions in the lake with corrected logic
- Atomic partition replacement in Iceberg prevents partial updates
- Query service cache invalidation ensures dashboards see updated data
8. Privacy, Access Control, and Observability
-
Privacy:
- User identifiers are one-way hashed before entering analytics (not reversible to actual users)
- Conversation content never enters the metrics pipeline
- PII scrubbing rules applied at collection boundaries
- Regional data residency enforced through Kafka topic partitioning
-
Access control:
- Query service enforces role-based access control (product team can see their features, SRE sees all operational metrics)
- Organization-level data segregation for multi-tenant scenarios
- Audit logging of all metric queries
-
System observability:
- Monitor ingestion lag (event timestamp vs. processing timestamp)
- Track data loss (expected event counts vs. actual from upstream instrumentation)
- Alert on schema violations, processing failures, query latency degradation
- End-to-end data quality tests using synthetic events with known properties
9. Query Layer and API Design
The metrics query service provides a semantic layer between raw storage and dashboards:
-
Time-series API:
GET /metrics/{metric_name}?start={ts}&end={ts}&interval={1m|1h|1d}&dimensions={model,region}- Returns pre-aggregated time series, merging sketches on the fly for requested dimension combinations
-
Top-N API:
GET /metrics/{metric_name}/top?dimension={platform}&limit=10- Identify highest-volume or highest-error platforms/models
-
Comparison API:
GET /metrics/{metric_name}/compare?baseline={model_v1}&comparison={model_v2}- Side-by-side metric comparison for A/B analysis
-
Caching strategy:
- Completed time periods cached indefinitely (immutable once batch processing closes them)
- In-flight periods cached for 1 minute
- Cache keyed by (metric, time range, dimensions, aggregation function)
Common Pitfalls
- Averaging percentages or percentiles – always store components and recompute
- Querying production databases directly – use CDC or async event emission
- Ignoring event-time vs. processing-time – user actions must be attributed to when they occurred, not when processed
- Unbounded cardinality in pre-aggregation – explodes storage and query performance
- Single path (streaming or batch only) – sacrifices either speed or accuracy
This design balances operational visibility with analytical rigor, protects production systems, and scales to billions of daily events while maintaining query performance.