All posts
System Design Mastermind · Part 30
  • System design
  • Interview prep
  • Stream processing
  • Exactly-once
  • Platform

Ad click aggregator system design: exactly-once counts, late clicks and hot ads

How to design an ad click aggregator (Google Ads, Meta, Uber Ads) in real interview order: the dollar cost of a counting error and rows per minute as the numbers that matter, a signed click URL and a redirect that waits on one log append, a click service, Kafka log, Flink aggregator, fraud filter, OLAP store, budget counter and nightly recount built in passes, one click walked from the tap to the bill, an explainer from raw clicks to billable ones, a lab on where duplicates come from and which fix catches which, a lab on watermarks, allowed lateness and budget pacing, a lab on hot ads and salted keys, and what happens when each part fails.

26 Oct 2026 · 32 min read · interactive

Share

The 1-minute answer

The ad server gives every ad a click URL with a signed token (impression id, ad, time, HMAC). A tap hits a stateless click service that checks the signature, uses the impression id as the click id, appends one event to Kafka keyed by ad id and answers with a 302 redirect; nothing else is in the user's path. A Flink aggregator drops click ids it has already seen, gets a fraud verdict, and counts clicks per ad in one-minute event-time windows; when the watermark passes, it upserts one row per (ad, minute) into an OLAP store that dashboards query, with hour and day roll-ups for long ranges. Late clicks within the allowed lateness update the row. A per-click spend counter lets the ad server stop a campaign at its daily cap within seconds. Raw clicks also land in a data lake, and a nightly recount with final fraud verdicts overwrites the streaming numbers; billing reads only the recount. The hard parts: counting each click exactly once (client duplicates, retries, restarts), late clicks versus fresh numbers and budgets, and hot ads that make one task the bottleneck.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

Watermarks and batch vs stream in general are in Foundations F17 (data pipelines); exactly-once across services in F11; the log itself in Part 27 (Kafka). This page puts them together for one problem where the counts are money.

Requirements and numbers

Agree what's promised, then size it. For ad clicks, the dollar value of one wrong click decides how hard you work for exactness; distinct ads per minute decide the storage. Change any input: each number comes with the decision it forces.

Functional

  • A tap redirects to the advertiser's page
  • Every click is recorded once
  • Advertisers see clicks per ad per minute
  • Query by campaign, hour, day, ranges
  • Feed budget pacing and billing

Non-functional

  • Redirect p99 well under 100 ms
  • No click lost, none counted twice
  • Dashboard within ~2 minutes
  • Budgets enforced within seconds
  • Billing exact, from a recount

Out of scope (say it)

Choosing which ad to show, conversion attribution, impression counting in depth, fraud models' internals.

Capacity calculator

Every input is an assumption 🔶: say it out loud. Anchors: Uber's ads pipeline handles "hundreds of millions of ad events per week" with 1-minute windows ✅ Uber 2021; Twitter's streams handle ~400 billion events a day ✅ Twitter 2021; Google's Photon joined "millions of events per minute" at peak ✅ Photon 2013. A billion clicks a day and 10 M ads are a common interview scale (third party), not any company's figure.

Three rules for this estimate
  1. A day is 86,400 seconds; size the click path for the peak, storage for the day.
  2. Rows aren't clicks: n clicks over G ads make G(1 − e^(−n/G)) distinct rows, so roll-ups pay only when ads repeat.
  3. Price the error: clicks × cost per click × error rate is what a bug costs per day.
They'll push on thisAnswer out loud, then open.

Core entities and the API

Three calls matter: the click redirect, the event the click service writes, and the advertiser's query. What they listen for: the click id is fixed before the click, the redirect waits on nothing but one log append, and today's numbers are marked provisional.

EntityKey fieldsNote
Request
Response

From raw clicks to the bill

The number an advertiser pays for is not the number of requests that hit the click service. Change the inputs and watch each step remove something.

Why it works this way

  • Duplicates share a click id, because the id is the impression id signed before the click. 🧭
  • Invalid clicks are removed from metrics and billing: "You won't be charged for invalid clicks or impressions." ✅ Google Ads help
  • Found after billing? Google credits them on the next invoice. ✅ Google Ads help
  • Budgets cap the bill: a campaign may spend up to 2× its average daily budget on a day, never more than 30.4× in a month. ✅ Google Ads help

The duplicate and invalid percentages are teaching values; platforms don't publish theirs. ❓

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.

They'll push on thisAnswer out loud, then open.

Walk one click, box by box

A reader taps a shoe ad on a news site. Follow the click from the signed URL to the advertiser's landing page, into a minute row, the budget counter and the dashboard, then a late click, then the nightly recount that the bill comes from. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. The aggregator pulls from the log (it isn't pushed to), and the ad server reads the budget counter. Replies, like the 302, go back along the same line.

What the click service does before the redirect

Everything here runs on the user's path, so it must be cheap. Six steps, one network call:

    Data and storage choices

    Raw clicks are the source of truth; everything else is a count you can rebuild from them. Dashboards read pre-aggregated rows, pacing reads a counter, billing reads the recount.

    DataPickConsideredWhy not those

    The one pipeline to know

    # The aggregator, per click. Illustrative, Flink-style.
    clicks
      .key_by(click_id)                 # dedupe: one place per id
      .filter(lambda c: not seen(c))    # keyed state, TTL 1 h
      .map(attach_fraud_verdict)        # inline rules; model later
      .key_by(ad_id)                    # salted for hot ads
      .window(tumbling(minutes=1),      # event time
              watermark=max_ts - 10s,
              allowed_lateness=1h)      # late → updated row
      .aggregate(count, valid, spend)
      .sink(upsert(table="ad_minute",
                   key=(ad_id, minute)))  # replays overwrite
    
    # Very late clicks → side output → nightly recount.
    # Checkpoint every 1–2 min: offsets + seen ids + windows.

    Illustrative. The order is the point: dedupe by click id before keying by ad, event-time windows, and a sink that overwrites. 🧭

    What the big pipelines do

    1. Uber: 1-minute tumbling windows keyed by ad, Kafka transactions committed on Flink checkpoints every 2 minutes, a record UUID as the idempotency key, Pinot upserts. ✅ Uber 2021
    2. Twitter: a UUID per event, best-effort dedupe in a time window in Dataflow, latency up to ~10 s, >95% exact match with batch. ✅ Twitter 2021
    3. Google Photon: each click id committed once in a Paxos-replicated registry across 5 datacenters; ids kept N days. ✅ Photon 2013
    4. Google Mesa: ads metrics loaded in versioned batches every few minutes; most queries in tens to hundreds of ms. ✅ Mesa 2014

    More storage questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: counting every click exactly once

    Duplicates come from three places: the client sends the same click twice, the job replays after a crash, and a probabilistic filter wrongly calls a new click "seen". Each needs a different fix. Pick a preset, then change one setting at a time.

    The rules this lab teaches

    1. Client copies are new events to Kafka; only dedupe by click id removes them. A second copy gets through if it arrives after its id expired: e^(−window ÷ mean delay). 🧭
    2. Replays need an idempotent or transactional sink: the dedupe state is restored from the checkpoint too, so replayed clicks look new. ✅ Flink 2018
    3. A Bloom filter drops real clicks: false positives = e^(−bits × (ln 2)²), 0.8% at 10 bits per id. ✅ Redis docs
    4. State = ids per second × window × bytes per id; past memory, shorten the window and let the nightly recount dedupe the day. 🧭

    Numbers to quote

    Uber checkpoints every 2 minutes (the default it mentions is 10), and output is committed only at the next checkpoint: "The main bottleneck for time is the Flink checkpoint interval." ✅ Uber 2021

    Photon: fewer than 5% of events were processed by both datacenters' joiners, and the id registry still emitted each once. ✅ Photon 2013

    Redis: 1% false positives need 9.585 bits per item; 0.01% need 19.17. ✅ Redis docs

    They'll push on thisAnswer out loud, then open.

    Deep dive: late clicks, fresh numbers and budgets

    Each click belongs to the minute it happened (event time), but some arrive late. The watermark delay decides how many make the first result, allowed lateness decides how many can still correct it, and the budget counter must not wait for either. Pick a preset, then change the inputs.

    Where each click is counted
    first result correction (late firing) past lateness → batch

    Delays are a mix of two exponentials, clicks spread evenly within a window, and a click is in a window's result if it arrives before end + watermark delay (+ lateness for corrections). The bar is drawn to scale, so small slices can be thin: read the numbers. 🔶

    The rules this lab teaches

    1. Allowed lateness is 0 by default in Flink; later elements are dropped unless you set it or use a side output. ✅ Flink docs
    2. Late firings are updated results of a window already emitted, so the sink must replace, not add. ✅ Flink docs
    3. State lives until end + lateness: open windows per key = ⌈(W + D + L) ÷ W⌉. ✅ Flink docs
    4. Pace from a per-click counter: overspend ≈ spend per minute × how late the counter is. 🧭

    Numbers to quote

    Twitter's batch pipelines discarded late events; most of the <5% gap between its new streaming counts and batch was late events the stream now captures. ✅ Twitter 2021

    Photon's target: join 99.9999% of events within a few seconds and 100% within a few hours; 90% were joined in under 7 s. ✅ Photon 2013

    Google Ads lets a campaign spend up to 2× its average daily budget on a day: overspend is a business rule, but it must still be bounded. ✅ Google Ads help

    They'll push on thisAnswer out loud, then open.

    Deep dive: hot ads and the shuffle

    Keying by ad id keeps an ad's clicks together, which is what counting needs, until one ad is a large share of all clicks and its task can't keep up. Then its lag holds back the watermark and every ad's numbers are late. Pick a preset, then change the inputs.

    What to build

    1. Dedupe first, keyed by click id: click ids spread evenly, so dedupe never has a hot key. 🧭
    2. Salt only hot ads: key (ad, 0…N−1), count each slice, then sum N rows per minute in a second stage. 🧭
    3. Find hot ads from rates every minute rather than by hand before a big event. 🧭
    4. Enough partitions up front: tasks can't outnumber Kafka partitions usefully, and adding partitions moves keys. 🔶

    The arithmetic

    Hottest task = hot share × peak ÷ min(sub-keys, tasks) + rest × peak ÷ tasks. 🧭

    Lag built in a spike = (hottest − capacity) × spike seconds; it drains at capacity − normal load. 🧭

    Salting viral ads with a suffix and stripping it when writing is the standard interview answer. ✅ Hello Interview (third party)

    They'll push on thisAnswer out loud, then open.

    A click's lifecycle

    A click is logged, counted, made final by the watermark, billed after the recount, or found invalid at any point. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

    NormalSomething went wrongGreyed out: not possible from the current state.

    States are named for teaching; a real pipeline tracks them as counts on rows (clicks, valid, invalid, final), not per click. 🔶

    Edge cases interviewers love

    They'll push on thisAnswer out loud, then open.

    Failure, monitoring and recovery

    The one failure users feel is the redirect. Everything after the log can be slow or wrong for a while and fixed by replaying from the log or recounting from the lake, as long as outputs overwrite. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

    Tracing it back: a normal click vs a restart

    Time from the tap to the minute row on the dashboard. In the second trace the aggregator crashes right after reading the click and restores from its checkpoint.

    How one failure becomes three

    What you'd alert on (SLOs)

    SignalTargetAlert

    Incident playbook

      The toolkit

      Name the technique, then say where it goes in this design.

      They'll push on thisAnswer out loud, then open.

      Making it fast, and who owns what

      The user's path is milliseconds; the counts are seconds to minutes, and the bill is hours, on purpose. Bars are sizing estimates, not measured figures.

      TeamOwnsPaged when…

      Senior follow-ups beyond the happy path

      Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

      Practice ladder

      Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

      Sources

      Checked October 2026. Company designs are as published: Uber's exactly-once ad event pipeline (Sep 2021), Twitter's move from lambda to streaming (2021), Google's Photon (SIGMOD 2013) and Mesa (VLDB 2014) papers. Mechanisms come from Apache Flink's windows docs (allowed lateness, late firings, side outputs) and its Feb 2018 exactly-once post, Apache Druid's rollup docs and Redis's BF.RESERVE docs (Bloom filter sizing). Product behaviour (invalid clicks, parallel tracking, overdelivery) comes from Google Ads Help pages. No platform publishes its duplicate or invalid-click rates, so the labs use rounded teaching values and say so. Hello Interview is a third-party prep site, used only to cross-check what interviewers expect.

      System Design Mastermind · Platform & Infra

      Series home

      All of Platform & Infra

      5 published · 7 comingWhat Senior platform loops lean on.

      19

      Distributed job scheduler system design: on time, at least once, never lost

      Jobs in a sharded store with a precomputed next_run_at → one scheduler per shard (lease + fencing token) claims due jobs every second: insert run (unique job_id + time) and advance next_run_at in one transaction → durable queue with deliver-at, enqueued a little early → workers lease runs, heartbeat, call the target with the run id as idempotency key → backoff, then a DLQ. At-least-once, made safe by idempotency.

      32 min · interactive Preview
      24

      Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trust

      Agents add up metrics for 10 s and batch them with logs → intake checks key and quotas, appends to a durable log, then 202 → writers map tags to series ids in an inverted index and store compressed points with roll-ups → logs: index a slice, archive all → monitors evaluate a window that ends in the past, and the whole stack is watched from outside.

      32 min · interactive Preview
      27

      Kafka system design: a distributed log that never loses an acknowledged message

      Topics split into partitions; the producer hashes the key, batches and sends to the partition leader → the leader appends to the page cache, followers in other zones pull, acks=all waits for every in-sync copy (RF 3, min ISR 2) → consumer groups pull from offsets and commit them → KRaft controllers move leaders; tiered storage keeps history.

      33 min · interactive Preview
      30

      Ad click aggregator system design: exactly-once counts, late clicks and hot ads

      Signed click URL → click service appends to Kafka and 302s → Flink dedupes by click id, counts per ad in 1-minute event-time windows, upserts (ad, minute) rows into an OLAP store → a per-click counter paces budgets → a nightly recount from raw clicks is what billing reads.

      You're reading this Preview
      33

      Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

      Card → vault → token; confirm with an Idempotency-Key → attempt row written before the bank call → gateway with timeouts and breakers → result + outbox in one commit → event log → append-only double-entry ledger and signed webhooks → a timeout is 'unknown', resolved by status check and the next day's settlement file → payouts from balances.

      33 min · interactive Preview
      ··

      Web crawler

      Coming next
      ··

      File sync (Dropbox)

      Coming next

      More posts