Skip to content

Lesson 36 of 38Case studies

Design Ad Click Aggregation

Count billions of ad clicks per minute with Kafka and Flink: event-time windows, watermarks, exactly-once billing, hot-ad salting, and nightly reconciliation.

22 min read0/5 questions

An advertiser pays you every time someone clicks their ad. Count a click twice and you overcharge them, which is a contract problem. Miss a click and you lose revenue. Show the numbers ten minutes late and their campaign dashboard looks broken, and they cannot pause a bad ad while it burns budget. Ad click aggregation is the textbook case of a stream processing system where money depends on the answer, which is why it comes up so often in senior interviews at companies with ads, marketplaces, or any usage-based billing.

Requirements

Functional

  • Record every click on an ad and redirect the user to the advertiser's page.
  • Count clicks per ad per minute, with filters such as country and device.
  • Advertisers query their counts in near real time: "clicks on my ads in the last hour, by minute".
  • Show the top 100 ads per minute for internal monitoring.

Non-functional

  • 1 billion clicks a day, with spikes during big events.
  • Counts visible within about a minute of the click.
  • Accurate enough to bill. No double counting, no silent loss, and an audit trail that explains every number on an invoice.
  • Fraudulent clicks (bots, click farms) must not be billed.

Out of scope: ad serving and auctions, conversion tracking after the click, and payments themselves (Design a Payment System covers ledgers).

Back-of-the-envelope numbers

QuantityMathResult
Average click rate1B / 86,400about 11,600/s
Peak click rate5x averageabout 60,000/s
Raw event sizeids, timestamps, IP, user agent, countryabout 300 bytes
Raw data per day1B × 300 Babout 300 GB/day
Aggregated rows per day2M active ads × 1,440 minutes, upper boundat most 2.9 billion, in practice far fewer

60,000 events a second is comfortable for a Kafka cluster and a modest Flink job. Throughput is not the hard part. The hard parts are correctness (each click counted exactly once, even through crashes and retries) and skew (one viral ad getting a large share of all clicks).

The click flow

When the ad server shows an ad, it creates an impression ID and builds the click URL with the impression ID, the ad ID, and an HMAC signature over both:

https://click.ads.example/c?imp=8f3a91&ad=ad_4471&sig=Zk2...&dest=https%3A%2F%2Fshop.example

The user clicks. The click redirect service checks the signature (so nobody can forge clicks for ads they never saw), writes a click event to Kafka, and returns a 302 to the advertiser's page. Writing to Kafka is a fast append, so the user never waits on aggregation, the same trick the URL Shortener lesson used for analytics.

The click event carries a click ID derived from the impression ID. Our billing rule is one billable click per impression, so if the user double-clicks or the browser retries, both events share a click ID and the second one is dropped later. The ID is created at the edge because only the edge knows which events are really the same click.

The topic is partitioned by ad ID, so all clicks for one ad land on one partition, in order, and the aggregator that owns that partition can count them without coordination.

High-level design

Ad click aggregation pipeline
Speed layer (seconds)Batch layer (daily)UserUserClick redirect: verify sig, 302Click redirectverify sig, 302Kafka: clicks: by ad_idKafka: clicksby ad_idFlink job: dedupe, windowFlink jobdedupe, windowOLAP store: ClickHouse / PinotOLAP storeClickHouse / PinotQuery APIQuery APIAdvertiserAdvertiserRaw archive: object storeRaw archiveobject storeNightly batch: SparkNightly batchSparkBilling: reconciledBillingreconciledclickappendupsert per minutesinkfinal countscorrections

The redirect service verifies the signed click URL, appends one event to Kafka, and redirects. The user waits only for this.

1/6

Deep dive 1: windows, watermarks, and late clicks

"Clicks per minute" sounds simple until you ask: which minute? A click happens on a phone at 12:00:58, the phone is in a tunnel, and the event reaches Kafka at 12:01:20. You want to count it by event time (when it happened, 12:00), not processing time (when you saw it), or advertisers see numbers shift with network conditions.

Flink groups events into tumbling windows: fixed, non-overlapping 1-minute buckets keyed by ad ID. The problem is knowing when a window is finished, since a late click could always still arrive. Flink's answer is a watermark: a running claim that "no events older than time T are still coming". A common strategy is bounded out-of-orderness: the watermark trails the newest event time seen by a fixed delay, say 10 seconds. When the watermark passes the end of a window, the window fires and emits its count.

Events that arrive after their window fired are late. You choose what to do with them. Flink can keep a window open for extra allowed lateness and emit an updated count, or route late events to a side output for the batch layer to pick up. That is the core trade-off: a longer delay means more complete counts but slower dashboards. Run this simulation of the logic.

Pythonwindows.py
from collections import defaultdict WINDOW = 60 # tumbling 1-minute windowsMAX_DELAY = 10 # watermark trails the newest event time by 10 s # (arrival order) click_id, ad_id, event_time in secondsevents = [ ("c1", "ad7", 5), ("c2", "ad7", 30), ("c3", "ad9", 58), ("c4", "ad7", 66), ("c2", "ad7", 30), # c2 again: a retry ("c5", "ad9", 55), # late but within the delay ("c6", "ad7", 75), ("c7", "ad9", 59), # c7 arrives after window 0 closed] counts = defaultdict(int) # (window_start, ad_id) -> clicksseen = set() # click ids already countedwatermark = -1closed = set() for click_id, ad, t in events: start = t - t % WINDOW if start in closed: print(f"late {click_id} t={t:>3} -> side output") continue if click_id in seen: print(f"dup {click_id} dropped") continue seen.add(click_id) counts[(start, ad)] += 1 watermark = max(watermark, t - MAX_DELAY) for (s, a) in sorted(counts): if s + WINDOW <= watermark and s not in closed: closed.add(s) for (s2, a2), c in sorted(counts.items()): if s2 == s: print(f"EMIT window {s}-{s + WINDOW}s {a2}: {c}") print("open windows:", {k: v for k, v in counts.items() if k[0] not in closed})
Output
Press Run (⌘ Enter) to see what happens.

Click c5 arrived out of order but within the 10-second delay, so it still counted. Click c7 arrived after event time 75 pushed the watermark to 65, past the end of window 0, so it went to the side output. In production the side output feeds the raw archive, and the nightly batch counts it.

Predict the outputPython

What does this print?

WINDOW, DELAY = 60, 10
watermark, closed, counted = -1, False, 0
for t in [12, 50, 71, 58, 80]:
  if t < WINDOW:
      if closed:
          continue        # late for window 0: dropped
      counted += 1
  watermark = max(watermark, t - DELAY)
  if watermark >= WINDOW:
      closed = True
print(counted)
Need a nudge? Hints walk you through it.
Quick check
Kafka has 64 partitions. One partition receives no clicks for 20 minutes because the ads routed to it are paused. What happens to the minute windows on the other partitions?
Need a nudge? A hint rules out a wrong answer.

Deep dive 2: exactly-once, for money

"Exactly once" in streaming really means effectively once: events may be processed more than once after a crash, but the effects (the counts written out) reflect each event once. You need three pieces, and missing any one breaks billing.

1. Deduplicate at the source of truth. Retries happen everywhere: the browser, the redirect service's Kafka producer, network glitches. Flink keys the stream by click ID and keeps a "seen" flag in its state for each click ID, with a TTL a bit longer than any retry could take (say 24 hours). A Kafka idempotent producer also stops broker-level duplicates from producer retries.

2. Checkpoint state and input position together. Flink periodically injects checkpoint barriers into the stream. When an operator sees a barrier, it snapshots its state (open window counts, the dedupe set) to durable storage. A completed checkpoint records the Kafka offsets and every operator's state at one consistent point. After a crash, Flink restores the last checkpoint and rewinds Kafka to those offsets. Events after the checkpoint are processed again, but their effect on state was rolled back, so nothing counts twice inside Flink.

3. Make the output safe to repeat. Replayed events will produce the same window results again, so the sink must handle that. Two options:

  • Idempotent upsert. Write each result keyed by (ad_id, window_start, country). Writing the same row twice leaves the same value. This is the simplest choice and works with most OLAP stores.
  • Transactional sink. Flink's two-phase commit writes results inside a transaction (for example a Kafka transaction) and commits only when the checkpoint completes. Downstream consumers read with read_committed, so they never see output from a failed attempt. Correct, but output is only visible once per checkpoint interval.
Put it in order5 steps

A Flink task manager crashes mid-minute. Order the recovery.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Why keep a batch layer anyway? Even a perfect streaming job has bugs, schema mistakes, and late data beyond the watermark. For billing you want a second, independent computation. Every raw click is archived to object storage (often as an Iceberg table), and a nightly Spark job recomputes per-ad totals for the day from scratch. Billing uses the batch number. Dashboards use the stream. A reconciliation job compares the two and alerts if they differ by more than a tiny threshold.

This is the Lambda architecture, and here you choose it on purpose. Its known cost is maintaining two code paths for the same logic. The alternative, Kappa, keeps only the stream and recomputes by replaying Kafka from the start with a fixed job. Kappa is simpler but needs very long Kafka retention and does not give you an independent check. When the output is an invoice, the independent check is worth the duplication. Say that trade-off out loud in an interview.

Deep dive 3: hot ads and skew

Partitioning by ad ID is great until a Super Bowl ad gets 30% of all clicks. Its key lives on one Flink subtask, which falls behind while the rest sit idle, and the whole job's watermark (the minimum, remember) waits for it.

The fix is two-stage aggregation with key salting:

  1. Stage 1: key by (ad_id, salt), where the salt is one of N values. Each salted key counts its share of the window on a different subtask.
  2. Stage 2: key by ad_id alone and sum the N partial counts. Stage 2 sees only N small records per window per ad, so it is cheap.

Use a deterministic salt such as hash(click_id) % N rather than a random number. A random salt gives a different split on every replay, which makes debugging harder. Deduplication must happen before salting, or two copies of one click could land in different salted buckets and both count.

Pythonsalting.py
import zlibfrom collections import Counter SALTS = 8clicks = [("ad_hot", f"c{i}") for i in range(10_000)] + [("ad_small", f"s{i}") for i in range(40)] stage1 = Counter()for ad, click_id in clicks: salt = zlib.crc32(click_id.encode()) % SALTS if ad == "ad_hot" else 0 stage1[(ad, salt)] += 1print("stage 1 keys:", len(stage1), " biggest:", max(stage1.values())) stage2 = Counter()for (ad, _), n in stage1.items(): stage2[ad] += nprint("stage 2:", dict(stage2))
Output
Press Run (⌘ Enter) to see what happens.

The hot ad's 10,000 clicks are spread over 8 subtasks of about 1,250 each, and stage 2 gets the exact total back. Salt only keys you know are hot (from a list refreshed every few minutes) so small ads skip the extra hop. Flink SQL can apply a similar local-then-global aggregation for you; check the current Flink docs for the optimizer setting.

Quick check
You salt every ad into 16 buckets but dedupe by click ID after stage 1. A user's browser retries a click. What can go wrong?
Need a nudge? A hint rules out a wrong answer.

Fraud filtering

Advertisers do not pay for bots. The industry calls bad clicks invalid traffic, split into general invalid traffic (known crawlers, data-center IPs, obvious automation) and sophisticated invalid traffic (click farms, malware, hijacked devices). Your pipeline handles them in two speeds:

  • Inline, before counting: reject bad signatures, known bot user agents, and data-center IP ranges, and apply per-IP and per-device rate limits (50 clicks a minute from one IP is not a person). Flag clicks that happen impossibly fast after the impression.
  • Offline, before billing: heavier models look at patterns across hours and accounts. Their verdicts flow into the nightly batch, which subtracts invalid clicks from the billed total. This is another reason the invoice comes from batch, not from the stream.

Keep filtered clicks in the raw archive with a reason code. When an advertiser disputes an invoice, you must be able to show exactly which clicks were removed and why.

Querying: OLAP and rollups

Aggregated rows go into a column-oriented OLAP store such as ClickHouse, Apache Druid, or Apache Pinot. These stores scan only the columns a query needs, compress them heavily, and are built for GROUP BY over time ranges. Sort the data by (advertiser_id, ad_id, minute) so one advertiser's query reads a narrow slice.

Store pre-aggregated rollups as well: per minute for the last few days, per hour for months, per day for years. A "last 90 days by day" chart then reads 90 rows per ad, not 130,000. ClickHouse can maintain rollups with materialized views into a summing table engine, and Druid and Pinot can roll up at ingest.

For the top 100 ads per minute, let Flink compute it once per window (a keyed count, then a top-N per window) and write it to a small table. One precomputed list read by everyone is far cheaper than sorting millions of rows on every dashboard refresh, the same idea as the cached top 100 in the Leaderboard lesson.

Match the pairs0/5 matched

Match each requirement to the mechanism that provides it.

Choose an item, then its match on the other side.

Bottlenecks, failures, and 10x scale

  • Redirect service down. Users cannot reach advertisers, which is the worst outage here. Keep it stateless, run it in many regions, and if Kafka is unreachable, write events to local disk and ship them later rather than failing the redirect.
  • Kafka backlog. If Flink falls behind, dashboards lag but nothing is lost, because Kafka retains days of data. Alert on consumer lag in minutes, not messages.
  • Dedupe state growth. A billion click IDs a day in state is large. Use a state backend that spills to local disk (RocksDB in Flink), and expire IDs with a TTL.
  • Schema changes. Use a schema registry so a new field in the click event cannot break the job mid-stream.
  • 10x (10 billion clicks a day): add Kafka partitions and Flink parallelism, and the design holds because work is keyed by ad. Salting becomes routine rather than an exception, and pre-aggregation at the redirect tier (counting in memory for a few seconds before emitting) cuts event volume. The batch layer scales by adding cluster capacity.
Key terms
event time
When the click actually happened, as opposed to processing time, when the pipeline saw it.
tumbling window
Fixed-size, non-overlapping time buckets, such as one per minute, keyed by ad.
watermark
A running claim that no events older than time T are still coming; when it passes a window's end, the window fires.
checkpoint barrier
A marker Flink injects into the stream so every operator snapshots state at one consistent point, together with the input offsets.
idempotent sink
An output that can receive the same result twice without changing the final value, such as an upsert by key.
key salting
Splitting a hot key into N sub-keys for a first aggregation, then summing the partial results by the real key.
Lambda architecture
A fast streaming layer plus a slower batch layer over the same raw data, with batch as the source of truth.