Design an Ad Click Aggregator

How to count ad clicks per ad per minute with fresh dashboards and exact billing, and what interviewers ask about deduplication, hot ads and late events.

Case study30 minLesson 1 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions
  10. What to practise next

An ad click aggregator records every click on an ad, redirects the user to the advertiser's site, and shows the advertiser how many clicks each ad received per minute. Advertisers are billed per click, so the counts have to be exact: too low and the platform loses revenue, too high and a customer is overcharged.

Interviewers ask it because the volume is high, a few ads receive most of the clicks, clicks can arrive late or twice, and the same number has to be both fresh on a dashboard and exact on an invoice. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a system that aggregates ad clicks.

You

A user clicks an ad, we record the click and redirect them, and advertisers see click counts. At what granularity do they want the counts, and how fresh must they be?

Interviewer

Clicks per ad per minute, and the dashboard should be current within a few seconds.

You

Are the same counts used for billing?

Interviewer

Yes, advertisers pay per click.

You

Then the dashboard can show a provisional number, but the number we bill from must count every valid click exactly once. How many clicks and ads should I plan for?

Interviewer

About 10 billion clicks a day across 1 million active ads.

  • Functional requirements: record a click and redirect the user to the landing page; return the clicks per ad per minute for any time range; produce final counts that billing can use.
  • Non-functional requirements: the redirect adds less than 50 ms; the dashboard is current within about 10 seconds; billed counts are exact, so each valid click is counted once; no accepted click is ever lost; the system survives the loss of any single machine.
  • Out of scope: choosing which ad to show, fraud detection (the design leaves a place for it), counting unique users, and the billing system itself.

Estimate the scale

  • Click rate: 10 billion clicks a day divided by about 86,400 seconds is roughly 116,000 clicks a second on average. Assuming the peak is three times the average, the peak is about 350,000 a second.
  • Ingest bandwidth: at about 300 bytes per raw click event, 350,000 events a second is about 105 MB/s.
  • Aggregate rows: there is at most one row per ad per minute, which is 1 million ads × 1,440 minutes = 1.44 billion rows a day. At about 40 bytes a row that is about 58 GB a day.
  • Partitions: assuming one partition and its task handle 10,000 events a second, the peak needs 35 partitions. The design uses 64, about 5,500 events a second each.
Estimate: Raw click storage

How much raw click data arrives per day?

You know
  • 10 billion clicks a day
  • About 300 bytes per raw click event

Show the working
  1. 1010 × 300 B = 3 × 1012 B = 3 TB a day
  2. Kept for 90 days: 3 TB × 90 = 270 TB, which belongs in object storage and not in the query store

Estimate 3 TB (anything from 1 TB to 10 TB is a good answer)

Raw data is about 50 times larger than the minute aggregates (3 TB against 58 GB a day), so queries read the aggregates.

Your turn: Define the API

Write the click endpoint and the query endpoint before reading on. What information does the click URL carry?

Compare with a model answer

The click is a GET that answers with a 302 redirect, and the query takes a time range. The click URL carries a signed impression token. The landing page is looked up by ad id on the server and is never taken from the URL, because otherwise the endpoint is an open redirect.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
GET /c?t={signed impression token}
  302 Found   Location: the ad's landing page (looked up by ad_id)
  The click is recorded before the response is sent. A bad or expired
  token still redirects, but the click is logged as invalid and not counted.
 
GET /v1/ads/{ad_id}/clicks?from=2026-11-14T10:00Z&to=2026-11-14T11:00Z
  200 { "ad_id": 42, "minutes": [
          { "minute": "10:05", "clicks": 1288, "final": false }, ... ] }
  403 Forbidden     the ad belongs to another advertiser
  400 Bad Request   the range is longer than 31 days at minute granularity
 
GET /v1/advertisers/{id}/clicks?from=...&to=...&group_by=ad&granularity=hour

The decision to argue is the signed token. When the ad server shows an ad, it creates a random impression id and signs the values {impression_id, ad_id, shown_at} with a secret key, using an HMAC. The click service can check the signature without a database call, and without it a script could invent clicks on a competitor's ad. The impression id is also the key for detecting duplicates.

Your turn: Model the data

Sketch the raw click event and the aggregate record. Which kind of store holds each one?

Compare with a model answer

The raw events go to a log and then to object storage. The aggregates are one row per ad per minute in a columnar analytics store, and each write replaces the stored value instead of adding to it.

Model the data

Records
-- click event: appended to the log, then copied to object storage (about 300 B)
impression_id   BINARY(16)   -- random, taken from the signed token
ad_id           BIGINT
advertiser_id   BIGINT
shown_at        TIMESTAMP    -- taken from the token
clicked_at      TIMESTAMP    -- event time, set by the click service
device_hash, ip, user_agent, valid (bool)
 
-- aggregate: one row per ad per minute (about 40 B)
ad_clicks_minute
  advertiser_id  BIGINT
  ad_id          BIGINT
  minute         TIMESTAMP
  clicks         BIGINT
  final          BOOLEAN      -- set by the batch recount
  ORDER BY (advertiser_id, ad_id, minute)   -- an upsert replaces the row

Raw clicks are written once and read in order, which fits a partitioned log such as Kafka, with a copy kept in object storage for the recount. Queries add up clicks over a time range, grouped by minute or hour, which means scanning a few columns across many rows. A columnar analytics (OLAP) store such as ClickHouse or Druid is built for exactly that.

The clicks column holds an absolute count that a later write replaces. It is never an increment, which means any writer can retry its write without changing the result.

Your turn: High-level design

Sketch the path from a click to the dashboard. Where is a click made durable, where is it counted, and where is it recounted?

Compare with a model answer

A click service appends each click to a partitioned log and then redirects. A stream processor removes duplicates, counts clicks per ad per minute and writes to an OLAP store. A batch job recounts from the raw archive and overwrites the rows with final numbers.

High-level design

Two paths compute the same numbers. The stream path is fast and almost always right, and the batch recount is slower and is the source of truth for billing. Both write to the same OLAP table, and the batch write replaces the stream's value.

A click is durable in the log before the redirect. The stream processor produces fresh counts, and the batch job recounts from the archive and marks the counts final.User's browser to Click service (GET /c?t=...); Ad server to User's browser (signed token); Click service to Click log (append); Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store (upsert); Batch recount to OLAP store (final); Advertiser to Query service; Query service to OLAP store (sum by minute).User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP storeGET /c?t=...signed tokenappendupsertfinalsum by minute

request and replyasynchronous message

A click is durable in the log before the redirect. The stream processor produces fresh counts, and the batch job recounts from the archive and marks the counts final.
A click: count it once, keep it fresh, make it finalUse the arrows or ← → keys
  1. A click: count it once, keep it fresh, make it final, step 1User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store
    impression
    7f3a
    ad
    42

    1The ad server shows ad 42 with a signed token for impression 7f3a. Nothing is stored yet.

  2. A click: count it once, keep it fresh, make it final, step 2User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick servicesignature okClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store
    impression
    7f3a
    clicked_at
    10:05:12

    2At 10:05:12 the user clicks. The click service checks the signature and stamps the event time.

  3. A click: count it once, keep it fresh, make it final, step 3User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick log3 copiesRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store
    impression
    7f3a
    redirect
    302

    3The click service appends the click to ad 42's log partition, waits until 3 replicas have it, and only then answers with a 302 redirect.

  4. A click: count it once, keep it fresh, make it final, step 4User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processor+1 at 10:05Batch recountAdvertiserQuery serviceOLAP store
    ad 42 @ 10:05
    1,288

    4The task for that partition has not seen 7f3a, so it remembers the id and adds 1 to ad 42's count for 10:05.

  5. A click: count it once, keep it fresh, make it final, step 5User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processor7f3a seen: dropBatch recountAdvertiserQuery serviceOLAP store
    ad 42 @ 10:05
    1,288
    duplicates dropped
    1

    5A double click reaches the same task, which finds 7f3a in its seen set and drops the second click.

  6. A click: count it once, keep it fresh, make it final, step 6User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store1,288 (draft)
    ad 42 @ 10:05
    1,288

    6Every 5 seconds the processor writes its open windows to the OLAP store, so the row (42, 10:05) is set to 1,288 with final = false.

  7. A click: count it once, keep it fresh, make it final, step 7User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store
    ad 42 @ 10:05
    1,288
    click to screen
    about 6 s

    7The dashboard shows the 10:05 count as provisional, about 6 seconds after the click.

  8. A click: count it once, keep it fresh, make it final, step 8User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorrestore: 1,270Batch recountAdvertiserQuery serviceOLAP store
    ad 42 @ 10:05
    1,270 restored

    8The task crashes. Its last checkpoint saved offsets, counts and the seen set together, with the count at 1,270. A new task restores it and replays the log.

  9. A click: count it once, keep it fresh, make it final, step 9User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store1,288 again
    ad 42 @ 10:05
    1,288

    9The replay rebuilds exactly 1,288 because the seen set and the counts were rewound together, and the upsert writes the same value again.

  10. A click: count it once, keep it fresh, make it final, step 10User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processortoo lateBatch recountAdvertiserQuery serviceOLAP store
    ad 42 @ 10:05
    1,288
    late clicks
    1

    10At 10:09 a click stamped 10:05:58 arrives from a server that had saved it to disk. The 10:05 window closed at 10:08, so the click goes to a side output.

  11. A click: count it once, keep it fresh, make it final, step 11User's browser to Click service; Ad server to User's browser; Click service to Click log; Click log to Raw archive, asynchronous; Click log to Stream processor; Raw archive to Batch recount; Stream processor to OLAP store; Batch recount to OLAP store; Advertiser to Query service; Query service to OLAP store.User's browserAd serverClick serviceClick logRaw archiveStream processorBatch recountAdvertiserQuery serviceOLAP store1,289 final
    ad 42 @ 10:05
    1,289 final
    stream was off by
    1

    11The hourly recount applies the same rules to the archive, gets 1,289 for (42, 10:05) including the late click, and overwrites the row as final.

1 / 11

Deep dives

Counting with a stream processor and a batch recount

The problem is that 350,000 clicks a second at peak is too many individual writes for most databases, and the counts must still appear within seconds. There are three options.

The simplest option is UPDATE ads SET clicks = clicks + 1 for every click. The count is always current, but it needs one database write per click, a popular ad's single row becomes a bottleneck, and a retried update counts the click twice.

The second option is a batch job over the logs. It can be exact, but its counts are as old as the last run, about an hour, which fails the 10-second requirement.

The third option, and the right one here, is a stream processor such as Flink that counts in memory and writes totals, combined with a batch recount for billing. The stream gives fresh counts, and the recount corrects anything the stream got wrong. The cost is two code paths that must apply identical rules.

The processor keys events by ad_id, so all clicks on one ad go to one task, and the task counts them in one-minute tumbling windows, which are fixed and do not overlap. Windows use event time, the clicked_at stamp, so a backlog after an outage still lands in the correct minute. Open windows are written to the OLAP store every 5 seconds. The log keeps 7 days of events so that any consumer can replay them.

Counting each click once

The same click can reach the processor more than once: a user double clicks, the click service retries an append after a lost acknowledgement, or the processor replays events after a crash. The log delivers at least once, so the design produces an exactly-once effect by combining deduplication on a business key with idempotent writes.

User and retry duplicates are removed by the processor, which remembers every impression id it has seen in the last 24 hours, the longest a click stays valid. Keying by ad_id sends both copies to the same task. The seen set costs 1010 ids × 16 bytes = 160 GB, or about 2.5 GB per task across 64 partitions. The log offsets, window counts and seen set are checkpointed together, so a restart rewinds all three. Replayed writes are harmless because each replaces the (ad, minute) row with an absolute count.

The seen set can live in three places. An exact set in the processor's state is a local lookup and is checkpointed with the counts, so it is rolled back together with them after a crash. A Bloom filter is ten times smaller or more, but each false positive drops a real click, and at a 0.1% rate that is 1010 × 0.001 = 10 million real clicks a day that are never billed. A shared key-value store with a set-if-absent operation lets any consumer check it, but it costs a network call per click, and it is not rolled back on a replay, so a replayed click is wrongly dropped as a duplicate.

Where to remember which impressions have been counted
OptionGood atBad atPick it when
Exact set in processor state Usual defaultLookups are local, and the set is checkpointed with the counts.It needs about 2.5 GB of state per task in this design.Use it for billing; it is the default.
Bloom filterIt is ten times smaller or more.False positives drop real clicks.Use it only for approximate dashboards.
Shared key-value store, set if absentAny consumer can check it.It costs a network call per click, and replays drop clicks.Use it when several consumers must share one decision.

Deduplicating on user, ad and minute is a common mistake in answers. It drops genuine repeat clicks and still lets a bot with many device ids through, so the key should be the impression id.

Hot ads and partition skew

The problem is that keying by ad_id puts all of one ad's clicks on one partition. That is fine for most ads, but an ad shown during a live final could get 30,000 clicks a second. The partition was sized for 10,000 a second, so its task falls behind, and every other ad on that partition falls behind with it.

The fix is to split a hot ad's work into two stages. The hot ad's events are keyed by (ad_id, salt), where salt = hash(impression_id) mod 8. This spreads ad 42 over 8 tasks of about 3,750 clicks a second each. A second stage keyed by ad_id adds up the latest partial count from each of the 8 tasks, so it receives 8 records every 5 seconds and not the 1.8 million clicks a minute that the ad actually gets. The salt is derived from the impression id and not from a random number, so both copies of a double click still go to the same first-stage task and are deduplicated there.

Only ads on a hot list are salted, and the list is refreshed every minute. If an ad joins the list between the two halves of a double click, both can be counted, and the recount corrects it.

Late events and the recount

The problem is that some clicks arrive after their minute has been counted. For example, a click server that cannot reach the log saves clicks to local disk and sends them when the log returns. The stream processor tracks a watermark, which is its estimate that no older events are still coming. It keeps each minute's window open until the watermark is 2 minutes past the end of that minute. Events that arrive after that go to a side output instead of being counted.

The batch recount handles those events. It runs every hour over the previous hour's data and applies the same rules to the raw archive, carrying the 24 hours of seen impression ids from one run to the next. It overwrites the stream's rows with final = true and leaves out clicks that the fraud system has marked invalid. The system should alert when the stream and the recount differ by more than about 0.1% in an hour.

Bottlenecks and failures

At 10 times the load, the peak is 3.5 million clicks a second, and the log needs about 640 partitions to stay at about 5,500 events a second each. The OLAP store is sharded further by advertiser.

When this failsWhat happensWhat you do
A click serverClicks that were in flight on it fail.Health checks take it out of rotation, clients retry on another server, and deduplication drops any copy that was already recorded.
The click logAppends fail or time out.The click service still redirects the user. It saves the click to local disk and appends it when the log recovers.
A stream taskCounts for the ads on its partitions stop updating.A new task restores the last checkpoint and replays the log, and the counts are exact again within a minute or two.
The OLAP storeDashboards stop showing new data.The processor retries its upserts, and the log still holds every event.
The batch recountMinutes stay provisional.Billing waits, and the job is rerun. Rerunning is safe because it overwrites rows with absolute counts.

The click service waits for the log's acknowledgement before it redirects, because redirecting first would lose a billable click if it crashed between the two steps.

What a strong answer sounds like

LevelWhat the answer does
JuniorCounts in a database row per ad, and adds a queue to protect the redirect once the interviewer asks about load.
MidUses a log, a stream processor with one-minute windows and an analytics store, and adds deduplication by id when asked.
SeniorSeparates fresh counts from final counts, signs the impression id, explains exactly-once effect, handles hot ads and late events, and bills from a recount.
Exactly onceStrong answer
Interviewer

How do you guarantee that a click is billed exactly once?

You

The log delivers at least once, so I make the effect exactly once instead. I key events by ad so both copies of a click go to one task, and that task remembers signed impression ids for 24 hours. It checkpoints the seen ids, counts and offsets together, and the writes replace the row for that ad and minute, so a replay changes nothing.

Interviewer

And what if the stream still gets a count wrong?

You

An hourly recount from the raw archive overwrites the stream's numbers and marks them final, and billing reads only final rows. The stream is there for fresh dashboards, and the recount is the number we charge from.

Follow-up questions

Advertisers also want counts by country and device. What changes?

Add those fields to the aggregate key. Keep the minute rows to a few dimensions and serve finer breakdowns from hourly rows, which are far fewer.

How do you stop click fraud?

A separate system reads the same click log and scores each click. The recount excludes the clicks it marks invalid, so advertisers are not billed for it.

Why not query the raw events directly?

One advertiser's clicks for a month can be billions of rows, and a dashboard would have to scan all of them for every chart. The minute aggregates are about 50 times smaller.

How long do you keep minute-level rows?

About 30 days, which is 58 GB × 30, or about 1.7 TB. After that, roll them up into hourly rows, which are 60 times fewer and can be kept for years.

How would you run it in several regions?

Run click services and a log in each region. Ship the raw events to one region for the recount. The impression id is created once, so it still identifies duplicates across regions.

Self-review: ad click aggregator0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure

What to practise next

Design Top-K Trending counts at the same scale but trades exactness for memory, and Design Metrics Monitoring stores counts as time series and alerts on them.