GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design an Ad Click Aggregator (Google Ads)

Send each tap to the shop in milliseconds, count a click once however many times it arrives, keep a halftime ad from stalling every dashboard, fix a minute after it was written, and bill from a recount you can explain. Built one step at a time, with experiments you can run.

An ad click aggregator records every click on an ad and counts them, so advertisers can watch their ads perform and pay for the clicks. The ad links to a redirect server, which checks the link’s signature, appends the click to a Kafka log and sends the browser on to the shop. A Flink job counts in two stages: the first, keyed by the ad and a slice of the impression ID in the link, drops repeated clicks and sums each second; the second, keyed by ad, adds up each minute. Each minute’s whole total goes to a ClickHouse table that keeps the largest total for each ad and minute, so a late click or a replay after a crash replaces the row instead of adding to it. Reports read hour and day rows built from settled minutes. Every click is archived in S3, and each night a Spark job recounts the day with the fraud rules and writes the counts invoices are built from.

Difficulty: Medium. Reported in interviews at Meta, Rippling, Snapchat, Google, Stripe. Also asked as Design an ad click counter, Ad click event aggregation, Design real-time ad analytics, Design Google Ads click counting.

Practise one part of it on a canvas that tests your design: Count Ad Clicks Exactly Once.

How do you design an ad click aggregator?

An ad click aggregator records every click on an ad and counts them, so advertisers can see how their ads perform and pay for the clicks. When someone taps an ad, their browser passes through the aggregator’s server on the way to the advertiser’s site, and the click is recorded there. The aggregator turns billions of those records a day into two things. One is counts per ad per minute, which a dashboard shows within two minutes. The other is a daily count, which an invoice is built from. Counting clicks on a laptop takes a hash map. Two billion a day is a different problem. Clicks arrive twice and arrive late, one ad can suddenly take more than a quarter of all traffic, and money rides on the result.

  1. Tapped: Theo taps a shoe ad. The shop must open at once, and the click must be recorded where nobody can block or fake it.
  2. Recorded once: imp-81f2: 3 records. A lost reply and a second tap send one click three times. The advertiser pays for one.
  3. Counted: 19:03: 412 clicks. One ad in a halftime break can bring 20,000 clicks a second to whoever counts it.
  4. Reported: Rosa: 90 days by day. A minute can change after it was written, and a report must not count it twice.
  5. Billed: Tuesday: 12,105 clicks. The invoice comes from a recount that has seen the whole day, and says why it differs.
One click, start to finish. The system does this about 23,000 times a second on average.

Picture Rosa, who runs marketing for a small trail-running shop and pays for each click on her ads. On Tuesday at 19:02 Theo, on a train, taps her ad for trail shoes. He expects the shop to open at once. Rosa expects to see his click on her dashboard within a couple of minutes, and to pay for it once, however many times his phone sent it. At the end of the month she expects an invoice she can check line by line.

Interviewers like this problem because the first answer is short: redirect, write to a log, count per minute, store the counts. The rest of the round is about what that answer does to the shopper when the log is slow. It is also about what it does to the money when a click arrives twice, arrives late, or should never have been billed.

In brief, the ad links to a redirect server. The server checks the link’s signature, appends the click to a Kafka log, and sends the browser on to the shop. A Flink job counts in two stages. The first, keyed by the ad and a slice of the impression ID in the link, drops repeated clicks and sums each second. The second, keyed by ad, adds up each minute. Each minute’s whole total goes to a ClickHouse table, and a report API reads it, rolled up into hours and days. Every click is also archived in S3. Each night a Spark job recounts the day with the fraud rules and writes the numbers invoices are built from.

The rest of this page is about the moments that design has to survive.

The first is a tap during an outage. A redirect that writes to a database before it answers makes every shopper wait for the database. When the database is unreachable, Theo stares at a blank tab for two seconds and then lands on the shop uncounted.

The second is a crash. A job adds late clicks to a minute with clicks = clicks + 19, then + 9, and crashes. When it replays, it adds all the late clicks again. The row says 478 for 450 real clicks, and Rosa’s dashboard shows 28 clicks nobody made.

What is the interviewer testing?

Most candidates reach a working answer quickly: a redirect that writes to Kafka, a stream processor that counts per minute, and an analytics database for reports. That answer is right, and a mid-level answer often stops there.

The interviewer then pushes on each piece. The log is unreachable. A click arrives three times. One ad gets more than a quarter of all clicks. A minute changes after it was written. A report spans three months. The invoice disagrees with the dashboard. A senior answer deduplicates by impression, keeps minutes open for late clicks, and rolls reports up. A staff answer also splits a hot ad across two stages, writes whole totals so a replay is harmless, and bills from a recount that keeps its reasons.

Spend most of the deep-dive time on deduplication, on late and repeated writes, and on the recount. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

What counts as one click?
Assume a tap that reaches our redirect with a valid link, and at most one billable click for each time an ad is shown. A retry, a double tap or a second tap on the same showing is the same click.
Does the dashboard bill?
Assume not. The dashboard is at most about two minutes behind and says its numbers are provisional. Invoices come from a count built each night, with rules that need the whole day.
Which reports?
Clicks per ad or campaign, by minute, hour or day, split by country and device, over any range up to 90 days. Assume nothing else is counted ahead of time.
Do we detect fraud?
Assume a fraud team owns the rules. The design keeps every record, applies their rules in the nightly count, and credits clicks they reject later.

Functional requirements

On the board: Functional requirements
1. Tap → 302 to the shop; record the click
2. Clicks per ad: minute, hour, day, ≤ 90 days
   split by country and device
3. Billable clicks and cost per ad per day
out: fraud rules, the auction, impressions

Say it, don’t write it: The count itself is simple. The hard part is counting each click once, fast enough for a dashboard and exactly enough for an invoice.

Two groups use the system. Shoppers never see it. They tap an ad and land on a shop, and the only thing they notice is delay, so the redirect must answer quickly with a 302. Advertisers read it. They watch clicks on a dashboard, pull reports, and pay invoices built from it.

  1. When a shopper taps an ad, send them to the ad’s page with a 302, and record the click.
  2. Show each advertiser clicks per ad by minute, hour or day, split by country and device, over any range up to 90 days.
  3. Produce a billable count and cost per ad per day, for invoices.

Out of scope

  • The auction that chooses which ad to show and sets its price
  • Fraud rules and models, which a fraud team owns; the design applies them
  • Impressions and click-through rate, beyond a short section at the end
  • Budgets, beyond a short section at the end
  • Conversions, meaning what the shopper did after landing

Non-functional requirements

On the board: Non-functional requirements
• 2B clicks/day ≈ 23k/s; peak 70k/s
• One ad can take 20k/s in a live ad break
• Counting adds ≤ 50 ms to a redirect, p99
• Dashboard ≤ 2 min behind, marked provisional
• Each click billed once; days final nightly
• A 90-day report in under 1 s

Say it, don’t write it: The shopper must never wait on the count, and the invoice must never trust the fast count.

  • About 2 billion clicks a day: about 23,000 a second on average, and 70,000 at the evening peak.
  • One ad can take 20,000 clicks a second, for example in a live broadcast’s ad break.
  • Counting adds at most 50 ms to a redirect at the 99th percentile (p99), and the redirect keeps working when counting is down.
  • Dashboards are at most 2 minutes behind, and say their numbers are provisional.
  • Each click is billed once. Each day’s billable count is final after a nightly recount, with a reason for every difference.
  • A report over 90 days returns in under a second, 1 s.

Two numbers are worth working out now, because each decides a piece of the design. The first is the write rate. 2,000,000,000 clicks ÷ 86,400 seconds is about 23,148, so about 23,000 a second. The evening peak is about three times that, 70,000. A database insert per click would put 70,000 inserts a second on the shopper’s path. So the redirect appends to a log, which is built for that rate, and the counting happens after the shopper has gone.

The second is the size. A click record is about 250 bytes: IDs, the ad, the time, the price, the country, the device, the address and the browser. Two billion a day is 2,000,000,000 × 250 bytes = 500 GB a day, and 17.5 MB a second at the peak. Keeping every record for a recount is cheap in object storage and expensive in a database. So the records go to S3, and databases hold only counts.

The other numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any real ad platform.

Core entities

On the board: Core entities
Click(impression, ad, time, price, …)
AdMinute(ad, minute, country, device
         → clicks, cost; largest wins)
AdDay(ad, day, … → clicks, cost, final?)
BillingLine(ad, day, clicks, reasons)
Credit(billing line, clicks, rule)

Say it, don’t write it: A click is the fact. Every count is derived from clicks, and a billing line never changes once it is on an invoice.

Follow Theo’s click through the records. His tap carries impression imp-81f2, Rosa’s ad, the price the auction set for that showing, and the time our server received it, 19:02:07. That is the Click. The counting job adds it to Rosa’s ad for minute 19:02, under his country and device. That is an AdMinute. It may be written more than once, each time with a larger total.

At 03:00 the next day, the recount writes Tuesday’s AdDay rows and marks them final. It also writes a BillingLine that records why the final count differs from the live one. If fraud is found later, a Credit points back to that line.

RecordWhat it holdsWhy it is separate
ClickImpression ID, ad, advertiser, time, price, country, device, address, browserThe only fact; every count can be rebuilt from clicks
Ad minuteOne ad, one minute, one country and device: clicks and costWritten again when late clicks arrive; the largest total wins
Ad hour, ad dayThe same, summed from settled minutes; a day row is marked final by the recountWhat reports over weeks and months read
Billing lineOne ad, one day: clicks, cost, and why it differs from the live countWhat an invoice is built from; never changed once sent
CreditA billing line, the clicks found invalid, the rule that found themHow a later finding reaches the next invoice

The one distinction that matters: a click record must never be lost, but every count can be rebuilt from clicks. A billing line is the exception in the other direction. Once an invoice has used it, it is never changed, only credited.

API

On the board: API
GET /c/{token}  → 302 to the ad’s page
token = sign(impression, ad, price, expiry)
GET /reports?ads=&from=&to=&grain=day
  → {rows: [{ad, t, clicks}], final_through}

Say it, don’t write it: The click endpoint is a plain link, so there is nothing in the browser to block. The advertiser comes from the session, never the query.

The shopper’s browser calls one endpoint, and advertisers call one.

CallReturnsWhy it looks like this
GET /c/{token}A 302 with the ad’s landing pageA plain link works in every browser and app, with no script to block
The token: impression ID, ad ID, price, expiry, signatureNothing; the server checks itSigned with a key only our servers hold, so it cannot be forged or edited
GET /reports?ads=…&from=…&to=…&grain=dayRows of ad, time and clicks, and final_throughThe advertiser comes from the signed-in session, never from the query
&split=country,deviceThe same rows, split by those fieldsOnly the promised fields are counted ahead of time

Two fields in the token exist for a reason. The impression ID means a retried request carries the same ID as the first, so the counting job can recognise it. And the price is there because each click is billed at the price the auction set when the ad was shown. The redirect has no other way to know it.

The report carries final_through, the last day the nightly recount has replaced. A reader who sees Tuesday marked final knows it matches the invoice. Today’s rows are provisional, and the dashboard shows them that way.

Step 1: record the click on the way to the shop

Start with the tap. The ad on the page links to /c/{token} on our redirect servers. A server checks the token’s signature and expiry, stamps the time it received the request, and appends the click to a Kafka topic called clicks. It answers with a 302 once Kafka has written the click to at least two of its three replicas (acks=all with min.insync.replicas=2). The first deep dive covers what happens when Kafka is slow to answer. The browser follows the 302 to the ad’s landing page, which the server looked up from the ad’s own record.

Kafka only adds to the end of a log, which is what makes it fast. The topic is split into partitions across brokers, and the server picks a partition by hashing the impression ID, so clicks spread evenly. Kafka keeps clicks for 7 days, long enough to replay anything the counters lose.

The interactive version of this example is available when JavaScript loads.

Nothing is counted yet. The log is the record of what happened, in the order it arrived.

Step 2: count clicks per ad per minute, and serve reports

A Flink job reads the log. Flink is a stream processor: it runs the same code on many tasks in parallel and sends each record to a task chosen by a key. Here the key is the ad ID, so every click on one ad reaches the same one of 64 counting tasks. A task keeps a seen-set of impression IDs, so a repeated click is not counted twice. The deduplication deep dive explains why that ID is the right one. The task adds each new click to its ad’s count for the current minute, under the click’s country and device, in memory.

Each minute the task closes the minute. Flink tracks a watermark, its estimate of how far click time has progressed. Here the watermark trails the newest click by 30 seconds. So minute 19:02 closes once clicks from 19:03:30 have arrived. The task writes one row per ad, country and device for the minute into a ClickHouse table. The report API reads that table for the advertiser who is signed in, and the dashboard asks again every 30 seconds. So a click shows up at most about two minutes after it happens.

The interactive version of this example is available when JavaScript loads.

ClickHouse is a columnar analytics database. It stores each column separately and reads only the columns a query names, which suits sums over many rows.

Step 3: keep every click, and recount each day for billing

Kafka keeps clicks for 7 days. A connector also copies every record into files in S3, one folder per hour, kept for as long as an invoice can be questioned. At 03:00 each night a Spark job reads yesterday’s files. It removes repeated clicks across the whole day, applies the fraud team’s invalid-traffic rules, and sums clicks and cost per ad. It writes the billing lines to PostgreSQL, where invoices are built. It also writes yesterday’s day rows to ClickHouse, marked final.

This is the part of the design that makes the money trustworthy. The stream is fast. The archive and the recount are what anyone can check.

The interactive version of this example is available when JavaScript loads.

With ordinary traffic this is already a working aggregator. The deep dives take it through an outage at the redirect, a click that arrives three times, a halftime ad, a minute that changes after it was written, a 90-day report, and an invoice that disagrees with the dashboard.

How do you count a click without making the shopper wait?

On Tuesday at 19:02 Theo is on a train, scrolling a sports site on his phone. He taps an ad for Rosa’s trail shoes. Two things must happen. His browser must reach Rosa’s shop quickly, because a shopper who waits on a blank tab often gives up. And the click must be counted, because Rosa pays for it.

The first design many people draw counts the click in the page. The ad links straight to the shop, and a small script sends a ping to a collector as the page unloads. Browsers have a call for exactly this, navigator.sendBeacon, which sends the ping “without delaying unload or the next navigation” (MDN). Theo reaches the shop without waiting.

The trouble is who controls the ping. It runs in Theo’s browser. An ad blocker drops it. A script can send a million of them without clicking anything. And nothing about a ping proves that a person reached the shop. The shopper can arrive with no record, or a record can arrive with no shopper.

The second design moves the count onto our server. The ad links to a redirect server, which inserts a row for the click in a database and then answers with a 302 to the shop. Now there is no separate request for a blocker to drop. A blocker can still hide the ad or refuse the link, but then there is no visit either. The count and the visit succeed or fail together.

Now the database is in Theo’s path. At the evening peak it takes 70,000 inserts a second, and when it is slow, every shopper is slow. Say it becomes unreachable, and the redirect gives up after two seconds. Theo stares at a blank tab for two seconds and then lands on the shop uncounted. The count has become a way for the shop to lose customers.

The fix keeps the redirect and changes what it waits for. The server appends the click to the Kafka log and answers 302 as soon as the log confirms. The broker adds the record to the end of a file that is already open and waits for one more replica to copy it. Within one region, that confirmation usually takes a few milliseconds. At the peak it is 70,000 appends and 17.5 MB a second, spread over many partitions and brokers, which is ordinary work for a Kafka cluster. Theo waits for one append.

Then the log itself is the thing to plan for. Suppose a network fault cuts one zone’s redirect servers off from Kafka for four minutes, from 19:02 to 19:06. Theo’s tap happened to reach a server in another zone. A shopper whose tap lands in the cut-off zone must not wait four minutes. So a server waits 50 ms at most. If the log has not answered by then, the server writes the click to a file on its own disk, called a spool, and redirects anyway. When the fault ends, the server sends the spool to the log. That shopper waited 50 ms, and the click reached the log four minutes late.

The spool is the fix for an outage, whatever sits behind the redirect. A redirect that writes to a database first could time out and spool as well. What the log adds is a store built for 70,000 appends a second in the first place.

The spool also trades one risk for another. A click in the spool lives on one machine’s disk, so the server flushes it to the disk before redirecting. If that disk dies before the log comes back, the click is lost; the alternative was losing the shopper. Each server reports how many clicks sit in its spool, and an alert fires when a spool grows. And if an append did succeed after all, and only its confirmation was slow, the click reaches the log twice. Both copies carry the same impression ID, which the next deep dive shows is harmless.

A click that reaches the log four minutes late also creates a problem for the counts. The minute it belongs to may already be written. The deep dive on late minutes picks that up.

The token in /c/{token} is what makes the redirect safe to put on the internet. It carries four things: the impression ID, the ad ID, the price and an expiry. The impression ID names this one showing of the ad. Our servers sign the token with a key only they hold, and check the signature before counting anything, so a forged or edited token is never counted. The destination comes from the ad’s own record, which each server keeps in memory, looked up by the ad ID. It never comes from the link. Otherwise anyone could use our domain to send people to any site they chose, a hole called an open redirect.

The experiment sends three taps through each design: an ordinary one, one with an ad blocker, and one during the four-minute fault. The tabs are a ping from the page, a database write before the redirect, and a log append before the redirect.

The interactive version of this example is available when JavaScript loads.

The gap: The shopper must reach the shop quickly, and the click must be recorded where nobody can block or forge it.

Option 1: A ping from the page

The ad links straight to the shop, and a script sends a beacon as the page unloads.

Works when: Site analytics that can live with some pings missing.

Breaks when: An ad blocker drops the ping and a script can forge it, so nothing billed can rest on it.

Option 2: Write to a database, then redirect

The redirect server inserts a row, then answers 302.

Works when: A few clicks a second.

Breaks when: Every shopper waits on the database, and an outage costs the shop its visitors.

Option 3: Append to a log, then redirect (start here)

Wait for one Kafka append, at most 50 ms, and spool to local disk if the log does not answer.

Works when: Always, for clicks that are billed.

Watch for: A spooled click lives on one disk until the log returns, and it arrives late for its minute.

In the interview: Open with option 3, and say what it waits for: one append, at most 50 ms. Mention option 1 to explain why the count lives on the server. If the interviewer takes the log away, describe the spool and what it costs.

Say this: The ad links to our redirect server, so the click is recorded on a machine we control, where no blocker can drop it separately from the visit. The server appends the click to Kafka and answers 302 once the log confirms, which is a few milliseconds. If the log does not answer in 50 ms, it spools the click to local disk and redirects anyway, so an outage costs a late count, never a lost shopper. The link is signed, and the destination comes from the ad’s record, so it cannot be forged or turned into an open redirect.

One tap arrives three times. Which records are the same click?

Go back to Theo’s tap at 19:02:07. His train enters a tunnel just as our server answers, and the 302 never reaches his phone. Nothing happens on his screen, so at 19:02:08 he taps the ad again. This time he lands on the shop. He goes back to the sports page, which is still open with the same ad on it, and taps it again at 19:02:31. That is three records in the log. How many clicks should Rosa pay for?

Counting records says three. That bills Rosa for a tunnel and a back button. Theo meant to visit her shop once.

The next idea groups records that look alike: one click per IP address, per ad, per minute. Theo’s three records share an address and a minute, so they become one. It works for Theo.

Now take an office at 19:15. Ana, Ben and Cleo work together, and each sees the ad on their own screen and taps it. The office reaches the internet through one public address, 203.0.113.9. All three taps share an address, an ad and a minute, so the rule keeps one. Two real people who visited Rosa’s shop are thrown away. A rule built from what records have in common cannot tell a repeated tap from a colleague.

The fix is to count the thing the product sells. Our rule is at most one billable click for each time an ad is shown. Each showing is called an impression. The ad server gives every impression a random ID, and the ID goes into the signed link.

Theo’s three taps all carry impression imp-81f2, so they are one click. Ana, Ben and Cleo each saw the ad on their own screen, so their links carry three different impression IDs, and they are three clicks. At 19:40 Theo sees the ad again, on another page. That is a new impression, imp-9c04, and a new click. Seven records make five clicks, and they are the right five.

Someone has to remember which impressions have already been clicked. Many redirect servers take traffic, and the tap at 19:02:08 may reach a different server from the first. No redirect server can remember alone. The counting job can. Every record for one impression carries the same ad, and the job keys clicks by ad, so all three of Theo’s records reach the same task. That task keeps a seen-set: the IDs of impressions it has already counted. A record whose ID is in the set stays in the archive and is left out of the count.

The set needs a limit, and the signed link supplies one. The token expires 24 hours after the ad is shown, and the redirect never counts an expired token. So no impression can produce a counted click more than 24 hours after it was shown. An ID can therefore leave the set 24 hours after its first click.

At 2 billion clicks a day, the set holds about 2 billion IDs. Each takes about 40 bytes: 16 for the ID and the rest for the store’s own overhead. That is about 80 GB, or 1.25 GB for each of 64 tasks. Flink keeps it in RocksDB, an embedded store on each task’s local disk, and a time-to-live on the state removes old IDs. Flink measures that time on its own clock, from when it stored the ID. A spool that sat on a disk for more than a day could slip a repeat through. The nightly recount checks across two days and catches it.

Teams often reach for Redis or a Bloom filter here instead, and both fail. The first failure depends on how Flink recovers from a crash. Every few seconds it saves a checkpoint: a snapshot of every task’s state, together with how far each task has read the log. After a crash it restores the last checkpoint and reads forward from there.

A shared Redis set would record each ID with SET imp-81f2 1 NX, which succeeds only if the key is new. The check then lives outside the counting job. Suppose the job counts Theo’s click, marks it in Redis, and crashes before its next checkpoint. After the restart it reads the click again, finds the ID in Redis, and drops it. The count has lost a click, because the count rolled back and the mark did not. A seen-set inside Flink’s state is saved and restored together with the counts, so the two always agree.

A Bloom filter fails differently. It holds the set in far less memory. It answers either “definitely new” or “maybe seen”. Dropping every “maybe” at a 1% false positive rate throws away about 1% of new clicks, 20,000,000 a day at this size. For a count that bills, every “maybe” has to be checked against exact state. Then the exact set has to exist anyway, and the filter only saves lookups for IDs it is sure are new.

The experiment runs the seven records through three rules. The tabs are counting every record, one click per address, ad and minute, and one click per impression.

The interactive version of this example is available when JavaScript loads.

The gap: A repeated tap, a second tap and a different person can all look alike, and only one of them is a new click.

Option 1: Count every record

Each record in the log is a click.

Works when: Nowhere money depends on it.

Breaks when: A tap in a tunnel or a second tap on the same ad bills the advertiser again.

Option 2: One click per address, ad and minute

Group records that share an IP address, an ad and a minute.

Works when: As a fraud signal, reviewed later.

Breaks when: Colleagues behind one office address become one click.

Option 3: One click per impression ID (start here)

The signed link carries the impression ID, and the counting task keeps a seen-set of IDs for 24 hours.

Works when: Always, when the ad server gives each showing an ID.

Watch for: The set is about 80 GB, so it lives in checkpointed state on disk, not in a separate store.

In the interview: Open with option 3, and give the product rule first: one billable click per impression. Show option 2 failing on the office example. If the interviewer offers Redis or a Bloom filter, say what each loses: agreement with the count after a crash, or real clicks.

Say this: A click’s identity is the impression it came from, so the signed link carries the impression ID, and a repeated tap on the same showing carries the same one. Every record for one impression lands on one counting task, which keeps a seen-set of IDs in Flink state. The link expires after 24 hours, so the set is bounded, about 80 GB across the job. It lives in checkpointed state, so after a crash the set and the counts roll back together.

One ad gets 20,000 clicks a second at halftime. Why does every dashboard fall behind?

On Sunday at 19:47 a football final reaches halftime. A sports brand has bought the ad in the break, and for three minutes it takes 20,000 clicks a second. The rest of the platform is at its evening peak, 70,000 clicks a second in all. Rosa’s ad has nothing to do with football. Her dashboard is about to fall behind anyway.

The counting job keys clicks by ad, so every click on one ad reaches one of 64 tasks. That was deliberate: one task holds the ad’s whole count and its seen-set. Do the arithmetic for the halftime ad. The other ads bring 70,000 − 20,000 = 50,000 clicks a second. Spread over 64 tasks, that is about 781 each. The task that owns the halftime ad gets its 781 plus all 20,000, about 20,781 a second. That is about 27 times the load of any other task.

Suppose one task can check and count about 5,000 clicks a second. That figure is an assumption for the arithmetic; measure your own. The hot task falls behind by 20,781 − 5,000 = 15,781 clicks every second. After three minutes, 15,781 × 180 is about 2.84 million clicks waiting for it. Once the break ends, it clears them at 5,000 − 781, about 4,219 a second. That takes about 11 more minutes.

Rosa’s dashboard suffers because every task that reads the log sends clicks to all 64 counting tasks. When the hot task cannot keep up, its input fills, and the readers must wait before they can hand it more. Flink calls this backpressure, and it “is propagated in the opposite direction, up the stream” (Flink). A reader waiting on the hot task reads nothing, so every other counting task receives clicks only as fast as the hot one drains them. The watermark comes from those readers, so it slows too, and every ad’s minutes from 19:47 on close late. For about 14 minutes, every advertiser’s dashboard is stuck behind one ad.

The number that shows this is consumer lag: how far the job trails the end of the log. It is the first thing to alert on.

The log itself is not the hot spot. It is partitioned by hashing the impression ID, so the halftime clicks are spread evenly across Kafka’s partitions and brokers. Partitioning the log by ad ID would have put 20,000 appends a second on one partition as well. The hot spot is the one place where every click on an ad must meet: the task keyed by ad.

Adding tasks does not help, because one ad goes to one task however many there are. The fix is to count in two stages, the standard cure for a hot key.

The first stage keys each click by its ad and a number from 0 to 63 taken from its impression ID, called its slice. Every copy of one impression has the same ad and the same slice, so the copies still meet on one task. The seen-set moves here and still works. But one ad is now 64 keys, spread over the 64 tasks by hashing. Each task gets roughly 70,000 ÷ 64 ≈ 1,094 clicks a second, whatever is popular. Each key adds up the clicks it counted in each second and sends one sum, such as “halftime ad, 312 clicks, minute 19:47”. The second stage keys those sums by ad and adds them into their minute.

Replay halftime. Each slice carries about 20,000 ÷ 64 ≈ 312 of the halftime ad’s clicks a second, and sends one sum for them. The ad’s counting task receives at most 64 sums a second for it, one for each slice, instead of 20,000 clicks. No task comes near 5,000 a second. The minutes close on time, and Rosa’s dashboard never notices the football.

The cost is up to one more second of delay, for the per-second sums, and one more hop across the network. An ad clicked once a second gains nothing from the first stage and loses nothing either: it sends a sum of 1. The top K breakdown walks the same two stages for a song released at midnight. Here the first stage has a second job, deduplication, which is why its key comes from the impression ID and not from a random number.

The interactive version of this example is available when JavaScript loads.

The experiment plays the three minutes of halftime twice. The tabs are counting tasks keyed by ad, and a first stage keyed by ad and slice in front of them.

The interactive version of this example is available when JavaScript loads.

The gap: Every click on one ad must meet in one place to be counted, and one ad can bring more than a quarter of all clicks.

Option 1: Key by ad

One task per group of ads checks and counts every click.

Works when: Traffic spread over many ads.

Breaks when: The halftime ad’s task carries about 27 times the load, and backpressure makes every minute wait for it.

Option 2: Key by ad and impression slice, then by ad (start here)

The first stage deduplicates and sums each second; the second adds each ad’s sums into the minute.

Works when: Once one ad can outrun one task.

Watch for: Up to a second more delay, and one more network hop.

Option 3: Split only the hot ads

Detect hot ads and spread only those over several keys, such as the ad plus a number from 0 to 7.

Works when: The extra second of delay matters for every other ad.

Watch for: An ad must be detected as hot before it hurts, and the copies of one impression must still meet.

In the interview: Open with option 2, and earn it with arithmetic: one task at 20,781 a second against 781 for the rest. Then point out that the key the deduplication needs already spreads the load, so the fix costs one per-second sum. Offer option 3 if the interviewer asks to keep ordinary ads a second fresher.

Say this: Keyed by ad, a halftime ad at 20,000 clicks a second lands on one task, about 27 times the load of the others. Backpressure then slows the readers feeding every task, so every dashboard falls behind. So the first stage keys by the ad and a slice of the impression ID, which spreads the ad over 64 keys and keeps deduplication working, and sums each second. The second stage keys those sums by ad, so a hot ad costs its counter at most 64 sums a second.

A minute’s count changes after it was written. How does the table end up right?

Back to the network fault from the first deep dive. From 19:02 to 19:06, one zone’s redirect servers could not reach the log, and they spooled clicks to disk. Everyone else’s clicks kept flowing, so the watermark kept moving. It trails the newest click by 30 seconds, so minute 19:03 closed once clicks from 19:04:30 had arrived. The job wrote Rosa’s ad for 19:03: 412 clicks.

At 19:06 the fault ends. Three servers send their spools a few seconds apart, carrying 19, 9 and 10 clicks for Rosa’s ad at 19:03. The true count is 412 + 19 + 9 + 10 = 450.

The simplest job writes each minute once, when it closes, and drops anything later. Flink’s windows do exactly this by default: “late elements are dropped when the watermark is past the end of the window” (Flink). Rosa’s dashboard says 412 for 19:03 until the nightly recount.

So keep the minute open for late clicks. Flink’s windows call this allowed lateness. A late click that arrives within the allowance is added to its minute, and the minute is sent again with its new total. Allow an hour. A click later than that goes to a side output, a separate stream of rejects, and the nightly recount counts it from the archive. The counting task gathers late sums for five seconds before it sends a minute again, so each spool becomes one write: 431, then 440, then 450.

Now the job must change a row it already wrote. The obvious write adds the difference: clicks = clicks + 19, then + 9. The row says 440. Then the job crashes before its next checkpoint, with the third spool not yet counted. Flink restores the last checkpoint, which was taken before any late clicks, and reads all 38 again. It adds 38. The row says 478, for 450 real clicks. An increment is safe only if it happens exactly once, and a replay makes it happen twice.

The fix starts with writing totals, not differences. Every time the job sends a minute, it sends the whole count: 412, 431, 440, 450. The table then needs a rule for which of those rows is current.

The obvious rule is a write number: the job numbers each write, and the table keeps the highest. A replay breaks it. Before the crash the job sent 431 as write 2 and 440 as write 3. The replay reads all 38 late clicks within a few seconds, gathers them into one write, and sends 450 as write 2. Write 3 beats write 2, and the table shows 440. The numbering depended on how the late clicks happened to be grouped, and a replay groups them differently.

So the table keeps the largest total for each ad, minute, country and device. The stream only ever adds clicks to a minute, so a bigger total has seen everything a smaller one saw. Replay the crash: the table holds 412, 431, 440 and 450, and the largest is the truth. A second 450 changes nothing.

This is what Flink means when it says a sink must take part: “To guarantee end-to-end exactly-once record delivery (in addition to exactly-once state semantics), the data sink needs to take part in the checkpointing mechanism” (Flink). A transactional sink commits its writes with each checkpoint. An idempotent sink, like this table, makes a repeated or out-of-date write change nothing.

The table is ClickHouse, with the ReplacingMergeTree engine and the clicks column as its version, which makes it keep the row with the most clicks. ClickHouse drops the other rows when it merges parts of the table in the background. Its documentation warns that “merging occurs in the background at an unknown time, so you can’t plan for it” (ClickHouse). Until the merge, every total written for the minute is on disk.

So every query reads with FINAL, which applies the replacement at read time. Another way is to group by the key and take the largest total. A query that simply sums the rows adds every total written for 19:03: 412 + 431 + 440 + 450 = 1,733, for 450 real clicks. FINAL costs time over long ranges, which is one more reason the next deep dive moves long reports off minute rows.

Click time comes from the redirect servers’ clocks, and those clocks need a guard. A server whose clock ran an hour fast would drag the watermark an hour ahead, and every other server’s clicks would arrive late. So the servers keep their clocks synchronised, and the job rejects a click stamped far from the time Kafka received it.

The experiment follows minute 19:03 of Rosa’s ad through the late clicks and a crash after the second spool. The tabs are writing each minute once, adding the difference, numbering the writes, and keeping the largest total.

The interactive version of this example is available when JavaScript loads.

The gap: A minute can change after it was written, and after a crash the job can send the same change again.

Option 1: Write each minute once

Close the minute, write its count, and drop anything later.

Works when: Dashboards that can wait for the nightly recount.

Breaks when: Late clicks stay missing from every chart until the recount.

Option 2: Add the difference

Late clicks become clicks = clicks + n.

Works when: A sink that never sees a replay.

Breaks when: A replay adds again: 478 for 450 clicks.

Option 3: Number the writes, keep the highest

Send whole totals with a write number; the table keeps the highest number.

Works when: A job whose replays group records exactly as before.

Breaks when: A replay can group the late clicks differently: write 3 says 440, write 2 says 450, and 440 wins.

Option 4: Keep the largest total (start here)

Send whole totals; the table keeps the largest for each ad, minute, country and device.

Works when: Counts that only grow, as a stream’s count of one minute does.

Watch for: Readers must apply the replacement, with FINAL or by taking the largest.

In the interview: Open with option 4, and give the rule plainly: write totals, not differences, and let the largest win. If the interviewer offers a write number, walk the crash that makes it fail. Mention a transactional sink if they ask about a store that cannot replace rows.

Say this: Late clicks reopen a minute that is already written, and a crash can replay any write, so the job never sends differences. It sends the minute’s whole total, and the table keeps the largest total for each ad and minute. That is safe because a stream only adds clicks to a minute, so a bigger total has seen everything a smaller one saw. A write number would not be safe, because a replay can group the late clicks differently. The table is a ClickHouse ReplacingMergeTree with clicks as its version, read with FINAL.

The interactive version of this example is available when JavaScript loads.

The code has four tabs: the redirect, the two Flink stages, the ClickHouse tables, and the nightly recount.

An advertiser asks for 90 days of clicks. Where does the answer come from?

At 22:00 on Tuesday, Rosa opens her campaign’s report: clicks per day for the last 90 days, for her 40 ads, split by country and device. She expects it to load in under a second.

The minute table can answer it. Each ad has at most one row per minute before the split by country and device, and 90 days is 90 × 1,440 = 129,600 minutes. Forty ads is up to 40 × 129,600 = 5,184,000 rows, each read with FINAL. Each country and device an ad draws clicks from multiplies its rows again.

That is one advertiser. A large retailer with thousands of ads asks the same question, and so do thousands of other advertisers. ClickHouse stores each column separately and reads only the columns a query names, so a scan of millions of rows is routine. But it still has to scan them for every report, and 89 of the 90 days have not changed since yesterday.

The fix is to store the answer at the grain people ask for. A day row holds one ad’s clicks for one day, by country and device. The same report reads 40 × 90 = 3,600 day rows before the split, 1,440 times fewer. An hour row serves reports on the last few days. The report API picks the coarsest grain that answers the question: day rows for 90 days, hour rows for the last week, and minute rows for the last two hours.

Building those rows has a trap in it, and it is the one from the last deep dive. ClickHouse can keep a summary table up to date by itself, with a materialized view. The view is a query that runs on every insert into the minute table and adds the new rows into an hour table. Minute 19:03 was written four times as its late clicks arrived: 412, 431, 440 and 450. The view sees every insert and adds them all. Rosa’s campaign had 1,860 clicks from 19:00 to 20:00 on Tuesday. The view’s hour row says 1,860 + 412 + 431 + 440 = 3,143, and nothing on the report looks wrong. A rollup fed by every insert counts every earlier total again.

So a rollup job builds hours and days from settled minutes. A minute is settled once no late click can change it, an hour after the watermark passes it. The counting job publishes how far it has settled, and the rollup job builds an hour only once that marker has passed the hour’s end. On an ordinary day that is about an hour after the hour ends; on a day the job falls behind, later. The rollup reads the hour’s minute rows with FINAL, sums them, and writes the hour row, and the day row the same way once the day has settled. It writes by replacement, keyed by ad and hour or ad and day, so running it twice is harmless.

Days follow each advertiser’s time zone, because an invoice day is the advertiser’s day. A day for an advertiser in Tokyo covers different minutes from a day for one in New York. That is one more reason days are built from minutes rather than counted directly.

Three more choices keep reports fast and honest. The advertiser comes from the signed-in session, and the API adds it to every query. So no ad ID in a URL can reach another advertiser’s rows. The tables are sorted by advertiser, ad and time, so one advertiser’s rows sit together on disk. And every report says which days are final, through final_through. The recount’s day rows are the final ones, and the table keeps them over the rollup’s. Minute and hour rows stay as the stream counted them, and the report labels them provisional.

Only the fields the product promises are counted ahead of time: country and device. A question nobody planned for, such as clicks by browser version, runs as a slower job over the archive and arrives as a file.

The interactive version of this example is available when JavaScript loads.

The experiment builds Rosa’s 90-day report three ways. The tabs are reading minute rows, rows kept by a view on every insert, and rows rolled up from settled minutes.

The interactive version of this example is available when JavaScript loads.

The gap: Advertisers ask about months at a time, and the minute rows that answer them grow by up to 2 billion a day.

Option 1: Sum minute rows at read time

Every report scans the minute table with FINAL.

Works when: The last two hours, and short ranges.

Breaks when: Ninety days is up to 5,184,000 rows for one advertiser’s 40 ads, on every report.

Option 2: A view that adds every insert

ClickHouse keeps hour and day rows up to date as minute rows arrive.

Works when: Counts written once and never updated.

Breaks when: Every earlier total of a minute is added too: 3,143 for an hour that had 1,860 clicks.

Option 3: Roll up settled minutes into hours and days (start here)

A job sums each hour and day once no late click can change it, and writes by replacement.

Works when: Reports over weeks and months.

Watch for: An hour appears about an hour after it ends, so the last two hours still read minute rows.

In the interview: Open with option 3, and say why the rollup waits: a minute can change until its lateness passes. If the interviewer suggests a materialized view, walk the double count of 19:03. Keep minute rows for the last two hours.

Say this: Reports read at the grain people ask for: day rows for months, hour rows for the week, minute rows for the last two hours. A job builds hours and days from minutes once no late click can change them, reads them with FINAL, and writes by replacement. A view that adds every insert would count every earlier total of a minute again. The advertiser comes from the session, and each report says which days are final.

The dashboard said 12,480 clicks. The invoice says 12,105. Which is right?

Just before midnight on Tuesday, Rosa’s dashboard says her campaign got 12,480 clicks that day. On the first of the month she gets an invoice, and Tuesday’s line says 12,105. She calls. Which number is right, and can anyone say why they differ?

The easy design bills from the dashboard. The minute table already has the counts, so sum Tuesday and send the invoice. But the stream judges each click as it arrives, within the hour it keeps a minute open, and some things take a whole day to see.

Three things surfaced after Tuesday’s minutes had settled. A redirect server lost power during a fault and came back 90 minutes later with its spool. It held 16 real clicks, too late for the stream, which set them aside. Ninety-one clicks came from address ranges that belong to data centres, where scripts run and people rarely browse. And 300 clicks came from twelve phones that each tapped the same ad about 25 times in four minutes, the pattern of a click farm. None of that is visible one minute at a time.

So billing reads a count built later, from everything. Every record the redirect servers wrote, repeats included, is copied from the log into files in S3, one folder per hour of arrival. At 03:00 each day a Spark job reads everything that has arrived and keeps the clicks that belong to yesterday. It removes repeated clicks by impression ID across the whole day and the day before, since a link lives 24 hours. It applies the invalid-traffic rules: known bots, data-centre ranges, and bursts from one device. The fraud team owns those rules and gives each set a version. Then the job sums, per ad and day, the clicks and their prices.

The job sums prices rather than multiplying a count by one price. Each click is charged its own price, set when the ad was shown and often below the advertiser’s bid. Google calls it the actual cost per click: “the final amount you’re charged for a click” (Google Ads). That price travels in the signed link, in millionths of a currency unit, so the invoice sums whole numbers.

The recount produces 12,480 + 16 − 91 − 300 = 12,105, and it keeps the reasons. The billing line for Tuesday records 12,480 counted live, 16 late, 91 from data centres, 300 from a click farm, and the version of the rules. The recount also writes Tuesday’s final day rows to ClickHouse, so the dashboard’s total for the day and the invoice agree.

A week after the invoice is sent, the fraud team finds a botnet that had been clicking slowly enough to pass every rule. It made 120 of Tuesday’s clicks. The invoice is paid. Changing Tuesday’s line would leave Rosa holding a document that no longer matches the record. So the platform issues a credit on the next invoice, linked to Tuesday’s line and to the rule that found the clicks. Google Ads handles it the same way: invalid clicks found after billing come back as “a credit on your next invoice where appropriate and possible” (Google Ads). The sent invoice never changes, and the invoice plus its credits is always the current truth. A Tuesday click that reaches the archive after the 03:00 run goes the same way, as a linked line on the next invoice.

Billing the dashboard’s 12,480 would have charged Rosa for the 391 clicks the rules reject and the 120 the botnet made. It would also have missed the 16 late ones. That is 391 + 120 − 16 = 495 clicks more than the platform stands behind.

The stream is exact over the clicks that reached it in time, and dashboards, budgets and alerts run on it. The recount sees the whole day and the rules that need it, and money runs on it. Running a fast path beside a batch path like this is called a Lambda architecture. Some teams run the recount as the same streaming code replaying the archived log, which is called a Kappa architecture: one codebase, the same idea. Either way, a daily report compares the two per ad, and a gap that the reasons do not explain raises an alert. After a counting bug is fixed, the recount runs again over the archive for the days it touched.

The archive holds addresses and browser details, so it is encrypted and readable only by the recount and the fraud team. Once the window for disputes closes, it is trimmed to what invoices need.

The experiment walks Tuesday from the dashboard to the invoice and a week past it. The tabs are billing from the dashboard, billing from the recount and editing the invoice later, and billing from the recount with a linked credit.

The interactive version of this example is available when JavaScript loads.

The gap: The fast count has not seen everything, and money can move only once.

Option 1: Bill from the dashboard

Sum the minute table for the period.

Works when: Budgets and dashboards, never invoices.

Breaks when: It bills 495 more clicks than the platform will stand behind, with no reasons.

Option 2: Recount, then edit the invoice when fraud is found

Bill from the nightly recount, and rewrite the sent invoice later.

Works when: Before an invoice is sent.

Breaks when: A paid invoice changes after the fact, and no record says why.

Option 3: Recount with reasons, then credit later findings (start here)

Bill from the nightly recount with its reasons, and put later findings on the next invoice as linked credits.

Works when: Always, for billing.

Watch for: A day has two numbers until the recount runs, so reports must say which days are final.

In the interview: Open with option 3, and give the reasons with numbers: late, data centres, click farm. Then say where later findings go: a credit, never an edited invoice. Name Lambda only if the interviewer asks what the pattern is called.

Say this: The dashboard runs on the stream, which is exact over the clicks that reached it in time. Invoices run on a nightly recount over every archived record, which deduplicates across the day, applies the fraud team’s versioned rules, and sums each click’s own price. The billing line keeps the reasons it differs from the live count. Anything found after an invoice is sent becomes a linked credit on the next one.

If they push: stop an ad when its budget runs out

Rosa sets a daily budget of $500. The ad server, which chooses which ad to show, must stop showing hers once she has spent it. It reads spend from the fast path. The counting job also sums cost per ad per minute, and a budget service adds up each ad’s spend for the day. That number is a couple of minutes behind. Clicks also keep arriving after the ad stops being shown, from pages people have not closed, for up to 24 hours. So spend can pass the budget. The platform picks a rule and states it. It slows an ad down as it nears its budget, based on how fast it is spending, and it does not bill clicks past the budget. The recount applies that rule. Platforms differ here: some let one day overspend and cap the month instead.

If they push: impressions and click-through rate

Counting impressions is the same pipeline with more traffic and no redirect. The ad server reports each showing, and since most ads shown are never clicked, impressions are many times the clicks. Click-through rate is clicks divided by impressions for the same ad. Count each click under the minute its ad was shown, which the token’s expiry records, so both numbers describe the same showings. Then the rate is a division at read time, not a join of two streams. The impression ID is the same ID a click carries, so a click whose impression was never reported is a signal for the fraud rules.

If they push: more than one region

Put redirect servers and a log in each region, close to shoppers, and count each region’s clicks where they land. A minute row carries its region, and a report sums the regions. A repeated tap almost always reaches the same region as the first. When a region fails over, a repeat can land in another region, and neither region’s seen-set knows about the other. The nightly recount reads every region’s archive and deduplicates by impression ID across all of them. So the invoice is right even when the live count briefly is not.

Walk one click through the final design

At 19:02:07 Theo taps Rosa’s ad. A redirect server checks the token for impression imp-81f2, appends the click to Kafka, and answers 302 in a few milliseconds. A first-stage task keyed by Rosa’s ad and imp-81f2’s slice has not seen imp-81f2. It adds the ID to its seen-set and adds one to Rosa’s ad for that second. His tap at 19:02:08 reaches the same task, finds the ID in the set, and is left out of the count, though the archive keeps it.

The counting task that owns Rosa’s ad adds the second’s sum to minute 19:02. Once clicks from 19:03:30 have arrived, the minute closes, and the task writes its whole total to the ClickHouse minute table. Rosa’s dashboard reads it with FINAL within 30 seconds. At about 21:00, once the 19:00 hour has settled, the rollup job writes it. At 03:00 the Spark recount reads Tuesday from S3, applies the rules, writes Tuesday’s billing line, and writes the final day rows.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 record every click, then redirectSigned link, redirect server, Kafka with acks=all, a spool on local diskA spooled click waits on one disk until the log returns
FR2 clicks per ad by minute, hour and dayTwo Flink stages, whole minute totals in ClickHouse where the largest wins, rollups of settled hours and daysQueries apply the replacement with FINAL; an hour appears about an hour late
FR3 billable clicks per dayArchive in S3, a nightly Spark recount with versioned rules, billing lines in PostgreSQLInvoices trail by a day; later findings become credits
Each click billed onceImpression ID in a signed link, a seen-set in checkpointed state, a recount across the dayThe seen-set is about 80 GB
One ad at 20,000 a secondThe first stage keyed by ad and impression slice, summing each secondUp to a second more delay

How does the answer change for click counters, impressions or clickstream analytics?

Interview variantWhat carries overWhat changes
Design an ad click counterEverything on this pageOften smaller, with no billing. Ask whether the count is billed before designing the recount
Ad click event aggregationThe whole pipelineOften adds the top N ads each minute. See the top K breakdown
Design ad impression countingThe log, the two stages, the rollupsMany times the volume, and no redirect: the ad server reports each showing
Design clickstream analytics for a websiteLog, stream, analytics storeNobody is billed, so no recount, and more questions are answered at read time
Design click fraud detectionThe records and the nightly recountThe rules become the whole problem: signals per device and address, models, and review
Design ad budget pacingThe fast count of spendThe count drives which ads are shown, so lag becomes overspend

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelSends clicks through a redirect server that appends to a log. Counts per ad per minute in a stream processor. Serves reports from an analytics database.
SeniorDeduplicates by an impression ID in a signed link, and shows why grouping by address fails. Counts by the time of the click, keeps minutes open for late clicks, and rolls reports up to hours and days.
StaffSplits a hot ad over two stages with deduplication in the first. Writes whole totals and lets the largest win, so a replay adds nothing, and keeps rollups away from views that add every insert. Bills from a nightly recount that keeps its reasons.
PrincipalDecides what the redirect does when the log is down, how long links live and so how much state deduplication needs, which rules only the recount can apply, and how credits keep sent invoices unchanged.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.