Design an Ad Click Aggregator
hard 75 minTurn ten billion clicks a day into fast dashboards and exact bills: a durable log, event time, deduplication, totals and a daily recount.
See it run
Follow a click into a durable log, then make quick and final counts.
Operations
Record one click
Save before redirecting.
Step 1 of 5
Click
ad
B
A person follows a signed link. The service checks expiry, target and size limits.
Step 1: Click
def click(token): event = verify(token) # impression + press number = click ID event.received_at = server_now_utc() kafka.append(key=(event.ad, event.visitor), value=event) wait_for_replica_ack() return redirect(event.landing_page)# laterflink.count(event)- Time
- Tens of ms
- State or work
- One log record
- Count before redirect
- reporting delays people
The 202 or redirect means saved, not counted.
In the real world
The same ad click aggregator doing real jobs. Pick one and step through it.
A checkpoint prevents an added total on replay.
Step 1 of 3
Save
position
100
total
20
Keys, count and position 100 are in one checkpoint.
Step 1: Save
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Count before durable append
criticalA saved redirect can have no recoverable click.
Wrongincrement(ad); return redirect()Rightappend_replicated(click); return redirect()Random partition key
criticalThe same visitor's repeats reach different workers.
Wrongkey = random()Rightkey = (ad, visitor)Add total on replay
criticalA worker restart repeats the output.
Wrongdb.increment(key, delta)Rightdb.replace(key, absolute_total, version)Use browser arrival minute
majorClock errors and delays move clicks between bills.
Wrongminute = browser_now()Rightminute = click.trusted_received_at // 60Delete suspicious clicks
majorReview, correction and billing disputes lose evidence.
Wrongif score > 0.95: discard(click)Rightclick.decision = invalid(score, reason, version)
Interview tips
Define before design
- Valid visitor-ad-minute.
- Raw, provisional and final.
- Finance cut-off.
Three protections
- Replicated append.
- State and position checkpoint.
- Replace absolute total.
Do not trust time
- Server receipt UTC.
- Early results.
- Late side output and recount.
Prepare the hot case
- Visitor partition.
- Two-stage merge.
- Pre-scale the known event.