Real-Time Event Processing Pipeline for High-Volume Telemetry
System DesignModel answerLast updated
Build a scalable pipeline ingesting ~1B events/day from distributed clients, delivering both low-latency metrics and accurate daily reports.
You're building a telemetry platform for a consumer application with clients running on web browsers, mobile devices, and connected TVs. These clients generate behavioral events: user interactions, playback actions, screen views, and periodic health checks.
The platform handles approximately 1 billion events daily. Business stakeholders need two outputs from this single pipeline:
- Live operational metrics — dashboards showing current activity, user counts, and feature usage, refreshed within minutes
- Trusted aggregate reports — finalized daily summaries that downstream teams rely on for decisions and financial reporting
Design a complete pipeline from event generation through query-serving that maintains throughput during traffic surges so metrics reflect current state quickly rather than falling hours behind. Address the journey from client instrumentation, through collection and computation, to the systems where aggregated data is queried.
Your design must handle:
-
System topology and capacity planning — Components from client through collection, buffering, computation, storage, and query layers. Include rough calculations (throughput rates, data volumes, partition counts, compute parallelism) that inform your choices.
-
Throughput management — How you identify when processing is falling behind incoming volume, and how you maintain pace during traffic increases without silently losing data.
-
Out-of-order arrivals — Devices lose connectivity and batch-upload events much later. Events may arrive hours or days after they actually occurred. How do you keep daily totals correct when relevant events arrive after a day's report has been published?
-
Event deduplication — Network behavior means clients may send the same event multiple times. How do you ensure each real-world event increments your counters exactly once?
Operating Parameters
- Average daily volume ~1B events; traffic follows usage patterns with peak loads 3-10× the average — sustained rates of tens of thousands events/sec with spikes approaching 100k events/sec
- Events average 0.5-1 KB (identifiers, timestamps, event classification, contextual attributes) in JSON or Avro; roughly 0.5-1 TB raw data daily
- Each event includes event timestamp (when it occurred on the device) distinct from arrival timestamp (when received by infrastructure)
- Client delivery is at-least-once — network retries mean duplicate sends are possible
- Live dashboards should reflect reality within minutes; hourly rollups within several minutes; final daily numbers within hours of day boundary
- Aggregates must be correct and auditable — late events and duplicates cannot corrupt counts; finalized daily figures must be trustworthy
- System should buffer rather than drop during overload, then recover
- Assume cloud infrastructure with managed storage, message queues, stream processors, and analytical databases
Key Questions to Explore
- What latency guarantees do consumers need — sub-minute updates or hourly/daily batch acceptable?
- Can published daily totals be revised, or must they be immutable once released?
- Is approximation acceptable (probabilistic distinct counts) or must all aggregates be exact and reconcilable?
- What's the realistic window for late data — minutes, hours, days — and is there a cutoff beyond which late events are handled separately?
- What serves as the deduplication key? Do events carry stable client-generated IDs, or must you construct keys from event attributes?
- Which metrics matter most (distinct user counts, additive counters like plays, conversion funnels) and what's the dimensional cardinality?
- How stable is the event schema — do you need versioning and evolution support?
- What are retention, cost, and compliance constraints (raw vs aggregated retention, PII, deletion handling)?
- Is the priority lowest latency, lowest cost, or operational simplicity?
Hints
Hint 1
Consider separating the speed layer (real-time approximations) from the batch layer (accurate reconciliation) and how they eventually converge
Hint 2
Use event-time windowing with watermarks to handle out-of-order delivery while eventually closing windows for finalization
Hint 3
Think about how idempotency keys and stateful deduplication within bounded windows can achieve exactly-once semantics
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
A robust solution uses a staged pipeline with clear separation of concerns:
Client → Ingestion Gateway → Durable Log → Stream Processor → Storage + Serving
Stage 1: Client SDK and Buffering
Clients batch events locally (10-50 events or 5-10 seconds) before sending to reduce network overhead. Each event gets a client-generated UUID as an idempotency key. Clients implement exponential backoff retry on failure.
Stage 2: Ingestion Gateway
Horizontally-scaled HTTP services (behind load balancers) receive client batches. The gateway validates schema, enriches with arrival timestamp, and writes to the durable log. Lightweight stateless design allows easy scaling. Returns 2xx only after log acknowledgment.
Stage 3: Durable Partitioned Log
Kafka, Kinesis, or Pub/Sub serves as the backbone. This is where back-pressure is absorbed — if processors lag, events queue rather than being dropped.
Capacity calculation: 1B events/day = ~11.5k events/sec average. With 10× peak = 115k events/sec. At 1KB per event = 115 MB/sec peak throughput.
Partition by a composite key like user_id or session_id to preserve ordering per user while distributing load. For Kafka, 100-200 partitions provides good parallelism. Retention of 3-7 days allows reprocessing windows.
Stage 4: Stream Processing
Use Apache Flink or Spark Structured Streaming for computation.
Event-time processing: Window on event_timestamp not arrival time. Configure watermarks — the system's estimate of how far out-of-order data can be. For example, a 5-minute watermark means "I expect events to arrive within 5 minutes of their event time."
Allowed lateness: Accept events up to 1-2 hours past the watermark before finalizing a window. Late events update in-flight aggregates. Events arriving after finalization go to a side output for correction processing.
Deduplication: Maintain bounded state keyed by event_id within each window. Flink's managed state automatically handles this with checkpointing. For Spark, use dropDuplicates with watermarking to bound state.
Two-path approach:
- Speed path: Real-time aggregations with 1-5 minute tumbling windows, using HyperLogLog for distinct counts (DAU/MAU). These are "provisional" and may be revised.
- Batch path: Hourly/daily recomputation from immutable raw events in object storage using exact SQL aggregations. These become "finalized" numbers.
Parallelism: With 100 partitions, run 100-200 task slots to handle peak load with headroom.
Stage 5: Storage
Raw events: Write to object storage (S3/GCS) in columnar format (Parquet) partitioned by date/hour from event timestamp. This is the immutable source of truth for reprocessing. Compress to ~200 GB/day.
Aggregates: Upsert into a columnar warehouse (BigQuery, Redshift, Snowflake) or OLAP store (ClickHouse, Druid) keyed by (metric, dimension_keys, window_timestamp). Mark records as provisional vs finalized.
Stage 6: Serving
Dashboards query the aggregate tables. Query engines provide sub-second response on pre-aggregated data. For real-time, query the latest provisional aggregates. For reports, query finalized data only.
Handling Late Data
Provisional-to-finalized lifecycle:
- Streaming produces provisional aggregates immediately
- After a window closes + lateness period (e.g., 2 hours after midnight for a daily window), mark as finalized
- Very late events (days later) trigger a correction job that reprocesses the affected partition and emits a delta or full replacement
Storage pattern: Use MERGE/UPSERT semantics. When reprocessing, overwrite the specific window partition with corrected totals. Queries see only the latest version.
Exactly-Once Semantics
End-to-end exactly-once requires:
- Idempotent source: Client-generated event IDs prevent duplicate processing
- Stateful deduplication: Stream processor maintains seen IDs within window bounds
- Transactional sinks: Flink's two-phase commit or Spark's
foreachBatchwith idempotent writes (upsert by window key)
Trade-off: True exactly-once adds latency (coordinator overhead) and complexity. For many metrics, effectively-once (dedup in stream + idempotent sink) is sufficient and simpler.
Scaling and Lag Management
Metrics to monitor:
- Consumer lag: Offset delta between latest message and last processed
- Watermark skew: How far behind real-time the watermark is
- End-to-end latency: Event timestamp to aggregate availability
Autoscaling:
- Scale gateway on CPU/request rate
- Scale stream processors on consumer lag threshold (e.g., lag > 1M messages or > 5 minutes)
- Pre-partition the log for peak capacity
Hot partition handling: Monitor per-partition lag. If one partition lags (skewed key), use key salting — append random suffix to partition key, aggregate with two-stage computation (local pre-aggregation, then global aggregation).
Distinct Count Approximation
Exact COUNT(DISTINCT user_id) requires shuffling all data — expensive at scale. Instead:
- Streaming path: HyperLogLog sketches (~1% error with 12KB state) that are mergeable across windows
- Batch path: Exact counts from warehouse SQL for finalized reports
Mark HLL-based metrics as approximate in dashboards.
Back-of-Envelope Summary
- Ingress: 115k events/sec peak, 115 MB/sec
- Log: 100-200 partitions, 3-7 day retention, ~3-7 TB storage
- Processing: 100-200 parallel tasks, 500 GB-1 TB memory for windowed state
- Raw storage: 200 GB/day compressed, ~6 TB/month, ~72 TB/year (before archival)
- Aggregates: 1-10 GB/day depending on cardinality
Observability
- Ingest rate, latency, error rate at gateway
- Consumer lag per partition
- Watermark progression
- Late-arrival rate and dead-letter queue volume
- Deduplication hit rate
- Provisional vs finalized delta size
- Alert on lag > threshold or watermark falling behind > SLA
Trade-offs
Lambda (dual path) vs Kappa (stream-only):
- Lambda: Simpler correct batch logic, but duplicate code maintenance
- Kappa: Single processing logic, but harder to achieve accuracy in streaming
Freshness vs accuracy:
- Real-time approximate (HLL) for dashboards
- Delayed exact for reports
Cost vs latency:
- More frequent checkpointing = lower recovery time but higher overhead
- Higher parallelism = lower latency but more cost
This architecture handles the scale, absorbs spikes via the durable log, achieves low-latency provisional results via streaming, and produces trustworthy finalized numbers via batch reconciliation, all while correctly handling late arrivals and duplicates.