Design a Clickstream Analytics Pipeline for a Mobile App
System DesignModel answerLast updated
Design a pipeline that ingests client events such as installs and clicks, powers near-real-time dashboards, and keeps raw data for batch analysis, with explicit correctness trade-offs.
Design a Clickstream Analytics Pipeline
A consumer app has a very large user base. Clients emit behavioral events such as app installs, impressions, and button clicks. The product team wants to see how the app is doing as it happens, and the data science team wants to dig into history later.
Design the system end to end.
What the system must do
- Live dashboards. Show metrics that refresh within seconds, for example installs per minute and click-through rate.
- Raw event retention. Keep every raw event so that large offline jobs (daily or weekly rollups, deeper analysis, backfills) can run on it.
- Metric scoping. The exact metric list is not fixed. Say which questions you would ask to pin it down, then assume a mix of counters and ratios, sliced by dimensions such as platform, app version, and country.
Quality expectations
- Very high write throughput from many clients.
- Seconds-level freshness on dashboards.
- Storage and compute that scale horizontally.
- Aggregates that are reasonably correct. Be explicit about delivery guarantees (at-least-once vs exactly-once) and about events that arrive late.
Out of scope
Infrastructure health monitoring (host uptime, service latency) is not required. You may mention it briefly.
What to cover
Walk through the architecture, the main components, the data flow, your storage choices, and how the real-time metrics path differs from the offline analytics path. State your scale assumptions with numbers.
Hints
Hint 1
Start by clarifying metrics, dimensions, freshness targets, and rough scale (users, events per user per day) before drawing components.
Hint 2
Put a durable log between ingestion and everything else so the live aggregation path and the raw archival path can consume independently and replay.
Hint 3
Ratios such as CTR cannot be summed across rows, so think about what you store in the aggregate tables. Also decide which timestamp you window on and what happens to late or duplicated events.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Split one event stream into two consumers with different goals: a low-latency aggregation path for dashboards, and a cheap, durable, replayable raw path for batch work. Be honest that real-time numbers are provisional and batch numbers are the source of truth.
1. Clarify and size
Metrics to confirm
- Counters: installs, clicks, impressions, sessions per minute.
- Ratios: CTR = clicks / impressions, install conversion.
- Uniques: DAU, unique clickers (approximate is usually fine).
- Dimensions: platform, app version, country, event type. Ask about cardinality limits and never expose user_id as a dimension.
- Freshness: about 10 seconds for dashboards, next day for batch.
Assumptions
- 100M DAU x 50 events/day = 5B events/day, about 60K events/s average. Plan for about 300K/s at peak.
- About 1 KB/event gives roughly 5 TB/day raw JSON, or about 1 TB/day as compressed Parquet.
- Retention: raw for 1-2 years in object storage, minute aggregates for about 90 days, hourly/daily rollups longer.
2. Ingestion API
Clients batch events and send them gzip-compressed to POST /v1/events. Each event has a client-generated event_id (UUID), type, user and device ids, client_ts, platform, app version, properties, and a schema version. The server replies 202 Accepted.
Clients buffer locally, flush every N events or T seconds, retry with backoff, and drop data past a size or age cap. Batching is the biggest lever on gateway QPS.
Dashboards use a separate query API, for example GET /v1/metrics?name=ctr&from=..&to=..&granularity=1m&group_by=platform.
3. Data model
- Raw event (immutable): client fields plus server-added
server_tsand geo-derived country. - Aggregate row:
(metric, window_start, granularity, platform, app_version, country) -> count, sum, HLL sketch. - Store numerators and denominators separately. Ratios do not add up: you cannot average CTR across countries. The query layer computes
sum(clicks)/sum(impressions)after grouping.
4. Architecture
Clients -> LB/CDN -> Stateless ingestion gateway (auth, schema check, enrich)
|
v
Kafka "events.raw" (partition by device_id, RF=3)
| |
v v
Flink: dedup -> event-time windows Raw sink -> object storage
-> per-minute aggregates (Parquet, dt/hour partitions)
| |
v v
Real-time OLAP (Druid/Pinot/ClickHouse) Spark / warehouse batch jobs
| |
+---> Query service + cache <--+
|
Dashboards / alerts
- Gateway: validates against a schema registry, stamps
server_ts, writes to Kafka withacks=all, and only then returns 202. Under backpressure it returns 429 and clients retry. - Kafka: absorbs bursts, decouples consumers, and enables replay after a bug. Use a few hundred partitions for peak load and about 7 days of retention.
- Real-time path: Flink dedups, windows, and aggregates, then writes a small number of rows per minute and dimension combination to an OLAP store built for fast group-bys.
- Raw path: an independent consumer writes columnar files (128-512 MB) to object storage. It is cheap and nearly unlimited, and serves batch, ad-hoc SQL, and ML features.
5. Deep dives and trade-offs
Event time vs processing time. Window on client_ts, clamped to a sane range around server_ts, because mobile clients go offline and clocks drift. Use a watermark (for example max event time minus 1 minute), emit early results every few seconds, and accept updates for about 1 hour of allowed lateness, each upserting the window row. Anything later goes to a side output and still lands in the raw store, so batch picks it up.
Delivery semantics. The pipeline is at-least-once end to end because clients retry. Dedup in Flink on event_id with keyed state and a TTL (about 1 hour). Combine checkpointing with idempotent sinks: the aggregate key is (metric, window, dims), so replaying a window overwrites instead of double-counting. This yields effectively-exactly-once aggregates without distributed transactions.
Reconciliation. A nightly Spark job recomputes the prior day from raw data, deduplicating across the whole day, and overwrites the OLAP rows. Dashboards become exact at T+1. The alternative is a kappa design that replays Kafka through the same Flink job; it avoids two code paths but needs long Kafka retention.
Unique counts. Store HyperLogLog sketches per window. They merge across time and dimensions with roughly 1-2% error. Cap dimension cardinality (top-N app versions plus "other") to prevent row explosion.
Hot spots. A viral launch can skew country or event type. Partition by device_id rather than event type, and pre-aggregate locally before the keyed shuffle (combiner-style).
Governance. Keep PII only in the raw store with encryption and access control. Support deletion requests through partition rewrites.
Operations. Monitor consumer lag, watermark delay, dedup rate, and the gap between real-time and batch totals. A growing gap signals a bug or excess lateness.
Common mistakes
- Pre-computing ratios and then trying to roll them up.
- Windowing on processing time, which distorts numbers when clients are offline.
- Writing raw events and aggregates from one code path with no replay option.
- Claiming exactly-once without explaining how (idempotent writes plus dedup).
- Using high-cardinality fields as dashboard dimensions.
- Not saying which numbers are provisional and which are authoritative.