Design: ad click aggregator

In one sentence

Log clicks to Kafka, drop duplicates by click id, count per ad per minute by event time with exactly-once output into an OLAP store, and reconcile against a batch recount of the raw log.

The stream path gives per-minute counts within about a minute; the batch path recounts the raw log, late clicks included, and overwrites the same rows.

How it works

  • The click path only appends to Kafka and redirects; all counting is asynchronous.
  • Drop duplicates by click id, then count per ad per minute in event-time windows.
  • Checkpoints plus a transactional or upsert sink keep counts exactly-once across restarts.
  • Late clicks miss their window; a batch recount of the raw log corrects the totals.
  • Dashboards read fresh stream counts; invoices read reconciled ones.

Check yourself

Answer to mark it learned; your answers aren't scored.

After every restart of the Flink job, advertisers see roughly double counts for the last minutes before the crash. Dedupe by click_id works. The sink runs UPDATE … SET clicks = clicks + n when a window closes. What do you fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: record every ad click; show advertisers clicks per ad per minute, sliced by campaign or country, and the top ads; feed billing. Non-functional: no click lost or counted twice; dashboards about a minute behind; queries under a second; the click redirect never waits on analytics.

Scale (assumed): 1B clicks/day ≈ 11.6k/s average, ~58k/s at a 5× peak; ~0.5 KB per event ≈ 500 GB/day of raw log.

Questions I'd ask:

  1. How fresh and how exact? A dashboard tolerates a small error for a minute; an invoice doesn't.
  2. Which dimensions do queries filter and group by?
  3. How late can a click arrive (offline mobile SDKs)?

API and data model

Event: {click_id, ad_id, user_id, ts, country}. The click_id is minted when the ad is served, so a retried click carries the same id. Aggregate row: (ad_id, minute, country) → clicks. Query: GET /ads/{id}/clicks?from&to&granularity.

Architecture

  1. Click service: appends the event to Kafka and redirects the user (Design: distributed message queue).
  2. Stream job (Flink): drops duplicate click_ids, then counts per (ad_id, minute) in 1-minute tumbling event-time windows (Stream processing: windows, watermarks, state).
  3. OLAP store (Pinot, Druid, ClickHouse): keeps the minute rows, rolls them up to hours and days, and serves dashboards.
  4. Batch recount: the raw log is archived to object storage; an hourly and daily job recounts it and overwrites the stream's totals.

The hard parts

  1. Exactly-once counts: client retries, redelivery and job restarts all create duplicates.
  2. Late events: the watermark closes a window, but a click that arrives later must still be billed.
  3. Hot ads: one viral ad overloads a single partition and subtask.
Code What the stream job does: dedupe, window, idempotent upsert
pythonWhat the stream job does: dedupe, window, idempotent upsert
from collections import defaultdict

WINDOW, ALLOWED_DELAY, DEDUPE_TTL = 60, 30, 3600   # seconds, by event time

# In Flink, seen and counts are keyed state, checkpointed together with the Kafka offsets
seen: dict[str, float] = {}          # click_id -> event time
counts = defaultdict(int)            # (ad_id, minute) -> clicks in open windows
max_ts = 0.0

def on_click(e: dict) -> None:       # e = {click_id, ad_id, ts}
    global max_ts
    if e["click_id"] in seen:        # client retry or redelivery: count it once
        return
    seen[e["click_id"]] = e["ts"]
    minute = int(e["ts"] // WINDOW) * WINDOW
    if minute + WINDOW <= max_ts - ALLOWED_DELAY:   # its window was already emitted
        late_clicks.send(e)          # not lost: the batch recount reads the raw log
        return
    counts[(e["ad_id"], minute)] += 1
    max_ts = max(max_ts, e["ts"])
    advance(watermark=max_ts - ALLOWED_DELAY)

def advance(watermark: float) -> None:
    for ad_id, minute in [k for k in counts if k[1] + WINDOW <= watermark]:
        # Deterministic key + absolute value: a replay overwrites, it never adds
        olap.upsert(key=(ad_id, minute), clicks=counts.pop((ad_id, minute)))
    for click_id in [c for c, ts in seen.items() if ts < watermark - DEDUPE_TTL]:
        del seen[click_id]           # bounded dedupe state
Real example

Uber's pipeline for ads on UberEats (2021): Flink reads ad clicks and impressions from Kafka, removes duplicates with keyed state, and counts them in one-minute tumbling windows. Each aggregated row gets a record UUID: Pinot upserts on it and the ad-budget service uses it as an idempotency key, so a replay never counts twice. Output goes to Kafka in transactions that commit on each Flink checkpoint, every 2 minutes, and readers use read_committed. Uber calls the checkpoint interval its main latency bottleneck: exactly-once, but not quite real time.

Trade-offs +3 · −3

+ You gain

  • The click path does one log append: an aggregation outage never breaks redirects.
  • Event-time windows give the same counts live and on replay.
  • The raw log is the source of truth: any aggregate can be recomputed after a bug.

− You pay

  • Two code paths, stream and batch, must apply the same dedupe and filter rules.
  • Transactional output waits for the next checkpoint, up to one interval; a tight watermark means more late clicks.
  • Dedupe state grows with click rate × TTL.

Use it when

High-volume event counting that is shown in near real time and also billed: ad clicks and impressions, API usage metering, view and like counters.

Avoid it when

A few thousand events a day: insert rows and GROUP BY in the database. If nobody needs numbers before tomorrow, a daily batch job alone is simpler.

Numbers to know 5
  • Assumed: 1B clicks/day ÷ 86,400 s ≈ 11.6k/s average, ~58k/s at a 5× peak.
  • Raw log: 1B × ~0.5 KB (assumed) ≈ 500 GB/day.
  • Dedupe state: ~42M click ids per hour of TTL (1B ÷ 24).
  • Freshness ≈ 1-minute window + watermark delay (e.g. 30 s) + up to one checkpoint interval when the sink is transactional.
  • Uber (2021): one-minute tumbling windows, Flink checkpoints every 2 minutes.
Common pitfalls 4
  • Counting by processing time: a consumer backlog moves clicks into the wrong minute, and the wrong invoice.
  • Incrementing the stored count on each window emit: a replay after a crash adds the window twice. Upsert by (ad_id, minute).
  • Different dedupe or fraud rules in stream and batch: the two totals never match and nobody trusts either.
  • Unbounded dedupe state: keep click ids for a TTL, not forever.
Interview questions 3

Answer out loud first, then reveal.

The stream job crashes and restarts. How do you avoid double counting?Show answer

Three layers. State and Kafka offsets come back from the same checkpoint, so each click affects the counts once. The sink is idempotent: every window row is upserted under a deterministic key, (ad_id, minute), or written in a transaction that commits with the checkpoint. And each click carries a click_id minted when the ad was served, so client retries are dropped in keyed state. Billing still reads the batch-reconciled totals.

A click arrives two hours late. Is it billed?Show answer

Yes, but not by the stream. The watermark closed that minute long ago, so the job sends the click to a late side output and counts it as a metric. The raw event is in the log, so the next batch recount includes it and overwrites the stored total. I'd state the contract to the product team: dashboards are fresh and nearly right; invoices come from reconciled data.

One ad gets 30% of all clicks. What breaks?Show answer

Skew. Keyed by ad, one subtask takes 30% of the load and lags while the others idle. I'd aggregate in two stages: key by (ad_id, salt) with a random salt from 0 to 15 and count per window, then key by ad_id and sum the 16 partial counts. Dedupe is keyed by click_id, so it is already spread evenly. In the store, a hot ad is still one row per minute.

Deep dive 3

Exactly-once counts, end to end

Duplicates enter at three places, and each needs its own fix. Client retries: the same click sent twice carries the same click_id; the job keeps seen ids in keyed state with a TTL and drops repeats. That state is ~42M ids per hour of TTL at 1B clicks/day; a Bloom filter would shrink it, but a false positive drops a real, billable click. Job restarts: Flink restores counts and Kafka offsets from the same checkpoint, so replayed events don't count twice (Stream processing: windows, watermarks, state). Sink writes: commit output in a transaction tied to the checkpoint, or upsert each row under a deterministic key such as (ad_id, minute), so a replay overwrites. Invalid clicks (bots, click farms) are filtered in a separate step before billing.

Late events and batch reconciliation

The watermark delay sets the trade: 30 s means each minute is final ~30 s after it ends, and anything later misses the stream count. Send those clicks to a side output and track their rate. They are not lost: every event is in the raw log, archived to object storage by event hour. A batch job recounts each closed hour and day with the same dedupe and filter rules, then overwrites the stored rows. Billing reads only reconciled periods, and an alert fires when stream and batch totals diverge beyond a threshold. This is the Lambda architecture: two code paths to keep in sync. The alternative, Kappa, keeps one streaming job and fixes history by replaying the log through a new version of it.

Serving store and hot ads

Queries are aggregations over time ranges with filters, the workload column stores are built for. Store one row per (ad_id, minute, dimensions) and roll up to hours and days: Druid's rollup at ingestion can cut row counts by orders of magnitude, at the cost of losing individual events. A 30-day chart then reads 720 hourly rows per ad instead of 43,200 minute rows. "Top ads" is ORDER BY clicks DESC LIMIT k over a window, or a dedicated pipeline (Design: top-K and heavy hitters). Hot ads: keyed by ad, one viral ad lands on one subtask. Aggregate in two stages: count per (ad_id, salt) with a random salt, then sum the partial counts per ad_id.