Design an Ad Click Event Aggregation Pipeline: Tumbling Windows, Watermarks & Exactly-Once
Counting Clicks Accurately When Real Money Is on the Line
Ad Click Aggregation Stream Architecture
1. Why Simple Stream Counters Fail
- Processing Time counts the click in the current 3-minute-late window, skewing campaign hourly metrics and billing spikes.
- Event Time assigns the click to the exact window when the user tapped the screen—requiring Watermarks to tolerate out-of-order late arrivals without waiting forever!
Event Timeline: [Window 12:00 - 12:01] ◄── Watermark allows 15s grace
Late Mobile Ping: click_ts = 12:00:52 arrives at 12:01:10 ──► Accepted into 12:00 window!
Very Late Event: click_ts = 12:00:10 arrives at 12:05:00 ──► Routed to Side Output / Batch Reconcile
2. Core Pipeline Architecture (Kafka → Flink → OLAP DB)
- Log Collector + Raw Kafka (
ad_clicks_raw):- Captures click events
(ad_id, click_id, user_id, ip, ts)immediately with minimal edge validation.
- Captures click events
- Stream Aggregation Engine (Apache Flink):
- Partitioned by
ad_idacross Flink operators using local RocksDB state backends + periodic Chandy-Lamport distributed snapshots to S3 for crash recovery. - Fraud & Deduplication Node: Filters duplicate
click_idretries or bot-farm bursts before aggregating. - Tumbling Window Aggregator: Sums clicks per
ad_idin fixed 1-minute non-overlapping windows and emits totals downstream.
- Partitioned by
- Aggregated Kafka → OLAP Storage (ClickHouse / Cassandra / Druid):
- Stores pre-aggregated per-minute ad counts for instant advertiser queries (
SUM(clicks)over last 24 hours) and Top-100 most clicked ads via min-heaps.
- Stores pre-aggregated per-minute ad counts for instant advertiser queries (
3. Guaranteeing End-to-End Correctness: Kappa vs. Lambda
- Lambda Architecture: Runs both a fast Flink stream layer (minute-level dashboards) and a daily batch Spark reconciliation job over raw S3 Parquet logs to catch rare very-late arrivals or bugs, overwriting final billing tables nightly.
- Kappa Architecture: Uses Kafka as the immutable source of truth; if aggregation logic changes, spin up a second Flink job replaying raw Kafka history from offset
0and swap the dashboard view! - Hotspot Mitigation: A viral Super Bowl ad generates massive load on one
ad_idshard. Append a random sub-shard suffix (ad_id#0..9) for partial local sums, then combine those 10 partial counters downstream!