"Design an ad click aggregator" looks like a counting problem, and counting is easy. The catch is that these counts are money. An advertiser is billed per click, so an undercount loses revenue and an overcount means you charged someone for clicks that never happened.
The interviewer is testing whether you treat accuracy as a requirement and not a hope. What happens when a consumer crashes halfway through a batch? What happens when a phone sends a click six hours late? What do you do when one ad takes 5% of all traffic? And how do you prove, to an angry advertiser, that your number is right?
If you have read the lesson on stream processing, this is its sharpest application: event time, windows, watermarks and exactly-once effects, all with a billing department watching.
Clarify the requirements
Functional requirements:
- Record every click on an ad (ad id, campaign, click id, timestamp, device, country).
- Report clicks per ad, campaign or advertiser in one-minute buckets, rolled up to hours and days.
- Advertisers query their counts on a dashboard, filtered by time range and country.
- Produce the final, billable click totals once a day.
- Drop fraudulent and duplicate clicks from billable counts.
Out of scope, said aloud: impressions and view-through attribution, ad auctions and bidding, and the fraud model itself (we only reserve a place for it in the pipeline).
Non-functional requirements:
- Counts must be accurate to the click for billing. Not "approximately right": the daily total must match the raw log.
- No double counting on retries. Clients retry, brokers redeliver, consumers restart. None of that may change a count.
- Dashboards are near real time: a click shows up within one to two minutes.
- Late events are normal. A phone that was offline delivers its clicks when it reconnects, sometimes hours later.
- The pipeline never loses a click it accepted. Once ingestion acknowledges an event, it is durable.
Estimate the scale
Assume 1 billion clicks a day and 200 bytes per click event, and a dashboard that advertisers open about 10 million times a day.
Writes: 1,000,000,000 ÷ 86,400 s ≈ 11,600 clicks per second on average. Traffic follows campaigns and time zones, so plan for 3× at peak, about 35,000 per second.
Raw storage: 1B × 200 B = 200 GB a day, or about 73 TB a year. We keep raw events for a year so any bill can be recomputed.
Aggregates: assume 5 million distinct ads get a click on a given day, each in about 20 distinct minutes. That is 100 million rows a day. At 50 bytes a row, 5 GB a day, 40 times smaller than the raw data.
Reads: 10M dashboard queries ÷ 86,400 s ≈ 116 per second. Tiny.
Bandwidth: 35,000 events/s × 200 B = 7 MB/s at peak, which one small Kafka cluster ignores.
Deduplication state: if we remember every click id for an hour at peak, that is 35,000 × 3,600 = 126 million ids. At 16 bytes each, about 2 GB.
"The throughput is modest: 35,000 events a second and 7 MB/s. This is not a scaling problem, it is a correctness problem. The data is write-heavy and reads are rare. What is hard is making counts exact under retries, crashes and late events, and keeping hot ads from skewing one partition."
Change the assumptions in the capacity estimator and watch the raw storage move.
API and data model
POST /v1/clicks { clickId, adId, campaignId, ts, deviceId, country } -> 202 Accepted
GET /v1/ads/{adId}/clicks?from=&to=&granularity=minute|hour|day&country=
-> { buckets: [{ start, count }] }
GET /v1/campaigns/{id}/billing?day=2026-12-01 -> { clicks, status: "final" }The click endpoint answers 202, not 200: it means "durably accepted", not "counted". Counting happens downstream.
raw_clicks (day, click_id) -> event // object storage, Parquet, source of truth
clicks_by_min (ad_id, minute_start) -> count, country_counts // wide-column store
billing_daily (campaign_id, day) -> clicks, computed_at, statusThe non-obvious choice is the click id. The client (or the redirect service that sees the click first) generates it, so a retry carries the same id. Everything about exact counting hangs on that one field.
High-level design
We simulate the ingestion and aggregation spine: a gateway, a stateless ingest service, a partitioned log, a group of aggregators and the counts store.
- The ingest service validates a click and appends it to the click log, keyed by ad id.
- Aggregators in one consumer group each own a share of partitions and write per-minute counts.
Describe this diagram
Components
- clients (Client)
- gateway (API gateway)
- click ingest (Service)
- click log (Kafka)
- aggregators (Service)
- counts store (Cassandra)
Connections
- clients sends to gateway
- gateway sends to click ingest
- click ingest sends to click log
- click log sends to aggregators
- aggregators sends to counts store
Run it, then try cutting the consumers in the log from six to two, or add load, and watch the backlog grow while the counts store stays calm.
The write path: the ingest service checks the payload, writes the event to the log with acks=all, and answers 202. A second consumer group copies every event to object storage as the raw record. Ingestion never touches the counts store, so a slow database cannot reject a click.
The read path: dashboards query the counts store directly. For a day's total the query sums at most 1,440 minute rows per ad, or reads the pre-rolled hourly rows.
The interesting problem: counting exactly once
A click can be delivered to your pipeline more than once: the browser retries, the load balancer retries, the broker redelivers after a consumer crash. "Exactly once" is not a property of the network. You build it from at-least-once delivery plus an idempotent effect. The lesson on idempotency covers the mechanism; here is how the three designs differ.
Approach A: increment a counter per click
Each ingest call runs UPDATE counts SET n = n + 1 WHERE ad_id = ? AND minute = ?.
Good: trivial, and always up to date.
Bad: a retry increments twice, so the count cannot be trusted. A popular ad makes one row take thousands of writes per second, which is a hot row. And there is no way to recompute: once a wrong number is stored, the evidence is gone.
Approach B: aggregate in a stream, deduplicate by click id
Events go to the log first. An aggregator keeps, per ad and minute, a running count and the set of click ids already seen, and emits the window when it closes. A repeated id is dropped. The aggregator commits its log offset and its state together (a checkpoint), so after a crash it resumes from the last checkpoint and replays the events since, and the dedup set absorbs the replays.
Good: the count is exact for events the stream sees, and the log gives you replay.
Bad: dedup state has to be bounded, so you only remember ids for a window (say one hour). A duplicate that arrives later than the window slips through. State is also a recovery cost: a big aggregator restarts slowly.
Approach C: stream for speed, batch for truth
Run B for dashboards, and also land every raw event in object storage. Once a day a batch job reads the day's raw events, deduplicates them over the whole day (a sort-and-distinct, with no memory limit), and writes the final billable totals. The stream's numbers are provisional; the batch number is the invoice.
Diagram, as text
- Ingest leads to Click log
- Click log leads to Stream aggregators
- Click log leads to Raw files in object storage
- Stream aggregators leads to Dashboard counts
- Raw files in object storage leads to Daily batch job
- Daily batch job leads to Final billing totals
- Final billing totals leads to Dashboard counts (reconcile)
This is the answer to aim for. The stream gives the one-minute freshness; the batch gives correctness without a memory bound, and doubles as a check on the stream. If the two disagree by more than a small threshold, an alert fires, and you have found a bug before an advertiser does.
The second decision: event time, windows and late clicks
Group clicks by the time they happened (event time), not the time you received them. A click at 11:59:58 that arrives at 12:00:03 belongs in the 11:59 bucket. That is the correct choice, and it forces a problem: when is the 11:59 bucket finished?
You answer with a watermark: the aggregator's estimate that no more events older than time T are coming. Pick an allowed lateness, say two minutes. A window closes and emits when the watermark passes its end plus two minutes. Anything later is a late event. You then choose:
- Drop it from the stream and rely on the batch. Simple, and the daily total still counts it.
- Emit a correction to the bucket, an upsert of the new total. The dashboard shows a number that quietly grows.
A good default is to keep the stream window short, fix late arrivals with corrections for up to an hour, and let the batch job settle anything after that. Say that this trades dashboard freshness against completeness, and that billing never depends on the stream's choice.
Bottlenecks and failures
Hot ads. One ad in a major event can take 5% of all clicks, about 1,750 per second at our peak. Partitioning by ad id sends all of them to one partition and one aggregator. Fix it by salting: split the hot key into, say, eight sub-keys, count each separately and merge the partial counts in a second step. Detect hot keys by monitoring per-partition lag, and salt only the ones that need it.
An aggregator crashes. It restarts from its last checkpoint, replays the log since then and rebuilds state. The dedup set makes the replay safe. Keep checkpoints frequent enough that replay takes seconds, not minutes.
Backlog. If aggregators fall behind, the log simply grows. Retention (seven days) gives you time to add consumers. The lag in seconds is the alert, not the error rate: nothing is failing, it is only late.
What if the counts store is down? Ingestion is unaffected, because it only writes to the log. Aggregators retry their idempotent upserts; dashboards go stale and show a "data as of" time. No click is lost.
What if the log is down? This is the one dependency that stops ingestion. Run it across three zones with replication factor 3, and have clients keep a small retry buffer. If you must degrade, the ingest service can spool to local disk and flush later.
Click fraud. Bots can inflate a competitor's bill. Run a filter stage (rate per device, impossible geography, known bad networks) that tags events instead of deleting them. Raw data stays complete, and billing excludes the tagged ones. Related: a rate limiter at the edge stops the crudest floods.
Trade-offs to name aloud
- Stream plus batch: two code paths to keep in agreement, in return for fresh dashboards and an exact invoice.
- Bounded dedup window: a bounded memory cost, in return for rare duplicates handled by the batch job.
- Allowed lateness: a longer wait gives more complete windows and slower dashboards.
- 202 on durable accept: the client learns the click was safe, not that it was counted.
- Salting hot keys: an extra merge step to avoid one overloaded partition.
What interviewers listen for
- A working answer: clicks go to a queue, workers aggregate by ad and minute into a store, and a dashboard reads it.
- A strong answer: produces a click id so retries are idempotent, uses event time with a watermark, makes the sink an overwrite, and sizes the numbers (35,000 per second, 40× aggregation).
- A standout answer: adds the daily batch reconciliation against raw events as the billing source of truth, handles hot keys with salting and treats fraud as tagging, not deleting.
Check your understanding
Common mistakes
Incrementing a database counter per click. It double counts on retry, creates a hot row for popular ads and leaves nothing to recompute from. Events first, aggregation second.
Saying "exactly-once" without saying how. The broker does not give it to you across a retry and an external write. Name the click id, the checkpoint and the idempotent sink.
Using arrival time. It is easier, and it moves clicks across buckets whenever the network hiccups. Billing by day then differs from what the advertiser saw.
No source of truth to recompute from. If you keep only aggregates, a bug in the aggregation code is permanent. Keep the raw events, and make the daily batch the invoice.
Using a Bloom filter for dedup and forgetting its error. A Bloom filter's false positives would silently drop real clicks, which undercounts a bill. If you use one as a first-pass filter, treat a "seen" answer as a hint and confirm it against exact state.
Ignoring skew. "Partition by ad id" is right for ordering and wrong for a celebrity ad. Show that you know both.
Practice
An advertiser says the dashboard showed 1,204,300 clicks for yesterday but the invoice says 1,198,950. Walk through how you would find out which is right and why they differ.
Write your own answer first, on paper or in a note. Then compare.
Show a hint
You have a stream result and a batch result for the same day. What can make each of them differ from the truth?
Show a strong answer
Start from the raw log. The raw events for that day are the ground truth. Recount that one campaign directly from them, deduplicating by click id over the whole day. That number settles which of the two is closer.
Explain the gap from the stream's side. The dashboard is provisional. It may include duplicates that arrived later than the one-hour dedup window, and it counts late events as corrections. A difference of 5,350 clicks is about 0.4%, which fits late duplicates, or fraud-tagged clicks that the batch excluded but the stream had already shown.
Check the fraud tags. Compare the batch's excluded count against the 5,350 gap. If they match, the dashboard simply counts clicks the invoice rightly removes.
Fix the product, not just the answer. Label dashboard numbers "provisional until the day closes" and show the final figure beside it once the batch is done.
The pattern worth keeping: when two numbers disagree, name which one is the source of truth, recompute from the raw data and explain the gap with a cause you can measure.
Aggregators are healthy, but the dashboard is 25 minutes behind and getting worse. How do you find the cause and recover?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Lag can be a producer problem, a consumer problem or a skew problem. What would you look at in each?
Show a strong answer
Measure lag per partition. If every partition is behind by a similar amount, the consumers are too slow overall: add aggregators, up to the partition count. If one partition is far behind the others, you have a hot key.
For a hot key, salt it. Split that ad's key across several sub-keys, count each and merge. Until the fix ships, the other partitions are unaffected, so only that ad's numbers are late.
Check the sink. If the counts store is throttling, aggregators block on writes. Batch the upserts per window instead of writing per event, or raise the store's capacity.
Recover without losing anything. The log keeps seven days, so lag is only delay. Scale out, let the backlog drain and watch the lag fall. Nothing needs replaying by hand.
The pattern worth keeping: in a log-based pipeline, a backlog is delay, not loss. Find whether the slowness is everywhere or in one partition before you add machines.
Key takeaways
- The scale is modest, the correctness bar is high. 35,000 events a second is easy, but billing needs exact counts.
- Exactly-once is at-least-once plus an idempotent effect. The click id and an overwriting sink do the work.
- Count by event time and use a watermark with an allowed lateness to decide when a window closes.
- Stream for freshness, batch for truth. Reconcile them daily, and treat disagreement as an alert.
- Salt hot keys and measure lag per partition, not just overall.
- Tag fraud, do not delete it. Raw data stays complete, billing excludes the tagged clicks.
Further reading
- Jay Kreps, Neha Narkhede and Jun Rao, "Kafka: a Distributed Messaging System for Log Processing" (NetDB workshop, 2011): the log that sits at the center of this design.
- Tyler Akidau and colleagues, "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing" (VLDB, 2015): event time, windows, watermarks and late data.
- Jay Kreps, "Questioning the Lambda Architecture" (O'Reilly Radar, 2014): the argument for and against running a stream and a batch path side by side.
- Apache Flink documentation, "Timely Stream Processing": event time, watermarks and allowed lateness in a real engine.