Building a Streaming Clickstream Metrics Platform End to End
System DesignModel answerLast updated
Design a streaming platform that turns raw website click events into fresh, correct, queryable aggregates, covering partitioning, windows, state, sinks, back-pressure and failures.
Scenario
Your company's website emits a continuous stream of click events. Product managers want dashboards that update within about a minute, and analysts want to run ad-hoc SQL over correct historical numbers. You are asked to own the data path from the browser to the queryable tables.
The intended building blocks are:
- Kafka as the ingestion log,
- Flink as the stream processor,
- a warehouse or analytics store as the serving layer.
Task
Walk through the complete pipeline design. Your answer should cover:
- Requirements and scale. The questions you would ask first, and the numbers you assume (event rate, peak, event size, latency target, tolerance for late data).
- Kafka layout. How you choose the partition count and the partition key, and which producer and topic settings you rely on.
- Flink processing. The time semantics, window types and watermark strategy you would use, and how you deal with late and duplicate events.
- State management. The state backend, checkpointing setup, and how you handle large state such as deduplication and unique-user counts.
- Delivery guarantees. How you get correct results end to end, and what the sink must do.
- Table modeling. How downstream tables are shaped so that dashboards and analysts can use them safely, including schema evolution.
- Back-pressure and failure handling. How you detect and react to slow operators, bad records, job crashes, and the need to reprocess history.
Explain the trade-offs behind your choices, and say how you would verify the pipeline is producing correct results.
Hints
Hint 1
Start by writing down assumed numbers (events per second, peak, event size, freshness target, maximum lateness). Partition count, state size and checkpoint interval all follow from them.
Hint 2
Treat delivery guarantees as a property of the whole chain: at-least-once ingest plus deduplication, checkpointed Flink state and offsets, and a sink that is either transactional or idempotent.
Hint 3
Make late data and replays harmless: aggregate in event time, let late firings overwrite rows keyed by window and dimensions, and use mergeable sketches rather than summed counts for unique users.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
I would first confirm who consumes the data and what they need.
- Dashboards: fresh within about a minute.
- Analysts: correct history via SQL.
- Metrics: page views, clicks, unique users, sessions and funnels, sliced by page, country, device and campaign.
- Scale (assumed): 50k events/s average, 500k/s peak, about 1 KB per event. That is roughly 500 MB/s at peak and about 4 TB per day.
- SLO: p99 under 2 minutes from event to queryable aggregate.
- Correctness: no double counting from client retries, and events up to 1 hour late must still be counted.
2. Event contract
Every event carries a client-generated event_id (for dedup), an event_time, a collector-set ingest_time (to detect clock skew), user/anonymous and session IDs, dimensions (page, type, device, country, referrer) and a schema_version. Use Avro or Protobuf with a Schema Registry and backward-compatible evolution only (add optional fields, never repurpose them).
3. Architecture
Clients -> Collector (validate, enrich) -> Kafka clicks.raw
-> Flink: parse -> dedup -> enrich (async) ->
windowed aggregates -> OLAP store (upsert)
sessionization -> sessions table
clean raw events -> lakehouse (Iceberg/Delta)
-> DLQ topic for bad records
Warehouse <- lakehouse tables, batch reconciliation
Two serving paths: a low-latency OLAP store for dashboards, and lakehouse tables as the source of truth for analysts and backfills.
4. Kafka design
- Partitions: if one partition comfortably handles about 10 MB/s, 500 MB/s peak needs roughly 50 partitions. I would pick 64 to 128 for headroom, because adding partitions later changes key-to-partition mapping.
- Key:
user_idoranonymous_id. It preserves per-user ordering, which dedup and sessionization benefit from. Keying by page would create hot partitions for viral pages. - Hot dimensions are handled inside Flink with two-stage aggregation: pre-aggregate on a salted key, then merge partials.
- Durability: producers use
acks=alland idempotence; topics use RF=3 andmin.insync.replicas=2. - Retention: 7 days is enough for replay after incidents; the lake holds longer history.
5. Flink processing
Event time with watermarks. Mobile clients buffer and send late, so processing time would give wrong windows. Use bounded out-of-orderness of 30 to 60 s plus idle-partition detection so a quiet partition does not stall the watermark.
Windows by purpose:
- 1-minute tumbling for core metrics,
- sliding (10 min, every 1 min) for trending,
- session windows with a 30-minute gap for sessions.
Use incremental AggregateFunctions so state is one accumulator per key per window rather than buffered events.
Late data. Allow lateness of 1 hour. A late event re-fires the window with an updated value, and the sink upserts it. Anything later goes to a side output and into the lake; a nightly batch job corrects the aggregates.
6. State
- RocksDB backend with incremental checkpoints to object storage every 30 to 60 s. Unaligned checkpoints help checkpoints finish under back-pressure.
- Dedup state keyed by
event_idwith a TTL of 1 to 2 hours (the realistic retry window). At 50k/s that is hundreds of millions of keys, which RocksDB can hold. If cost is a concern, accept approximate dedup for non-financial metrics. - Unique users as HyperLogLog sketches. They merge correctly from minutes to hours to days; summing per-minute distinct counts would overcount.
- Assign stable operator
uids and a generousmaxParallelismso savepoints survive code changes and rescaling.
7. End-to-end correctness
Exactly-once is a property of the whole chain:
- Ingest is at-least-once, so duplicates exist; Flink dedup by
event_idremoves them. - Inside Flink, offsets and state are checkpointed together, so recovery replays consistently.
- The sink must tolerate replay:
- Kafka sink: transactional two-phase commit tied to checkpoints, consumers use
read_committed. Visible latency is bounded below by the checkpoint interval. - Lakehouse sink: atomic file commits on checkpoint completion.
- OLAP store: idempotent upsert keyed by
(window_start, dimensions), so a replayed or late firing overwrites rather than adds.
- Kafka sink: transactional two-phase commit tied to checkpoints, consumers use
8. Table modeling
- Raw/clean events (lake): partitioned by event date, one row per
event_id, the replayable source of truth. - Aggregate tables: grain
(window_start, page_id, country, device, campaign)with additive measures (views, clicks) and a sketch column for uniques. Primary key is the grain, enabling upserts. - Sessions table: one row per session with start, end, page count and conversion flag.
- Rollups (hour, day) are derived from the minute table by merging sketches.
- Expose stable views to consumers so physical changes do not break dashboards. Evolve schemas additively, and version breaking changes as new tables.
9. Back-pressure
Flink's credit-based flow control slows the source, and Kafka absorbs the surplus as consumer lag instead of data loss. Watch lag in seconds, backPressuredTimeMsPerSecond and busyTimeMsPerSecond per operator, and checkpoint duration and size. Then fix the bottleneck:
- Slow sink: batch writes, raise sink parallelism.
- Slow enrichment: async I/O with a local cache.
- Skew: salted keys.
- Sustained growth: autoscale, or rescale from a savepoint.
After an outage, throttle catch-up so the OLAP store is not flooded. Run heavy jobs (sessionization) separately from the critical aggregate job.
10. Failure handling
- Bad records go to a DLQ with error metadata; never crash the job on one record. Alert on DLQ rate.
- Job failures: exponential-backoff restarts, tolerate a few failed checkpoints, HA job manager.
- Reprocessing: for bugs, replay from Kafka (within retention) or from the lake into a new output version, then swap consumers over.
- Reconciliation: compare streaming totals against a batch recomputation from the lake daily and alert if drift exceeds a threshold (say 0.1%).
11. Validation and monitoring
- Event-to-visible latency (p50/p99) against the SLO.
- Freshness per table, lag, checkpoint health, DLQ rate.
- Replay tests: kill the job mid-stream and confirm output equals an uninterrupted run.
- Synthetic canary events with known counts.
Common mistakes
- Claiming "Kafka gives exactly-once" without addressing sinks and dedup.
- Using processing time, or no allowed lateness.
- Keying by a skewed dimension.
- Summing distinct counts across windows.
- Buffering raw events in window state instead of aggregating incrementally.
- Failing the whole job on a malformed record.
- No reconciliation path, so silent drift goes unnoticed.
Trade-offs to mention
Shorter checkpoint intervals lower recovery time but add overhead and raise sink commit latency. Longer lateness improves accuracy but delays final values and grows state. Approximate structures (HLL, Bloom filters) save memory at the cost of small, bounded error.