System DesignSep 21, 2026⏱️ 3 min read
Design an Ad Click Event Aggregation Pipeline: Tumbling Windows, Watermarks & Exactly-Once

Design an Ad Click Event Aggregation Pipeline: Tumbling Windows, Watermarks & Exactly-Once

Counting Clicks Accurately When Real Money Is on the Line

Online advertising (Google Ads, Meta Ads) settles billions of dollars via Real-Time Bidding (RTB) and pay-per-click billing. At 1 billion+ ad clicks per day (~11,500 QPS average, 50K+ QPS peak), advertisers expect real-time dashboards within 1 minute while finance demands 100% auditable billing accuracy—no double-counting or dropped events.
Ad Click Aggregation Stream Architecture

Ad Click Aggregation Stream Architecture


1. Why Simple Stream Counters Fail

Suppose a mobile device clicks an ad inside a subway tunnel and reconnects 3 minutes later:
  • 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

  1. Log Collector + Raw Kafka (ad_clicks_raw):
    • Captures click events (ad_id, click_id, user_id, ip, ts) immediately with minimal edge validation.
  2. Stream Aggregation Engine (Apache Flink):
    • Partitioned by ad_id across Flink operators using local RocksDB state backends + periodic Chandy-Lamport distributed snapshots to S3 for crash recovery.
    • Fraud & Deduplication Node: Filters duplicate click_id retries or bot-farm bursts before aggregating.
    • Tumbling Window Aggregator: Sums clicks per ad_id in fixed 1-minute non-overlapping windows and emits totals downstream.
  3. 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.

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 0 and swap the dashboard view!
  • Hotspot Mitigation: A viral Super Bowl ad generates massive load on one ad_id shard. Append a random sub-shard suffix (ad_id#0..9) for partial local sums, then combine those 10 partial counters downstream!

Share this article

Comments