"Design an ad click aggregator" usually gets a stream processor in the middle of the board with "exactly-once" written beside it. Clicks go into Kafka, Flink counts them per ad per minute, and a database serves the counts. The candidate says the counts can be billed, because Flink's checkpoints, its saved snapshots of state, make them exact.
Then the interviewer asks about three clicks. One reaches the pipeline 40 minutes late, after its minute was counted. One turns out on Thursday to have come from a bot farm on Monday. One was counted twice for 3 weeks, because a click-server release gave a repeated click a new ID. Each changes a number that an advertiser has already seen, and may already have paid.
Flink's exactly-once covers none of them. It promises that each event that reached Kafka changes the job's state once. A click that arrives after its window closed, a click that was valid on Monday and invalid on Thursday, and two copies of one click with different IDs are all outside that promise. The invoice depends on all three.
Never keep a count you can't compute again. Keep every click in a log that never changes, under an ID that survives retries, and treat the dashboard's number and the invoice's number as two runs of the same query over that log.
That sentence settles most of the design. The click has to reach the log before anything else, because a click missing from the log can't be counted by any later run. The stream processor is the first run, fast and provisional. The invoice comes from a second run, made once late clicks and fraud verdicts have settled. A bug fix is a third run.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
An ad platform shows ads on its own pages and in partner apps. Each ad carries a click URL that points at the platform's click server. When a user clicks, the click server records the click and redirects the browser to the advertiser's landing page. Advertisers pay for each click, and they watch their clicks, impressions and spend per ad and per campaign on a dashboard.
Four kinds of system go by this name, and each is designed differently.
- Ad serving, which picks the ad for each page view in an auction. Ad serving and real-time bidding designs it. Here it is the service that creates each impression and its click URL.
- Click analytics for links, as in the URL shortener. Nobody pays per click there, so a click may be dropped and counts may be approximate.
- Metrics about the platform itself, such as request rates and error counts. Metrics and monitoring designs that, and those numbers are about our servers, not anyone's bill.
- Counting ad events well enough to bill on. Every valid click is counted once and charged once, and the totals have to hold up when an advertiser disputes them. This is the one we're designing.
Functional requirements
Core:
- Record each click and send the user to the landing page.
- Count clicks, impressions and spend per ad, per minute, with each click counted once however many times it is delivered.
- Let advertisers query their counts for any time range, by ad or campaign, and by country and device.
- Produce the billed total per campaign per day, which must match a recount from the raw clicks.
Out of scope, deliberately:
- Choosing which ad to show, and the auction that sets its price. The click arrives with its price already set.
- Budget pacing, where ad serving stops showing a campaign that has spent its budget. It reads our counts.
- Conversions, meaning purchases or sign-ups after the click, and crediting them to ads.
- Invoicing and collecting the money. The payment system takes the billed totals from here.
- The fraud models themselves. Fraud detection builds them, and this design runs their verdicts.
Non-functional requirements
- Scale. 20 billion impressions a day across 10 million active ads, a click rate of 1 percent, and an average price of $0.50 a click. These are assumptions, sized for a large platform.
- Redirect latency. The click server answers in under 20 ms at the 99th percentile, the latency 99 percent of requests beat. The redirect sits between the user and the page they asked for.
- Freshness. A click shows on the dashboard within 1 minute.
- Billing accuracy. No click is billed twice, no valid click is lost, and every billed total can be reproduced from the raw clicks.
- Retention. Raw clicks are kept for as long as an invoice can be disputed, assumed to be 13 months.
Requirement 4 carries the design, and this is what getting it wrong costs.
The question is how exact the counting has to be, and
which events set the size of the pipeline. Daily figures
become rates with the course's divide-by-100,000 shortcut.
Volume
clicks 20B × 1% = 200M/day
average 200M / 100,000 ≈ 2,000/s
peak, 5x ≈ 10,000/s
impressions 20B / 100,000 = 200,000/s
peak, 5x = 1M/s
Money
billed a day 200M × $0.50 = $100M
assume 0.1% of clicks are delivered twice
by at-least-once delivery, and counted twice
200M × 0.001 = 200,000/day
200,000 × $0.50 = $100,000/day
─────────────────────────────────────────────────────────
Impressions outnumber clicks 100 to 1, so they set the size
of the pipeline. Clicks carry the money, and a duplicate
rate nobody would notice on a dashboard overbills
advertisers by $100,000 a day.The set up
Core entities
- Impression. One ad shown once. Ad serving gives it an
impression_idwhen it serves the ad. - Click. A user's click on one impression. Its ID is the only interesting field: a click's ID is its impression's ID, so a double click, a browser retry and a resent event all carry the same one.
- Ad and campaign. An ad belongs to a campaign, and a campaign to an advertiser. Ad serving owns both, and we read them.
- Minute count. Clicks, impressions and spend for one ad, country and device in one minute.
- Closed day. The billed total for one campaign on one day, with a version number. The recount writes it, and nothing changes it in place.
System interface
GET https://clk.ads.example/c?t=eyJpbXAiOiI5ZjJjNDFk...
→ 302 Location: https://shop.example/spring-sale
the token in t, signed by ad serving when it served the ad:
{ "imp": "9f2c41d8e0b7a3c6", "ad": 48213, "camp": 7710,
"served_at": "2026-11-08T12:00:03Z", "cpc_micros": 420000,
"dest": "https://shop.example/spring-sale", "sig": "..." }
POST https://px.ads.example/i (impression beacon)
{ "imp": "9f2c41d8e0b7a3c6", "ad": 48213 }
→ 204
GET /v1/stats?campaign=7710&from=2026-11-01&to=2026-11-08
&granularity=hour&group_by=ad,country
→ 200 { "counted_to": "2026-11-08T14:05:30Z",
"rows": [ { "ad": 48213, "hour": "2026-11-03T14:00Z",
"country": "IN", "clicks": 1240, "impressions": 131022,
"spend_micros": 520800000, "status": "closed" }, ... ] }
GET /v1/billing/campaigns/7710/days/2026-11-01
→ 200 { "clicks": 88412, "amount_micros": 36120440000,
"version": 1, "cut_at": "2026-11-05T00:00Z" }
Four things to note.
The token carries everything the click server needs. Ad serving signs it with a key the click server shares, so the click server checks the signature and redirects without reading a database. A token forged for an ad that was never shown fails the check. The price is in the token too, because the auction set it when the ad was served.
The click's ID comes from the impression, not from the click server. If the click server made a fresh ID for each request, a double click would produce two IDs and two charges. With the impression's ID, one impression produces at most one billable click, however often the request is repeated. That's a product rule as well as a technical one, so state it in the interview. Google Ads draws the line at 2. Its help page on clicks says it won't charge for more than 2 clicks per ad impression, and notes that browsers cache results pages, so an ad can be clicked again without a new impression being recorded. Our rule gives up that second click's revenue, and in return the duplicate check needs nothing but the ID.
Every stats row says whether it can still change. status is provisional for a count from the stream and closed for a count from the recount. The advertiser can see which numbers are still moving.
Money is in micros, millionths of a currency unit, held as integers. Integers add up exactly and binary floating point doesn't, and an invoice has to. The payment system keeps minor units for the same reason.
All of that is the data plane. The control plane holds ads, campaigns, fraud rules and job settings. The click server needs only the token and the key that verifies it, so clicks keep redirecting and counting while ad serving's own databases are down.
High-level design
1. Record the click: when is it safe?
The redirect has two jobs, and they conflict. The user wants the landing page now. The advertiser's bill needs the click recorded somewhere that survives a crash. The question is where the click has to be before the click server sends the 302.
Redirect first, send the click afterwards
The URL shortener does this, on purpose. The handler appends the click to a buffer in memory, returns the 302, and a background thread sends the buffer to Kafka every second. If Kafka is unreachable, the click is dropped, because a failed redirect is worse than a missing click.
Here a missing click is lost revenue, so the same choice is wrong. A process that crashes loses the clicks in its buffer, and nothing records that they existed. An outage costs far more. If Kafka is down for 10 minutes at peak, the click servers drop 6 million clicks, worth $3 million, as the worksheet below shows.
Write the click to Kafka, then redirect
The handler sends the click to Kafka with acks=all, on a topic with 3 replicas and min.insync.replicas=2. The broker then confirms only once at least two replicas, in two zones, have the event. The handler returns the 302 when that confirmation arrives. Inside one region that adds a few milliseconds, two round trips between zones at the course's 0.5 to 2 ms each.
Its cost is that Kafka is now part of every redirect. When a partition's leader fails over, or the cluster is down, the handler has two bad choices. It can wait and then fail the redirect, which loses the visit the advertiser paid for. Or it can redirect without recording, which loses the click. Most teams add a fallback that writes to local disk when Kafka times out. That fallback runs only during an outage, so its bugs are found during an outage.
Append to a local log, ship it afterwards
Question the premise that the click has to be on another machine before the user moves on. It has to be somewhere a crashed process can't lose it, and the click server's own disk is such a place.
So the fallback becomes the only path. The handler appends the click to a local append-only file, with its ID and a sequence number that counts up on each server. Many clicks share one flush to disk, at the course's 0.3 ms per flush on a data-centre NVMe drive. When the flush that covers the click returns, the handler sends the 302. A separate shipper process reads the file and produces each click to Kafka, with the same acks=all and min.insync.replicas=2. It saves its place in the file only after Kafka confirms. If Kafka is down, the file grows and the redirects carry on.
What you give up. Until the shipper sends it, a click exists on one disk, and a dead disk loses it. Normally that lasts under a second. During a Kafka outage it lasts the whole outage, so the entire backlog has one copy, and the worksheet below prices that. Each server also reports its highest sequence number to monitoring every few seconds, outside Kafka. Clicks lost with a dead disk then show up as numbers the server reported and the archive never received, so the loss is counted, not silent, apart from the few seconds since its last report. And each click server needs a disk sized for an outage, plus a shipper to run and watch.
The question is what a 10-minute Kafka outage at peak
does to clicks in each design. Peak is 10,000 clicks a
second, and a click event is about 500 bytes.
clicks in the outage 10,000 × 600 s = 6M
their value 6M × $0.50 = $3M
Redirect first, drop when Kafka is down
clicks lost = 6M
Write to Kafka first
redirects that wait, then fail or go
unrecorded = 6M
Local log, shipped afterwards
waiting on click servers 6M × 500 B = 3 GB
shipped after recovery at an assumed 4x peak,
while new clicks arrive 6M / (40,000 − 10,000) ≈ 200 s
held in one copy until then; a server whose disk
dies late in the outage loses its share, one of
12 click servers (deep dive 4)
6M / 12 = 500,000 clicks, 500,000 × $0.50 = $250,000
─────────────────────────────────────────────────────────
Only the local log keeps both the redirect and the click.
The backlog fits in 3 GB and reaches Kafka about 3
minutes after it recovers. Until then it has one copy,
and a disk that dies late in the outage costs about
$250,000, counted by the sequence numbers, apart from
the few seconds since that server's last report.The click server decides nothing about money. A token with a bad signature gets an error page and a log line for the fraud team. The same check keeps the click server from being an open redirect, a link on a trusted domain that sends people wherever an attacker writes into the URL. Only ad serving can sign a destination. Every other click is recorded and redirected, including one from a known bot or one whose impression is days old. Whether it is billable is decided later, from the log, where the decision can be made again.
Impressions arrive as beacons from the browser or app, at 100 times the click rate. A separate fleet of collectors takes them with the same local log and shipper. Nobody waits on a beacon, so a collector answers 204 without waiting for the flush. A beacon the browser never sends, because the tab closed or an ad blocker stopped it, is lost before it reaches us. So impression counts are a lower bound, whatever we build.
2. Count each click once, per ad and per minute
Click servers and collectors ship every event to Kafka: clicks to a topic called clicks, impressions to impressions. Both are keyed by the event's ID, so the events spread evenly over each topic's partitions. A stream processor, a consumer that keeps state between events and restores it after a crash, reads both topics and keeps a count for each ad, country, device and minute.
The events go to a log, not to a work queue such as SQS. Two readers need every event, the stream processor and an archive sink, and the stream processor reads events again after a crash. A queue deletes each message once one reader has it, as message queues vs event streams explains. The archive sink is a Kafka Connect job that copies every event to S3 as Parquet files, a column-oriented file format, one set per hour.
Kafka Streams and Flink are the two usual stream processors. Both count by the time an event happened, and both save their state together with their place in Kafka. We use Flink, because section 4 runs the same program over files in S3, and Kafka Streams reads only from Kafka.
Three questions decide how it counts. Which minute does a click belong to? How is a copy recognised? And how does a count survive a crash without counting anything twice?
Which minute does a click belong to?
The click server stamps each click with the time it received it, clicked_at. That is the click's event time. The time the stream processor reads the click is its processing time. The two differ by the shipping and queueing delay, which is normally under a second and can be 10 minutes after a Kafka outage.
If clicks were counted by processing time, every outage would move them into later minutes. A click from 23:59:50 that is read at 00:00:10 would be billed on the wrong day. So the counts use event time. The job keeps a one-minute tumbling window for each key, a fixed minute that doesn't overlap the next one, and adds each click to the window its clicked_at falls in. Uber's ad pipeline keys its one-minute windows by ad and minute for the same reason: so a click lands in the right minute however late it arrives.
Event time raises a question processing time never had: when is a minute finished? A click from 12:00:50 can still be on its way at 12:05. A stream processor answers with a watermark, a timestamp that moves forward as events arrive and says the job expects nothing older than it. Here the watermark trails the newest event time seen by 30 seconds. When it passes 12:01, the 12:00 window emits its final count. Deep dive 1 covers the clicks that arrive behind it.
The dashboard doesn't wait for the watermark. While a window is open, it emits its current count every 10 seconds, so a click shows up within seconds and requirement 3 holds.
How is a copy recognised?
A click can reach the stream more than once, in two ways. A redelivery is the same event sent again: the shipper resent a batch it wasn't sure about, or restarted from its last saved place in the file. A repeat request is a new request for the same token: a double click, a browser retry, or a second click on a cached page. The click server stamps a repeat with its own clicked_at, but the ID is the same, because the ID comes from the token.
So the job remembers the IDs it has counted. Before any window sees an event, an operator, one step of the job, looks it up in state keyed by event type and ID. The type is in the key because a click shares its impression's ID. If the key is there, the copy is dropped. If not, the key is stored and the event goes on.
IDs are random, so this state spreads evenly over the operator's parallel copies, which Flink calls subtasks. How long to remember an ID is deep dive 2: 7 days for clicks, and an hour for impressions.
How does a count survive a crash?
The stream job's state is its open windows and the IDs it has seen. A machine that dies takes its share of both, so the job restores them from a saved copy. The restored state also has to agree with what was already written to the data store the dashboard reads. So the question becomes how the counts in that data store stay exact when the job can crash between updating its state and writing its output.
Add each click to a counter in the database
The consumer runs UPDATE counts SET clicks = clicks + 1 for each click and commits its Kafka offset, its place in the topic, afterwards. It's the obvious design, and it works until a crash.
A crash after the update and before the commit replays those clicks, and each is added again. The counter can't tell, because it holds a number, not the IDs behind it. Change data capture calls this applying differences, and a consumer that does it has to remember every event it applied. At the 0.1 percent redelivery rate assumed in the first worksheet, that's $100,000 a day of overbilling.
Checkpoints and a transactional sink
Flink takes a checkpoint at a set interval, every few minutes here: a consistent snapshot of every subtask's state, together with the Kafka offsets it had read, written to object storage. After a crash, every subtask restores the last checkpoint and re-reads Kafka from those offsets. So the job's state counts each event once.
Each window emits only what's new since its last result, and the data store adds the results up. So the results have to be exact too. Flink's Kafka sink, the operator that writes results out, writes them inside a Kafka transaction and commits it only when the checkpoint completes. Flink's own write-up on it calls this a two-phase commit. Readers set read_committed, so they never see results from a checkpoint that failed.
Uber's ad pipeline works this way: one-minute windows, a checkpoint every 2 minutes, and Pinot reading the committed results.
Its cost is freshness. Flink's Kafka documentation says this "delays record visibility effectively until a checkpoint is written". With 2-minute checkpoints, a click can wait 2 minutes plus its window, which breaks requirement 3. Shorter checkpoints mean more transactions and more snapshots.
Write whole counts, so a replay overwrites
Question the premise that each result has to be delivered exactly once. It only has to land harmlessly when it's delivered twice.
So the job emits each window's whole current count, never an increment, every 10 seconds, keyed by ad, country, device and minute. Each row also carries events_applied, the number of events the window has counted so far. For each key, the data store keeps the row with the larger events_applied. Delivery can be at-least-once, because a row delivered twice replaces itself. After a crash, the job restores an older checkpoint and re-emits smaller counts. The data store takes those rows too, but the larger row it already holds hides them until the replay passes it.
Checkpoints still make the job's own state exact, and they can stay minutes apart, because they no longer decide when a click becomes visible. The Dataflow paper names both output modes. Discarding mode emits independent results for a consumer that adds them up, which is the senior tier. Accumulating mode suits a consumer that "expects to overwrite old values with new ones", which is this one.
What you give up. The data store has to replace rows by key and keep the larger version. ClickHouse can, and section 3 picks it. Druid can't, because its streaming rollup sums rows that share a key. The rule also hides a correct count that is lower, such as one from a job restarted with no state, or a recount by fixed code. So only the close can lower a day's numbers. And the job writes each live row up to 6 times a minute instead of once.
3. Serve the counts: which data store?
Advertisers ask two kinds of question. "How is this campaign doing right now?" reads the last few hours by minute. "How did it do this month?" reads 30 days by hour or day, grouped by ad and country. The data store has to take the stream's writes and answer both.
Which data store, and what actually forces it
Three numbers decide it: how fast the stream writes rows, how many rows a month-long chart reads, and what it costs to hold every key in memory.
The question is which data store takes the stream's writes and still answers a month of counts quickly. Writes a row is rewritten only when its count changed, so rows written are at most events counted at peak, at most ≈ 1M/s one Postgres primary, course figure 5,000 to 20,000/s primaries for the writes alone 50 to 200 One chart: a campaign of 500 ads, 30 days, by hour, counted per ad before the country and device split minute rows 500 × 30 × 1,440 = 21.6M hour rows 500 × 30 × 24 = 360,000 day rows 500 × 30 = 15,000 Pinot's upsert map, 24 B plus a 16 B hashed key per row a day, at most one row per event 20B × 40 B ≤ 800 GB ───────────────────────────────────────────────────────── Even at a tenth of these bounds, Postgres needs 5 to 20 primaries for writes alone. Minute rows suit today's chart and cost 60 times the hour rows for a month. And a map of every key in memory needs up to 800 GB for each day kept, and tens of gigabytes even at a tenth of that.
One Postgres table of minute counts
One row per ad, country, device and minute, with an index on campaign and minute. Postgres can take the upsert, an insert that updates the row if its key exists, as INSERT ... ON CONFLICT DO UPDATE ... WHERE excluded.events_applied > counts.events_applied. For one advertiser's last hour, it's the right answer.
It fails on writes first. Even at a tenth of the bound in the worksheet, the stream's rows need 5 to 20 primaries before a query runs. Then the month-long chart groups 21.6 million ad-minutes, more once country and device split them, and a row store reads every column of every row to do it. Choosing a database gives the rule: a dashboard that scans gets its own column store.
A columnar store of minute rows, replaced by key
A columnar store keeps each column apart and compressed, so a query reads only the columns it names. Two of them can replace a row by key.
Pinot's upsert keeps a map from every key to its newest row in memory, so a read never sees an old version. Uber's ad pipeline uses it, at hundreds of millions of events a week. Here the map would need up to 800 GB of memory for each day kept, and tens of gigabytes even at a tenth of that.
ClickHouse's ReplacingMergeTree keeps no map. It stores every version and removes the older ones during background merges, keeping the row with the largest version column. Merges run at an unknown time and may never reach some rows, so every read adds FINAL, which collapses the versions as it reads. Take ClickHouse, with events_applied as the version column.
Its cost is the month-long chart. It still reads 21.6 million ad-minutes, through FINAL, every time someone opens it.
Keep minute rows only while a day can change
Question the premise that counts are kept by the minute because they were counted by the minute. A minute row is useful while its day can still change, and a dashboard shows minutes only for recent hours.
So keep minute rows for 7 days, in the table that replaces by key. When the recount in section 4 closes a day, it writes that day's hour and day rows into closed tables, partitioned by day. Every version of the day, the first included, is built in a staging table and swapped in with ClickHouse's REPLACE PARTITION. The swap is atomic, so a reader sees one version of a day or the other. A month-long chart reads closed hours for the closed days, and sums minute rows only for the 4 days still open: today and the 3 before it.
Counted per ad, before the country and device split, that chart reads 26 × 24 × 500 = 312,000 closed hours and 4 × 1,440 × 500 = 2.9 million open minutes. That's 3.2 million rows instead of 21.6 million.
What you give up. Minutes older than 7 days are gone from ClickHouse, so a chart of last month can't zoom to minutes. The raw clicks are still in the archive, so any minute can be counted again if a dispute needs it. The API also has to know which days are closed and stitch two tables into one answer.
| data store | what goes in it | what forces it |
|---|---|---|
| local file on each click server and collector | events not yet shipped | a redirect can't wait on the network, and a click can't be lost |
Kafka, clicks and impressions | every event, kept 7 days | several readers at their own pace, and a re-read after a crash |
| S3, Parquet files by hour | raw clicks for 13 months, impressions for 90 days, fraud verdicts and billed click IDs | the recount, backfills and disputes |
| Flink state, in RocksDB on local disk | open windows, click IDs for 7 days, impression IDs for an hour | windows and duplicate checks |
| ClickHouse | minute rows for 7 days; closed hour and day rows | up to about 1 million rows a second, and scans over months |
| Postgres | each campaign's closed days, by version | read by invoicing, and changed only by adding versions |
The tables
-- S3, written by an archive sink that copies every event from Kafka
raw_clicks ( -- Parquet, partitioned by hour of clicked_at
click_id bytes, -- derived by the click server, = token_imp
token_imp bytes, -- the impression ID, copied from the token
ad_id, campaign_id bigint,
served_at, clicked_at timestamp, -- the impression's time; event time
archived_at timestamp, -- commit time of the row's file in S3,
-- from the file's metadata
cpc_micros bigint, -- the price, from the token
country, device, region, ip, user_agent,
server_id, server_seq bigint -- server_seq counts up per server
)
-- raw_impressions is similar, keyed by impression_id
-- S3, written by the fraud models, and by the close
invalid_clicks (click_id, click_day, reason, model_version, found_at)
-- click_day: the day of the first copy;
-- found_at: commit time of the verdict's file
billed_click_ids (day, version, click_id, written_at)
-- the IDs each version of a day billed
filtered_click_ids (day, version, click_id, written_at)
-- the IDs its inline rules dropped
-- ClickHouse, written by the stream
live_minute (
campaign_id, ad_id, minute_start, country, device, region,
clicks, impressions, spend_micros, filtered_clicks,
events_applied bigint -- the version: the larger row wins
) ENGINE = ReplacingMergeTree(events_applied)
ORDER BY (campaign_id, ad_id, minute_start, country, device, region)
TTL minute_start + INTERVAL 7 DAY
-- ClickHouse, written by the close; every version of a day is
-- built in a staging table and swapped in with REPLACE PARTITION
closed_hour (campaign_id, ad_id, hour_start, country, device,
version, clicks, impressions, spend_micros)
ENGINE = MergeTree PARTITION BY toDate(hour_start)
ORDER BY (campaign_id, ad_id, hour_start)
closed_day -- the same, by day
-- Postgres, read by invoicing
closed_days (
campaign_id bigint, day date, version int,
clicks bigint, amount_micros bigint,
cut_at timestamptz, -- the run counted rows up to this time
job_version text, rules_version text,
primary key (campaign_id, day, version)
)
Four things to note.
raw_clicks keeps every column the close needs. The close runs the same program as the stream, so the archive holds what the stream reads: country, device, region, IP address and user agent. IP addresses and user agents are personal data, so keeping them for 13 months is a retention decision privacy law has to allow, not only a storage cost.
A version is a run up to a cut time. archived_at is the commit time of the file a click arrived in, so it marks when the row became readable. found_at is the commit time of a verdict's file, and written_at is when a close billed or filtered an ID. Version n of a day counts only rows at or before its cut_at, with the job and rule versions it records, the rules' IP ranges and bot lists included. So running it again gives the same total. A later click or verdict can only change a later version, and an invoice names the versions it was cut from.
token_imp sits beside click_id. The click server derives click_id, and token_imp is copied straight from the signed token, so the two should always match. A row where they differ is a click-server bug, found the day it ships.
server_seq makes a lost click countable. Each server reports its highest number to monitoring every few seconds, outside Kafka. A number it reported that never reached the archive is a lost click, even when the server died and sent nothing more. Only the few seconds since its last report go uncounted.
The queries that carry the product
-- 1. The live dashboard: the last 6 hours by minute
SELECT minute_start, ad_id, sum(clicks), sum(spend_micros)
FROM live_minute FINAL
WHERE campaign_id = 7710 AND minute_start >= now() - INTERVAL 6 HOUR
GROUP BY minute_start, ad_id;
-- 2. A month by hour: closed hours, plus the open days' minutes
SELECT hour_start, ad_id, country, sum(clicks)
FROM closed_hour
WHERE campaign_id = 7710 AND hour_start >= '2026-10-09'
GROUP BY hour_start, ad_id, country;
-- the API adds query 1's shape, by hour, for the four open days
-- 3. Closing day D as a version cut at :cut_at, in effect
SELECT campaign_id, count(*) AS clicks, sum(cpc_micros) AS amount
FROM (SELECT click_id, argMin(campaign_id, clicked_at) AS campaign_id,
argMin(cpc_micros, clicked_at) AS cpc_micros,
argMin((ip, user_agent, served_at, clicked_at), clicked_at) AS first
FROM raw_clicks
WHERE toDate(clicked_at) = D AND archived_at <= :cut_at
GROUP BY click_id) -- copies first: one row per click ID
WHERE passes_inline_rules(first) -- then the rules, as in the stream
AND click_id NOT IN (SELECT click_id FROM invalid_clicks
WHERE click_day BETWEEN D - 7 AND D + 7
AND found_at <= :cut_at)
AND click_id NOT IN (SELECT click_id FROM billed_click_ids
WHERE day BETWEEN D - 7 AND D + 7 AND day != D
AND written_at <= :cut_at
UNION ALL
SELECT click_id FROM filtered_click_ids
WHERE day BETWEEN D - 7 AND D + 7 AND day != D
AND written_at <= :cut_at)
-- each day's latest version by :cut_at
GROUP BY campaign_id;
-- 4. Reconciliation for day D, by a job that reads both data stores
closed_days.amount_micros (version 1)
− sum(live_minute FINAL.spend_micros for day D), per campaign
Query 1 runs most often, because every open dashboard refreshes it. Query 3 is the one an interviewer pushes on, usually by asking what happens to a click that arrives after its day has closed. Section 4 answers that.
4. Bill from a recount
The stream's counts are provisional for three reasons, each from earlier sections. A click more than an hour late goes to a separate topic instead of its window. Fraud verdicts arrive days after the click. And the job's code can have a bug. Billing needs a number that counts the late clicks, leaves out the invalid ones and can be redone after a fix, once per campaign per day.
Bill from the live counts
Sum each campaign's minute rows at the end of the month and send that to invoicing. It needs no second system, and the stream's counts are exact for every click it saw in time.
It bills what the stream knew at the time, and the stream learns some things too late. Assume the fraud models flag 2 percent of a day's clicks in the 3 days after it. Billing from the live counts charges 200M × 2% = 4 million invalid clicks a day, $2 million, and every one comes back as a credit a month later. Clicks more than an hour late are never billed at all. And nothing independent ever checks the stream's numbers.
A nightly batch job recomputes each day
A second pipeline, such as a Spark job over the S3 archive, recomputes yesterday's counts every night and overwrites the stream's numbers. Billing reads the batch output. This is the Lambda Architecture: a fast layer and a correct layer, side by side.
Its costs are on record. Jay Kreps described the main one in 2014: "maintaining code that needs to produce the same result in two complex distributed systems". When the two disagree, nobody knows which one is wrong. And the Dataflow paper describes a Google team that ran a weakly consistent stream with a nightly MapReduce for truth. Its customers stopped trusting the stream's numbers, and the team rebuilt the system around strong consistency. A nightly run also comes too early, because a fraud verdict about Monday can arrive on Thursday.
One program, run twice, and versions after that
Question two premises: that the correct layer is separate code, and that a billed number is final.
Run the same Flink program over the archive. Flink's documentation says a bounded job produces "the same final results regardless of the configured execution mode". In batch mode it can assume perfect watermarks, so no click is late. The run for a day starts 72 hours after the day ends. That's long enough for click servers to ship what they held back, and for most fraud verdicts to land.
The run's start time is the version's cut_at, and it reads only clicks archived, verdicts found and IDs billed or filtered by then. Like the stream, it drops copies first and then applies the inline rules. It removes the invalid clicks, and any click ID already billed or filtered on another day within 7 days on either side, as the stream does. Then it writes closed hour and day rows, the click IDs it billed and those its rules filtered, and version 1 of each campaign's closed_days row. Closes run one at a time.
Looking both ways is what keeps a late first copy from being billed twice. Say click C1 belongs to day D but reaches the archive after D's cut, and its repeat C2 lands on D+1. D+1's close finds no billed copy, so it bills C2. When D is re-closed, C2's ID is billed on another day within 7 days, so C1 is left out, and the click is billed once.
A reconciliation job then compares closed against provisional, campaign by campaign. The stream is exact for every click it saw in time, so the two should differ only in known ways. There are clicks more than an hour late, and verdicts found after the stream counted. There are also retries that crossed into the other region, counted once in each region's stream (deep dive 4). late_events, the verdict files and the click IDs found in both regions' archives count each kind. Repeat requests should match, because both runs remember a click ID for 7 days.
So the job explains the difference, and alerts on any part it can't explain. Both runs are the same code, so that part points at what surrounds the job: a missing archive file, a shipper gap, or a crash the stream didn't recover from cleanly.
That also means reconciliation can't see a bug both runs inherit, in their shared code or in the click_id the click server wrote. Checks on the raw log can. A row whose click_id differs from its token_imp shows up in the archive the day the bug ships.
A late click or a verdict that lands after the close goes into a later version. A small job reads each new archive file and verdict file, and adds any closed day they touch, and the 7 days after it, to a days_to_reclose list. A daily run re-closes the listed days in date order, each with its own start time as its cut_at, so each one sees the IDs the day before it just wrote. That writes version 2. If the day has been invoiced, the difference goes on the next invoice.
Google Ads works this way for invalid traffic. Its help pages say invalid clicks found before the end of the billing cycle aren't charged, and those found after the invoice come back as a credit in the next cycle. Google's Mesa paper describes the same move inside the data: fraudulent clicks are offset by negative facts, applied in order after the clicks they cancel.
What you give up. A day's bill waits 72 hours, so the November invoice can't be cut before 4 December. Advertisers see provisional numbers move when a day closes, so the API labels them. And each re-close stores another version.
The question is how long to keep raw events, since the recount, every backfill and every dispute read them. S3 storage at the course's $0.023 per GB-month. Clicks a day 200M × 500 B = 100 GB a year 100 GB × 365 = 36.5 TB per month to keep a year 36,500 GB × $0.023 ≈ $840 Impressions a day 20B × 200 B = 4 TB a year 4 TB × 365 = 1.46 PB per month to keep a year 1,460,000 GB × $0.023 ≈ $33,600 Billed in a month $100M × 30 = $3B ───────────────────────────────────────────────────────── A year of raw clicks costs about $840 a month against $3 billion billed, so clicks are kept for the 13 months an invoice can be disputed. Impressions cost 40 times more and bill nothing here, so their raw events go after 90 days and only their counts stay.
Deep dives
Deep dives 1, 2 and 3 come up in most versions of this interview.
1. Late and out-of-order events
The stream job's watermark, its estimate of how far event time has got, trails the newest event time it has read by 30 seconds. Flink computes one per Kafka partition, and an operator's watermark is the smallest of its inputs'. The Dataflow paper names the two ways a watermark goes wrong, and this design meets both.
Too fast. A click arrives behind the watermark. Say a click server is cut off from Kafka for 2 hours, and ships its file when it reconnects. Every click in it is 2 hours old, while the other servers' clicks are current. Those clicks are behind the watermark, so they're late.
Too slow. One partition holds every window back. Say one subtask falls behind because its machine is slow. Its partition's watermark lags, and so does the watermark of every operator downstream of it. No window anywhere emits its final count. The Dataflow paper reports that a Google billing team "had significant issues with watermark lags caused by stragglers in their input".
Watch each partition's lag and alert on it. The early emissions every 10 seconds keep the dashboard moving while a window waits for its final count.
Now the clicks that arrive behind the watermark. Allowed lateness is how long a window keeps taking clicks after the watermark passes its end. Flink's default is 0, so late elements are dropped. This job allows an hour. A click up to an hour late still reaches its window, which emits a new count, and Flink's documentation says to treat that output as an updated result. Here that costs nothing extra, because the data store already keeps only the newest version of each row.
The two settings answer different delays. The 30 seconds covers the normal path, a flush, a shipper batch and Kafka, so that almost no click is late at all. The hour covers a shipper that restarts or a short Kafka outage, so that the dashboard still catches up by itself. Anything slower than that is rare, and waiting for it would keep every window, and every remembered impression ID, open longer, which deep dive 2 prices.
Past the hour, the job sends the click to a side output, a second stream for late data, which writes to a topic called late_events. The click is already in the archive, so the day's close counts it. The rate of late_events is a metric, because it measures the gap between what the dashboard shows and what the close will bill.
2. Dedup by click ID, and what the state costs
The duplicate check keeps every ID it has counted, in Flink's keyed state. Here keyed state lives in RocksDB, an embedded key-value store on the subtask's local disk, so it can grow past memory, and it is copied to object storage at each checkpoint. Because the check and the windows share one checkpoint, they're restored together: a click is either counted and remembered, or neither. Idempotency and exactly-once delivery explains why the record of what was seen has to live with the effect.
How long to remember an ID depends on which kind of copy the check has to catch. A redelivery keeps its original clicked_at. Once its window is past the hour of allowed lateness, any further redelivery is late and never reaches a window, so an hour covers redeliveries.
A repeat request is different. It gets a new clicked_at, so it arrives on time however long after the first click it comes, and only the ID check can stop it. So the length for clicks comes from a rule both runs apply: a click more than 7 days after its impression isn't billable. Each click ID stays until the watermark passes its impression's served_at plus 7 days and the hour.
Impressions aren't billed, so their IDs only have to catch redeliveries. Each is deleted when the watermark passes the end of its minute plus the hour, which is when its window is deleted too.
The question is how much state the duplicate check holds.
Assume about 50 bytes per entry in RocksDB, ID and
expiry included. The busiest hour is 2.5x an average hour.
Clicks, kept 7 days for repeat requests
200M × 7 × 50 B = 70 GB
Impressions, kept 1 hour for redeliveries
200,000/s × 2.5 × 3,600 ≈ 1.8B
1.8B × 50 B ≈ 90 GB
total ≈ 160 GB
Impressions kept 7 days instead
20B × 7 × 50 B = 7 TB
A Bloom filter for the clicks, 1% false yes
new clicks dropped from the live count
200M × 1% = 2M/day
─────────────────────────────────────────────────────────
Exact state is about 160 GB across the job. Impressions
kept for 7 days would be 7 TB. A Bloom filter would make
the live count about 1 percent low, every day.A Bloom filter would hold the click IDs in far less memory, and it loses no billed money, because the close counts exactly. But a false yes says "seen" about a new click and drops it from the live count. Pacing then reads spend about 1 percent low, and every reconciliation starts with a 1 percent gap that hides the smaller gaps it exists to find.
Google's Photon, which joins ad clicks to the searches behind them for billing, keeps click IDs for N days in a registry replicated across data centres. Its paper treats N as a trade between storage and dropping events delayed longer than that. Here the token rule sets N at 7 days, and the close drops IDs billed or filtered on other days within 7 days on either side, so the stream and the bill agree.
3. Hot ads and keys
Ad traffic is uneven. A launch campaign, a sports final or a celebrity's ad can take a large share of all impressions for an hour.
The design avoids hot keys in two places on purpose. Kafka topics are keyed by event ID, not by ad, so one ad's events spread over every partition. Message queues vs event streams explains why a key that orders events also pins them to one partition. Nothing here needs one ad's events in order, because windows sort them by event time. The duplicate check is keyed by event ID too, so it's even.
The window operator can't avoid a hot key, because it has to bring each key's events together.
The question is what one popular key does to the job.
The window operator runs as 128 parallel subtasks. Its
busiest key is one ad on one device in one country.
impressions at peak 1M/s
each subtask, if spread evenly 1M / 128 ≈ 7,800/s
the busiest key at 5% of all 1M × 5% = 50,000/s
→ one subtask gets 6 times the average, and its
backpressure slows every source that feeds it
Each subtask sums its events per key for 1 s, then shuffles
partial counts for the busy key 128 × 1/s = 128/s
─────────────────────────────────────────────────────────
50,000 events a second become 128 partial counts, at the
cost of one second of delay.A subtask that can't keep up makes Flink slow down the subtasks feeding it. This is called backpressure, and it lets one busy key slow the whole job. The fix is to sum before the shuffle, the step that sends each event to the subtask that owns its key. Each upstream subtask keeps a small map of counts per key for 1 second, then sends one partial count per key to the window operator, which adds the partials. It works because counts and sums can be added in any order. A distinct count couldn't be pre-summed this way, and would need a sketch.
4. How many servers, and what actually needs scaling?
The fleet follows the impressions, which outnumber clicks 100 to 1.
The question is which tiers grow with traffic and which are set by something else. Peak is 1M impressions and 10,000 clicks a second. Click servers, at 5,000 clicks/s each, below the course's 10,000 to 50,000 for trivial work, as headroom for the load 10,000 / 5,000 = 2 for failures 2 per zone, 3 zones, 2 regions = 12 Impression collectors, at 20,000 beacons/s each for the load 1M / 20,000 = 50 at 60% busy 50 / 0.6, rounded up = 84 Kafka in, at peak 1M × 200 B + 10,000 × 500 B ≈ 205 MB/s on disk, 3 copies ≈ 615 MB/s partitions for impressions = 256 each, at peak 1M / 256 ≈ 3,900/s Flink subtasks today = 128 duplicate-check state each 160 GB / 128 ≈ 1.25 GB ───────────────────────────────────────────────────────── Failure domains size the click tier, not traffic. The impression path sets the fleet.
The click servers and the collectors are separate fleets. A surge of beacons can then slow impression counting without slowing a single redirect.
The design runs in two regions. Each region has its own click servers, Kafka and stream job, and writes its rows with the region in the key. ClickHouse holds both regions' rows in each region, so either can serve every dashboard. The cost is a second copy of every ClickHouse row, sent across regions.
A click lands in one region's log, except when a browser retries into the other region after a failure. Then each region's stream counts it once. The close reads both regions' archives together, so it counts that click once, and the reconciliation counts how often it happens.
5. What happens when the stream job is down?
Clicks keep working. Click servers redirect and write their files, shippers fill Kafka, and the archive sink copies every event to S3, because none of them depend on the stream job. Kafka keeps 7 days, so an outage shorter than that is recovered by restarting from the last checkpoint and reading the backlog. A longer one is recovered from the archive in batch mode. Either way no click is lost. That is why the log comes first.
The dashboard stops updating. It shows the last counts the job emitted, so each response carries the watermark it was computed to, and the API shows "counted up to 14:05".
The consumer that suffers most is budget pacing in ad serving, which reads spend to stop a campaign at its budget. With stale spend, a campaign can keep running after its budget is gone. Uber's post names downtime of its aggregation job as its biggest reliability problem, because a delay can stall pacing and lead to overspend. Pacing belongs to ad serving. This design's part is to give every count its watermark, so pacing can slow a campaign when the data is old instead of trusting it.
6. Backfill after a bug
Say a click-server release starts taking the click ID from a field the client sends, instead of from the token. Some app versions put a fresh value in that field on every request. A double click or a browser retry now arrives under two IDs, and both are counted. That's the third click from the opening.
The raw-log check from section 4, a click_id that differs from its token_imp, flags this on its first day. Without that check, say it ran for 3 weeks and doubled 5 percent of clicks: 200M × 5% × 21 = 210 million extra clicks, $105 million, some of it already invoiced. The close counted them too, because both runs key on the click_id the click server wrote.
The fix starts with the archive, which holds every raw event. Each row still has the impression ID from its signed token, so the corrected job takes the click ID from token_imp again, and the copies collapse into one.
- Fix the click server, and version the job. The click server takes the ID from the token again. The batch job takes it from
token_imp, and its new job version goes into everyclosed_daysrow it writes. - Shadow write. Run the batch job over the 21 days, and the 7 after them, in date order into a separate table, each day reading the IDs the shadow run itself billed. Compare it with what was billed, campaign by campaign, writing nothing that's live. The 7 days after the bug are rerun so that a repeat crossing the fix is judged against corrected IDs. If you expect about 5 percent fewer clicks on the bug's days and see 40 percent, the fix is wrong.
- Publish new versions, in date order. Each affected campaign-day gets a new
closed_daysversion, and new versions of itsbilled_click_idsandfiltered_click_ids, so the next day's re-close excludes the corrected IDs. Days already invoiced get a credit on the next invoice, the same path as a late fraud verdict. - Leave open days to their close. The stream's rows for those days are too high, and the fixed job can't lower them, because the data store keeps the row with the larger
events_applied. The close counts those days correctly and replaces the provisional numbers.
The recount reads about 28 × 100 GB, 2.8 TB of clicks, from object storage, so it puts no load on Kafka or on the live job. Kafka keeps only 7 days, so it couldn't serve this replay anyway.
7. Click fraud, briefly
Fraud filtering happens in two stages, because some fraud is visible in one click and some only across weeks.
Inline, in the stream. Cheap rules run before the window. They catch a token used more than 7 days after its impression, and too many clicks from one IP address or device in a minute. They also catch an IP address in a data centre's published ranges, and a known bot's user agent. A click that fails is counted in the row's filtered_clicks column and not in clicks, so the advertiser sees what was filtered. Google's help pages say most invalid traffic is caught "shortly after the ad interaction".
Later, over the archive. Models look for patterns across days, such as one group of devices clicking many advertisers' ads in the same order. They write verdicts to invalid_clicks with a model version. Google says it also "analyzes traffic over longer time periods to find more complex patterns". The close reads the verdicts that exist when it runs, and a later verdict creates a new version and a credit.
A rule change is another run of the same query over the same log. The models themselves belong to fraud detection.
8. How do you know it is working?
During an incident you need four answers quickly: are clicks being lost, how far behind is the stream, how many clicks are arriving late, and does the close agree with the stream.
- Sequence numbers each click server reported that the archive never received, and the age of its oldest unshipped click. A missing number is a lost click. A growing age means a shipper or Kafka is stuck, and the disk is filling.
- Watermark lag per partition, the wall clock minus the partition's watermark. One partition far behind is the stalled subtask from deep dive 1.
- The
late_eventsrate. It's the part of tomorrow's bill the dashboard doesn't show. - The difference between closed and provisional money per campaign-day. Alert when it goes above its usual level. It's the only check that compares the stream with a second count.
Final design
One click, end to end:
- Ad serving creates an impression ID and signs it into the ad's click URL with the ad, the campaign, the price and the destination. The browser's impression beacon goes to a collector, which keeps it in its own local file and shipper.
- The user clicks. A click server checks the token's signature, appends the click to its local file with its server's next sequence number, waits for the group flush, and returns the 302. Every few seconds, it reports its highest number to monitoring.
- The shipper produces the click to Kafka's
clickstopic, keyed by click ID, withacks=allandmin.insync.replicas=2. An archive sink copies every event to hourly Parquet files in S3. - The stream job drops copies by ID, remembering click IDs for 7 days and impression IDs for an hour. It applies the inline fraud rules, sums each key's events for 1 second on each subtask, and adds them to one-minute windows by event time.
- Each window emits its whole count every 10 seconds, and its final count when the watermark passes, 30 seconds after the minute. Clicks up to an hour late update their window, and later ones go to
late_events. - ClickHouse keeps the row with the larger
events_appliedfor each key, and every read oflive_minuteusesFINAL. The dashboard reads minute rows for open days and closed rows for closed days, and each row says which it is. - Fraud models write verdicts to
invalid_clicks. 72 hours after a day ends, the same job runs in batch mode over that day's archive, up to itscut_at. It drops copies, then applies the inline rules, then removes invalid clicks and IDs billed or filtered on other days within 7 days either side. It writes closed rows, the billed and filtered IDs and version 1 ofclosed_days. The reconciliation compares closed with provisional. - Invoicing reads the closed versions. A later click or verdict puts its day on
days_to_reclose, a new run writes a new version, and the difference goes on the next invoice.
The numbers behind the shape: 20 billion impressions and 200 million clicks a day, $100 million billed. The impressions set the fleet, about 84 collectors and 256 partitions, and 12 click servers are there for failure domains. The duplicate check holds about 160 GB, 7 days of click IDs and an hour of impression IDs, and a year of raw clicks costs about $840 a month to keep.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth at this level, and it's fine to be led.
You should route clicks through a redirect, put them on Kafka, count them per ad per minute in a stream processor, and serve the counts from a column store. You should say why a duplicate click is a problem and give each click an ID to drop copies by.
You aren't expected to raise watermarks, transactional sinks or versioned invoices without being asked. You are expected to answer sensibly when asked "a click arrives 5 minutes late, which minute does it count in?"
Senior
You drive the structure, and three things should come up without prompting.
Where the click is safe before the redirect. Say what happens to clicks when Kafka is down, and price it.
Event time, a watermark and allowed lateness. Say which minute a late click counts in, and where it goes when it's later than you allow.
How a count survives a crash. Name the mechanism, a checkpoint with a transactional sink or idempotent writes of whole counts, and what it costs in freshness.
Two things are disqualifying: counting by processing time for a billed number, and claiming Flink's exactly-once covers clicks that never reached Kafka.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
Make the log the source and the counts queries over it. Then a late click, a fraud verdict and a bug fix are each another run, not a migration.
Bill from a second run of the same program, made 72 hours after the day, and close each day as a version so a later correction becomes a credit, not an edit.
Write whole counts with a version, so delivery can be at-least-once and freshness doesn't wait for checkpoints.
Size the duplicate check by the copies it must catch: 7 days of click IDs for repeat requests, an hour of impression IDs for redeliveries, about 160 GB.
Be able to say what you would not build. No transactional sink when the data store can keep the larger version. No second codebase for the batch layer. No click-ID registry replicated across regions, when the close catches the rare retry that crosses them. No Bloom filter in the duplicate check. No fallback path that runs only during outages. A team could spend a quarter on any one of these.
Sources
Every figure about a real system above was read for this page in one of these. The traffic, prices and fleet sizes are assumptions, worked through in the worksheets.
- Akidau et al., The Dataflow Model, VLDB 2015. Event time against processing time, and watermarks that are too fast or too slow. Discarding and accumulating output, the billing team held back by stragglers, and the customers who stopped trusting a weak stream with a nightly batch.
- Ananthanarayanan et al., Photon: Fault-tolerant and Scalable Joining of Continuous Data Streams, SIGMOD 2013. Joining Google's ad clicks to their queries for billing, and the registry of click IDs kept for N days.
- Gupta et al., Mesa: Geo-Replicated, Near Real-Time, Scalable Data Warehousing, VLDB 2014. Google's ad reporting warehouse, and fraudulent clicks offset by negative facts in update order.
- Uber Engineering, Real-Time Exactly-Once Ad Event Processing with Apache Flink, Kafka, and Pinot, 2021. One-minute windows keyed by ad and minute, 2-minute checkpoints with a transactional Kafka sink, Pinot upserts, the volume of hundreds of millions of events a week, and aggregation-job downtime as the main reliability risk.
- Apache Flink documentation: timely stream processing, generating watermarks, windows, the Kafka connector, execution mode and state TTL, plus the project's post on end-to-end exactly-once with two-phase commit. Watermarks per partition, allowed lateness and side outputs, and delayed visibility with the exactly-once sink. The same results in batch mode with perfect watermarks, and TTL in processing time only.
- Jay Kreps, Questioning the Lambda Architecture, O'Reilly, 2014. The cost of keeping two systems that must produce the same result.
- Data store documentation: ClickHouse's ReplacingMergeTree and REPLACE PARTITION, Pinot's upsert and its memory estimate, and Druid's rollup, best-effort in streaming ingestion.
- Google Ads Help, About invalid traffic and Issues with clicks and clickthrough rate. Invalid clicks caught before the billing cycle ends aren't charged, those found later are credited in the next cycle, and no more than 2 clicks are charged per ad impression.