System design interview: design an ad click aggregator
An ad click aggregator turns a raw stream of click events into counts per ad per minute, plus the most clicked ads, quickly enough for advertisers' dashboards and accurately enough to bill from. The design is a stream pipeline: a log such as Kafka partitioned by ad ID, a stream processor that deduplicates clicks and counts them in event-time windows with a watermark for late arrivals, an analytics store for queries, and a batch job over the raw log that reconciles the numbers.
By Evin JohnPublished 7 min read
1. Clarify the requirements
Ask what the counts are used for. Dashboards can tolerate small errors; invoices cannot, and that changes the guarantees you need.
- Functional: count clicks per ad per minute; query an ad's clicks over any recent range; list the top 100 ads by clicks in the last minute or hour; filter by country, device or campaign.
- Non-functional: dashboard numbers within a few minutes of the click; queries answer in under a second; billing totals exact after reconciliation; the pipeline survives node failures without double counting.
- Out of scope unless asked: the ad serving and auction system, click fraud models (mention a hook for them), impression counting (same design, more volume).
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Clicks | 1 billion a day | about 11,600 a second on average; plan for 5x at peak, about 58,000 |
| Raw event size | about 100 bytes (click ID, ad ID, time, country, device, user hash) | about 100 GB a day of raw clicks |
| Active ads | 2 million, of which about 300,000 get a click in a given minute | up to 300,000 count rows per minute |
| Aggregated rows | 300,000 a minute for 1,440 minutes, about 50 bytes each | about 430 million rows, about 22 GB a day |
The event rate is moderate for a partitioned log and a stream processor. The design questions are about correctness, not raw capacity.
3. Define the query API
GET /v1/ads/{ad_id}/clicks?from=2026-12-03T10:00Z&to=2026-12-03T11:00Z&granularity=minute&country=DE
-> { points: [ { minute, clicks } ], final: false }
GET /v1/ads/top?window=1m&limit=100&country=US
-> { minute, ads: [ { ad_id, clicks } ] }The final flag tells the dashboard whether the numbers have been reconciled. Advertisers see live figures quickly and know which ones may still move.
4. Sketch the data model
| Data | Store | Shape |
|---|---|---|
| Raw clicks | Partitioned log, then object storage by hour | click_id, ad_id, event_ts, country, device, ... |
| Per-minute counts | Columnar analytics store or time-series database | (ad_id, minute, country) -> clicks, written as upserts |
| Top ads per minute | Same store or a small key-value table | (minute, filter) -> ordered list of (ad_id, clicks) |
| Dedup state | Inside the stream processor, keyed by click_id, with a TTL | seen click IDs for the last few hours |
5. Counting correctly: windows, watermarks and duplicates
- Event time, not arrival time. A click at 10:00:59 that arrives at 10:01:03 belongs to the 10:00 minute. Count by the timestamp in the event.
- Tumbling windows. One-minute, non-overlapping windows per ad. Hourly and daily numbers are sums of minutes, computed in the store.
- Watermark. The processor tracks how far event time has progressed, minus an allowed lateness (say one minute). When the watermark passes a window's end, the window closes and its counts are written.
- Late events. Clicks for a closed window are not dropped. They go to a correction stream that recomputes the stored row from deduplicated clicks (or adds each click ID at most once), so replaying corrections cannot inflate it, and the batch recount picks up anything still missing.
- Duplicates. Retries and double taps create repeated click IDs. Keep seen IDs per partition for a few hours and skip repeats; fraud filters can mark suspicious clicks at the same step.
from collections import defaultdict
class MinuteCounts:
def __init__(self, lateness_s=60):
self.lateness = lateness_s
self.open = defaultdict(lambda: defaultdict(int)) # minute -> ad -> count
self.max_seen = 0
self.seen_ids = set() # dedupe; in production a TTL store
self.closed, self.late = [], []
def add(self, click_id, ad_id, event_ts):
if click_id in self.seen_ids:
return
self.seen_ids.add(click_id)
minute = event_ts // 60 * 60
watermark = self.max_seen - self.lateness
if minute + 60 <= watermark: # its window already closed
self.late.append((minute, ad_id)); return
self.open[minute][ad_id] += 1
self.max_seen = max(self.max_seen, event_ts)
self._close(self.max_seen - self.lateness)
def _close(self, watermark):
for minute in sorted(m for m in self.open if m + 60 <= watermark):
self.closed.append((minute, dict(self.open.pop(minute))))6. The architecture
- Sources
- Ad servers
- Click redirect tracker
- Ingest
- Partitioned log, key = ad ID
- Streaming
- Stream processor: dedupe, windows, top N
- Correction path for late clicks
- Storage
- Analytics store (per-minute counts)
- Raw archive in object storage
- Consumers
- Query service and dashboards
- Nightly reconciliation job
- Billing
7. Deep dives
- Exactly once, in practice. The processor checkpoints its input offsets and window state together. Writes to the store are upserts keyed by (ad, minute), so replaying after a crash rewrites the same rows with the same values instead of adding to them. Frameworks that commit output and offsets together help, but idempotent writes are the property to name.
- Top N per minute. Because the log is partitioned by ad ID, every click for an ad lands in one partition. Each partition's top 100 is exact for its ads, so merging the partitions' lists and keeping the top 100 gives the exact global answer. Partition by anything else and the merge can miss an ad that is moderately popular everywhere.
- Hot ads. A huge campaign can overload its partition. Add a small random suffix to that ad's key so its clicks spread over a few partitions, count each part, then sum the parts in a second stage. The top N merge then needs that second stage before ranking.
- Filters. Counting by every combination of country, device and campaign multiplies rows. Pre-aggregate the common filters; send rare combinations to the analytics store's own group-by over finer rows.
- Reconciliation. The nightly job recounts from the archived raw clicks with the same dedupe rule and compares totals per ad and day. Differences are corrected in the store and the day is marked final; repeated large gaps point to a pipeline bug.
- Lambda or kappa. Running a separate batch pipeline for truth (lambda) costs two code paths; replaying the log through the same streaming code (kappa) keeps one. Either way, keep the raw clicks long enough to recount.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Stream processor crashes | Counts for open windows lost from memory | Restore from the last checkpoint and replay the log from its offsets; upserts make the replay safe |
| Duplicate events after a producer retry | Inflated clicks and bills | Dedupe by click ID before counting; recount nightly with the same rule |
| Clock skew on devices | Clicks land in the wrong minute | Prefer the tracker's server timestamp; clamp client times that are in the future |
| Log retention shorter than an outage | Clicks lost before they are processed | Retention of several days, archived to object storage continuously |
| Bug in aggregation code | Wrong numbers for hours | Fix, then replay the affected hours from the raw archive and overwrite the rows |
9. Trade-offs to discuss
- Freshness or finality. Longer allowed lateness means fewer corrections but slower dashboards. Show fast provisional numbers and mark reconciled ones final.
- Store raw or only aggregates. Aggregates are small; raw clicks are what let you fix bugs and answer disputes. Keep both, raw in cheap storage.
- Pre-aggregate or query raw. Pre-aggregated rows answer dashboards in milliseconds; querying finer rows supports any filter but costs more per query. A columnar store can do both at this volume. The same storage reasoning appears in SQL vs NoSQL.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Your aggregator crashes and restarts from a checkpoint ten minutes old. Are some clicks counted twice?
- Candidate
- No. The checkpoint holds both the log offsets and the open window state, so the restart reprocesses those ten minutes from the same starting point. Closed windows are written as upserts keyed by ad and minute, so rewriting them produces the same rows, not doubled ones.
- Interviewer
- And a click that arrives two hours late?
- Candidate
- Its window is closed, so it goes through the correction path and is added to that minute's row. The nightly recount from raw clicks confirms the total before the day is marked final for billing.
- Lead with why accuracy matters (billing) and let it justify dedupe, watermarks and reconciliation.
- Explain why partitioning by ad ID makes top N exact.
- Keep the raw data and say how you would replay it.
Practicing this design with Natively
Stream-processing vocabulary (watermark, upsert, checkpoint) is easy to use loosely under pressure. A transcribed mock round helps: Natively transcribes your explanation as you give it, can suggest the next point when the interviewer asks about replays, and draws the pipeline as a diagram on request. Reading the transcript afterwards shows whether you said event time or just time.
Questions people ask
How do you design an ad click aggregator?
Write click events to a log partitioned by ad ID, run a stream processor that removes duplicate click IDs and counts clicks in one-minute event-time windows, and upsert the counts into an analytics store for queries. Keep the raw clicks so a batch job can recount and reconcile the numbers used for billing.
How do you avoid double counting ad clicks?
Deduplicate by a unique click ID before counting, checkpoint log offsets together with window state, and write results as upserts keyed by ad and minute. A replay after a crash then rewrites the same rows instead of adding to them, and a nightly recount catches anything that slipped through.
What is a watermark in stream processing?
It is the processor's estimate of how far event time has progressed, usually the latest event time seen minus an allowed lateness. When the watermark passes the end of a window, the window is closed and its count is written; events for it that arrive later are handled as corrections.
How do you find the top clicked ads per minute?
Partition the stream by ad ID so each ad's clicks are counted in one place, compute each partition's top N for the minute, and merge those lists. Because no ad is split across partitions, the merged top N is exact.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
