Design a High-Scale Event Streaming and Analytics Pipeline
System DesignModel answerLast updated
Design an end-to-end pipeline that ingests millions of user interaction events per day, handles duplicates and late arrivals, and serves both real-time dashboards and raw session queries.
Context
A SaaS platform used by thousands of enterprise customers wants to understand how users interact with its product. Every time a user loads a page, completes a workflow step, triggers an error, or clicks a significant control, the application should record that event. The collected data will power three things:
- Internal product dashboards showing adoption trends, funnel conversion, and daily/monthly active user counts — updated within one minute of events arriving.
- Per-session and per-user audit trails that enterprise customers can request, for compliance and support investigations.
- Ad-hoc exploration by analysts who want to query raw events across arbitrary dimensions.
Your task is to design the full system: the client-side SDK and ingest API, the data pipeline, the storage layer, and the query path.
Scale to Design For
| Dimension | Value |
|---|---|
| Enterprise tenants | 10,000 |
| Daily active users | 5 million |
| Events per user per day | ~100 |
| Total events per day | ~500 million |
| Average event payload | 1 KB |
| Average throughput | ~6,000 events/sec |
| Peak throughput (4× burst) | ~25,000 events/sec / ~25 MB/sec |
| Raw event retention | 90 days hot, then cold archive |
| Aggregate retention | Indefinite |
Requirements
Functional
- A client SDK and HTTP ingest API that collect structured events from web and mobile apps.
- Client-side buffering and retry so events are not lost on flaky connections; deduplication so retries do not inflate counts.
- Real-time aggregations (DAU/MAU, top actions per tenant, conversion funnels) with data freshness under one minute.
- Raw event queries: retrieve the full chronological event trace for a given user, session, or time window.
- Strict data isolation between tenants — one tenant must never be able to read another's events.
Non-functional
- Ingest API p99 latency under 50 ms.
- Dashboard query latency under 1 second.
- 99.99% ingest availability; no event loss after the server acknowledges receipt.
- Horizontal scalability to handle ingestion spikes and growing data volume.
What Your Answer Should Cover
- SDK and API design — event schema, client-side buffering, retry and deduplication strategy, offline persistence.
- End-to-end pipeline architecture — ingestion tier, message bus, stream processing, persistence, and archive layers.
- Storage trade-offs — justify your choice(s) among columnar OLAP, wide-column stores, time-series databases, and object storage for raw vs. aggregate data.
- Data integrity — how you handle duplicate events from retries, out-of-order events, and device clock skew.
- Multi-tenancy — how isolation is enforced at every layer.
- Honest trade-offs — where your design makes simplifying choices and what you give up.
Hints
Hint 1
Start with the math: 500M events/day × 1 KB is 500 GB/day uncompressed. Work out what that means for Kafka retention, hot storage, and cold archive before picking any technology. Numbers anchor every trade-off that follows.
Hint 2
The hardest constraint is 'no event loss once acknowledged.' Think about what the ingest gateway must do before it returns 202 — and what happens if the downstream message bus is briefly unreachable.
Hint 3
For storage, the raw-event workload (fetch all events for user X in session Y) and the aggregate workload (count distinct users per tenant per day) have very different access patterns. Consider whether one engine can serve both, and if so, what table layout makes it work.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing the System First
Before touching architecture, turn the numbers into concrete storage and throughput targets. This shapes every decision.
| Metric | Calculation | Result |
|---|---|---|
| Peak ingest bandwidth | 25K events/s × 1 KB | ~25 MB/s |
| Raw volume per day | 500M × 1 KB | ~500 GB/day |
| Hot storage (90 days, ~8× columnar compression) | 500 GB × 90 ÷ 8 | ~5–6 TB, ~12 TB with 2 replicas |
| Kafka retention (7 days, RF=3) | 500 GB × 7 × 3 | ~10–11 TB |
| Aggregates | Rollup tables | Low GBs per year |
A single ingest pod handles roughly 5,000 req/s at under 50 ms. You need a small fleet per availability zone to absorb peak, plus a load balancer in front.
Good clarifying questions before proceeding: Is audit logging held to a stricter completeness guarantee than analytics? (Assume yes — it must be immutable and gap-free.) Does "freshness under one minute" apply only to dashboards? (Assume yes.) Are tenants uniformly sized? (Assume no — expect a power-law distribution where a handful of tenants generate most traffic.)
2. SDK and Ingest API
Event schema
{
"event_id": "018f2c1e-...-uuidv7",
"event_name": "workflow.step_completed",
"user_id": "u_83f2",
"session_id": "s_19a",
"client_ts": "2024-05-01T10:00:01.004Z",
"sent_at": "2024-05-01T10:00:05.120Z",
"schema_version": 3,
"context": { "platform": "web", "app_version": "5.2.1" },
"properties": { "workflow": "payroll", "step": 4 }
}
The event_id is a UUIDv7 — time-ordered and collision-safe, generated the moment the event occurs. Retries replay the same ID, making deduplication straightforward. The server stamps received_at and tenant_id (derived from the auth credential, never from the payload — this is the first isolation boundary).
Endpoint: POST /v1/events:batch — accepts up to 20 events, returns 202 Accepted with per-event status. Unknown properties are accepted; malformed envelopes are rejected with a reason code.
SDK behavior
- Batching: buffer events in memory, flush on 20 events, 5-second timeout, or app backgrounding. Use
sendBeacon/fetch keepaliveon web so navigations don't drop the flush. - Offline persistence: write unsent events to IndexedDB (web) or SQLite (mobile). Cap the buffer at ~1,000 events or 5 MB; drop the oldest when full and increment a dropped-events counter. Delete only after acknowledgment.
- Retry: exponential backoff with jitter. Respect
429 Retry-After. Never retry4xxvalidation failures. - Compression: gzip each batch, typically reaching 10–20% of original size.
3. Pipeline Architecture
SDKs
→ Global LB / edge CDN
→ Ingestion Gateway (auth · validate · rate-limit · stamp received_at)
→ Kafka (raw-events topic, RF=3, acks=all, min.insync.replicas=2)
├─ Flink job: dedup → clock-correct → enrich
│ ├─ ClickHouse: raw_events table (90-day hot)
│ └─ ClickHouse: rollup/aggregate tables
├─ Archiver consumer → S3 Parquet / Iceberg (cold, partitioned by tenant/date)
└─ Audit consumer → append-only, object-locked bucket per tenant
Query Service (tenant-scoped, result-cached) → dashboard and ad-hoc query paths
Critical invariant: the gateway returns 202 only after Kafka confirms acks=all. That is the "no loss once acknowledged" boundary. If Kafka is briefly unavailable, the gateway spills to a local disk spool and replays asynchronously — this is what keeps availability at 99.99% without sacrificing the durability guarantee.
Kafka partition key: hash(tenant_id, user_id) preserves per-user ordering and distributes load across partitions. 64–128 partitions leaves growth headroom.
This is a Kappa-style architecture: one canonical log, with historical reprocessing done by reading from Iceberg rather than maintaining a separate batch code path.
4. Storage Strategy
| Engine | Raw per-user traces | Multi-dimensional aggregates | Verdict |
|---|---|---|---|
| Wide-column (Cassandra / Bigtable) | Excellent point lookups | No ad-hoc group-by | Too narrow |
| Time-series DB (InfluxDB / Prometheus) | Poor — high-cardinality user_id | Good only for fixed metrics | Wrong fit |
| Columnar OLAP (ClickHouse / Druid / Pinot) | Good with the right sort key | Excellent | Choose this |
ClickHouse serves both workloads with careful table design:
Raw events table
- Engine:
ReplicatedReplacingMergeTree(event_id)— the replacing key handles late-arriving duplicates. - Partitioned by
toYYYYMMDD(event_time), ordered by(tenant_id, user_id, event_time). - A session trace or audit query is a narrow range scan on the primary key. TTL drops partitions older than 90 days from hot storage; Iceberg holds the archive.
Aggregate rollup tables
- Engine:
AggregatingMergeTree, fed by Flink or ClickHouse materialized views. - Store
uniqCombinedState(user_id)per tenant per minute. HLL states merge across time windows, so MAU = merge of 30 daily states. Error is ~1%, acceptable for dashboards. - Action counts keyed on
(tenant_id, event_name, minute). - Funnel queries use ClickHouse's
windowFunnel()overraw_events, bounded by tenant and time range — this hits the under-1-second target at this scale.
Sharding: shard by tenant_id. Large tenants get dedicated shards or are further split by (tenant_id, user_id mod N).
5. Data Integrity
Duplicate events are produced at every hop (SDK retry, Kafka at-least-once, Flink reprocessing). Deduplicate in layers:
- Flink maintains keyed state on
event_idin RocksDB with a 24-hour TTL. At 500M events/day × 16 bytes per UUID, this is manageable (~8 GB state). - Flink uses exactly-once checkpoints with idempotent writes to ClickHouse.
ReplacingMergeTreeis the backstop — useFINALorargMaxfor audit-grade reads that cannot tolerate duplicates.
Clock skew is corrected server-side:
event_time = received_at − (sent_at − client_ts)
This cancels a constant device clock offset. If the corrected value differs from received_at by more than 24 hours, fall back to received_at and set a ts_suspect flag. Preserve all three original timestamps so audit investigations remain explainable.
6. Multi-Tenancy Enforcement
Isolation is layered, not relied on at a single point:
tenant_idis set from the auth credential server-side, never from the event payload.- The Query Service injects a mandatory
tenant_idfilter derived from the caller's identity token. - ClickHouse row-level policies enforce the same filter as a second guard.
- Each tenant gets its own S3 prefix and a separate KMS key for the archive.
- The audit store is a separate, object-locked bucket per tenant.
7. Trade-offs to Be Explicit About
ClickHouse for both workloads keeps the operational footprint small, but heavy ad-hoc scans can compete with dashboard queries. Mitigate with separate read replicas or per-workload query quotas.
HLL for unique counts introduces ~1% error. If DAU/MAU figures feed billing, compute exact counts in a nightly batch job over Iceberg instead.
Kappa over Lambda eliminates duplicate processing logic, but historical backfills are gated on Iceberg read throughput — plan for that if you anticipate frequent schema corrections.
Common mistakes to avoid: deriving tenant_id from the client payload (injection risk), using only the client timestamp for ordering (clock skew breaks funnels), skipping the local spool fallback on the gateway (drops events during Kafka maintenance), and relying on a single deduplication layer (any one layer can be bypassed or delayed).