Design an Ad Click Aggregator
Understanding the Problem
📊 What is an ad click aggregator? When someone clicks an ad, two things have to happen: the user lands on the advertiser's site, and the click gets counted. An ad click aggregator handles the second part at scale. It collects every click, removes duplicates and junk, and rolls them up into metrics (clicks per ad per minute, by country and device) that advertisers watch on a dashboard and that billing relies on. It's a streaming analytics problem where the numbers are also money.
You'll also hear this as "design an ad reporting system," "design real-time ad metrics," or as a follow-up: "now one ad gets 100 times more clicks than any other; what breaks?" Those are the same system, with the emphasis on freshness or on data skew. We'll design the whole thing and give both their own deep dive.
Functional Requirements
We'll agree with our interviewer that ads are already served by someone else. We start at the moment a user clicks.
Core Requirements
- Users should be able to click an ad and be redirected to the advertiser's website.
- Advertisers should be able to query click metrics for their ads and campaigns over time, at one-minute granularity.
- Advertisers should be able to break metrics down by dimensions such as country and device.
Below the line (out of scope)
- Ad serving, targeting and the auction.
- Conversion tracking (what the user did on the advertiser's site).
- Impressions. They flow through an almost identical pipeline at much higher volume; we'll mention where it differs.
- The billing system itself. It reads our numbers, and we'll make them trustworthy enough for it to.
Non-Functional Requirements
Ask your interviewer about scale, freshness and how much accuracy matters. For our design: 5M active ads, 1B clicks a day, and a peak about 5x the average.
Core Requirements
- The system should handle ~60k clicks/sec at peak.
- The system should redirect users with minimal added latency (under 50ms on our side).
- The system should make clicks visible in reports within about one minute (real-time reporting).
- The system should be accurate: no lost clicks, no double counting, and duplicate or invalid clicks filtered out. Final numbers must match what we bill.
- The system should answer advertiser queries in under a second, including over months of data.
Below the line (out of scope)
- Ad hoc SQL over raw clicks for every advertiser. Analysts get that from the data lake, not the dashboard.
- Sophisticated ML fraud detection. We'll leave a hook for it.
The math. 1B clicks / 86,400 ≈ 11.6k clicks/sec on average, about 60k/sec at peak. A click event (click ID, impression ID, ad, campaign, advertiser, timestamp, country, device, IP, user agent) is about 300 bytes, so raw data is 300 GB a day, roughly 110 TB a year. At peak that's about 18 MB/sec into the pipeline. Kafka handles that without much thought.
The more interesting number is the aggregate. In any one minute there are about 700k clicks on average, spread over hundreds of thousands of distinct ads. Grouped by (ad, minute, country, device), that's on the order of hundreds of millions of rows a day at minute granularity. Too many to scan for a "last 90 days" query, which tells us we'll need coarser rollups for long ranges.
Notice the two very different timescales. The redirect has to happen in milliseconds, for one user. The metrics can take a minute, for everyone. Separating those paths early, with a durable log between them, is the most important design decision in this problem.
The Set Up
Planning the Approach
We'll build the click path first, then the simplest way to answer queries, then replace it with a streaming pipeline. The deep dives cover freshness, accuracy (no loss, no double counting, reconciliation), dedupe and invalid clicks, data skew from hot ads, and query speed over long ranges.
Defining the Core Entities
- Ad: an ad with an advertiser, a campaign and a target URL.
- Impression: one showing of an ad to a user, with a unique impression ID. Each impression can produce at most one billable click.
- Click: one click event, tied to an impression, with its timestamp and dimensions (country, device).
- Aggregate: a count of clicks for one ad, one time bucket and one combination of dimensions. This is what advertisers query.
API or System Interface
// click path, hit by the browser
GET /click?imp={impressionId}&ad={adId}&ts={servedAt}&sig={hmac}
-> 302 Location: https://advertiser.example/landing?...
// reporting
GET /metrics?advertiserId=...&adIds=...&from=...&to=...
&granularity=minute|hour|day&groupBy=country,device
-> { series: [{ ts, adId, country, device, clicks }] }
The click URL is built by the ad server when the ad is shown, and signed with an HMAC over the impression ID, ad ID and timestamp. The Click Service verifies the signature before doing anything else. That stops anyone from inventing clicks for arbitrary ads, or redirecting users to URLs of their choosing.
High-Level Design
1) Users should be able to click an ad and be redirected
There are two ways to get the user to the advertiser:
- Client-side: the ad's link points straight at the advertiser, and the browser fires a tracking beacon to us in the background. The redirect is as fast as it can be, but beacons get blocked, dropped when the page unloads, and are trivially easy to fake.
- Server-side: the link points at our Click Service, which records the click and responds with a
302to the advertiser's URL.
We go server-side. Every click passes through us, so we see all of them, and we control what gets recorded. The cost is one extra round trip, which we keep fast:
- Verify the signature (microseconds, no I/O).
- Look up the target URL for the ad from an in-memory cache (ad URLs change rarely).
- Publish the click event to Kafka, asynchronously, and return the
302without waiting for the aggregation.
Kafka is the boundary between the millisecond path and the minute path. Once the event is acknowledged by Kafka (replicated to three brokers), it's durable, and everything downstream can be slow, crash and retry without the user noticing.
2) Advertisers should be able to query click metrics over time
The simplest version writes each click as a row in a database and runs a GROUP BY for every query:
SELECT date_trunc('minute', clicked_at) AS minute, COUNT(*)
FROM clicks
WHERE ad_id = :adId AND clicked_at BETWEEN :from AND :to
GROUP BY minute ORDER BY minute;
It's simple, and it falls over quickly. A billion inserts a day into a row store is already a sharded-database problem, and a dashboard asking for a big advertiser's last 30 days scans tens of millions of rows. Hundreds of advertisers refreshing dashboards means hundreds of those scans at once.
The fix is to aggregate before storing. A stream processor (Flink) reads clicks from Kafka, counts them in one-minute tumbling windows keyed by (adId, country, device), and writes one row per key per minute to an OLAP store built for time-bucketed aggregates: ClickHouse, Apache Pinot or Druid. A Query Service sits in front and turns API calls into OLAP queries. Kafka also archives every raw click to S3, which we'll use for reconciliation and for analysts.
Now a query for one ad over a day reads at most 1,440 rows per dimension combination, instead of every individual click.
3) Advertisers should be able to break metrics down by country and device
Dimensions go into the aggregation key. The Flink job counts by (adId, minute, country, device), and the OLAP table stores them as columns:
CREATE TABLE clicks_1m (
minute DateTime,
advertiser_id UInt64,
campaign_id UInt64,
ad_id UInt64,
country LowCardinality(String),
device LowCardinality(String),
clicks UInt64,
version UInt64 -- newer writes for the same key win
) ENGINE = ReplacingMergeTree(version)
PARTITION BY toYYYYMMDD(minute)
ORDER BY (advertiser_id, ad_id, minute, country, device);
It's a replacing table rather than one that adds rows together, because a window's count can be rewritten (late clicks, retries). We'll see why in the deep dives.
A query grouped by country sums over device, a query for a campaign sums over its ads, and so on. The OLAP store is very good at these sums because the data is columnar and sorted by (advertiser_id, ad_id, minute), so one advertiser's data for a time range is a contiguous slice.
Every dimension multiplies the number of rows, so we add them carefully. Country (~200 values) and device (~4) are fine because real traffic is sparse: most ads get clicks from a handful of countries in any minute. A dimension like "city" or "user agent string" could explode the row count and should stay in the raw data on S3, not in the aggregate.
Potential Deep Dives
1) How do we make reports real-time?
"Real-time reporting" usually means advertisers see clicks within a minute or so, so they can react to a campaign launch.
Bad Solution: Periodic Batch Jobs
Approach
Land raw clicks in S3 and run a Spark job every hour (or every 15 minutes) that aggregates the new files and loads them into the OLAP store.
Challenges
Freshness is the batch interval plus the job runtime, so 15 minutes to over an hour. That fails our one-minute requirement. Running batches more often makes the overhead per run (startup, listing files, small-file problems) dominate. Batch is still useful, but as a correctness check, not as the fast path.
Good Solution: Stream Aggregation with Tumbling Windows
Approach
Flink aggregates clicks into one-minute windows by event time and writes each window's counts to the OLAP store as soon as the window closes. Freshness is about a minute plus a little pipeline delay.
The important detail is event time vs. processing time. A click that happened at 10:00:59 but reaches Flink at 10:01:03 (network delay, a mobile client reconnecting, a Kafka consumer catching up) belongs in the 10:00 bucket. Flink uses watermarks to decide when a window is complete: with a watermark that trails the newest event by, say, 10 seconds, the 10:00 window closes once the stream has moved past 10:01:10.
Challenges
Some clicks arrive after the watermark. Dropping them loses money. So we configure allowed lateness (say 10 minutes): a late click reopens its window, and Flink emits an updated count for it. The OLAP write has to be an upsert keyed by (ad, minute, dimensions) so the corrected count replaces the old one rather than being added on top. Anything later than that goes to a side output and is picked up by reconciliation.
Great Solution: Stream for Freshness, Batch for Truth
Approach
Keep the streaming pipeline for the dashboard, and add an hourly (or daily) reconciliation job that recomputes exact counts from the raw clicks in S3 and corrects the OLAP store where they differ. The stream gives speed; the batch, which sees every event including the very late ones, gives the final word.
Rows that have been reconciled are marked final, and billing only uses final rows. The dashboard can show the fast numbers with a note that the last few hours are "preliminary."
Challenges
You're running two pipelines that compute the same thing, and they must agree on the logic (dedupe rules, time bucketing, filters). Sharing the aggregation code between the Flink job and the Spark job, or using a framework that runs the same code in both modes, keeps them from drifting apart. A difference between the two is also a great alarm: if reconciliation keeps making big corrections, the streaming job has a bug.
When an interviewer asks for "real-time" reporting, ask how real-time. A minute is a stream processor. A second is a different design (pre-aggregating in memory and pushing to dashboards), and it's rarely needed for ad reporting. Billing needs neither; it needs exact numbers by the end of the day.
2) How do we make sure no click is lost or counted twice?
Clicks are money, so we need to walk the whole path and check each step.
Click Service to Kafka. The producer uses acks=all with the topic replicated three ways, so an acknowledged event survives a broker failure. If Kafka is unreachable, we don't want to fail the redirect (the user did nothing wrong), so the Click Service writes the event to a local disk buffer and returns the 302 anyway; a background process ships the buffer to Kafka when it recovers. We could lose events if the host dies at the same time as Kafka is down, which is a rare double failure. Saying that out loud is better than claiming zero loss.
Producer retries. A retried send can put the same event in Kafka twice. Enabling the idempotent producer avoids duplicates from retries within one producer session, and the dedupe step below catches everything else, since every click carries its impression ID.
Flink processing. Flink checkpoints its Kafka offsets and its window state together. After a failure it restores the last checkpoint and replays from those offsets. The state is restored to exactly what it was, so counts inside Flink are exactly-once.
Flink to the OLAP store. This is where duplicates usually sneak in: Flink wrote some results after the last checkpoint, crashed, replayed, and writes them again. Two ways to make this safe:
- Idempotent upserts. Every output row is keyed by
(ad, minute, country, device)and carries the full count for that window, not a delta. Writing it twice is the same as writing it once. In ClickHouse this is aReplacingMergeTreewith a version column; Pinot has upsert tables. - Transactional sinks. Flink's two-phase commit sink writes results in a transaction that commits only when the checkpoint completes. This works with Kafka as the sink (Flink writes to an output topic transactionally, and a loader reads only committed data).
Idempotent upserts are simpler and are what we'd pick.
Reconciliation catches the rest. If anything slipped through, the batch job over S3 fixes it before the numbers are final.
3) How do we handle duplicate and invalid clicks?
Not every click should be counted. Users double-click, browsers prefetch, bots click everything, and some publishers click their own ads.
Duplicates. We count at most one click per impression. The impression ID is part of the signed click URL, so it can't be forged. In Flink, we key the stream by impression ID and keep a small piece of state per impression with a TTL (say 24 hours): the first click passes through, later ones are dropped. That's about 1B entries a day at around 50 bytes each, so on the order of 50 GB of state, spread across tasks in Flink's RocksDB state backend, which keeps it on local disk. You could do the same with Redis SET imp:{id} 1 NX EX 86400, but keeping it inside Flink avoids a network call per click and is covered by Flink's checkpoints.
The signature also lets us reject clicks on impressions that are too old: an impression served three days ago that suddenly gets clicked is suspicious.
Invalid clicks. Basic rules run in the stream: too many clicks from one IP or device in a short time, known data-center IP ranges, clicks that arrive impossibly fast after the impression. These are filtered before counting, and we keep separate counts for raw and valid clicks so the numbers are explainable.
More thorough fraud detection (ML models, cross-advertiser patterns) runs later and can invalidate clicks hours or days after the fact. We don't rewrite history for that. Instead the fraud system emits adjustment events, which land in a separate adjustments table as negative counts against the original ad and minute, with a reason. The Query Service adds the two tables together, and there's an audit trail of what was removed and why.
4) How do we handle data skew when one ad gets most of the clicks?
Flink partitions the stream by the aggregation key, which starts with adId. That spreads load nicely when clicks are evenly spread across ads. They aren't. A big brand's launch, a viral video ad or a Super Bowl spot can get tens of thousands of clicks per second, and all of them hash to the same Flink task. That one task falls behind, its backpressure slows the whole job, and every advertiser's dashboard goes stale because of one ad.
Bad Solution: Add More Partitions
Approach
Increase the number of Kafka partitions and Flink tasks.
Challenges
It doesn't help. Hashing puts every event for one key on one task no matter how many tasks there are. More partitions spread the other ads more thinly while the hot one stays exactly as hot.
Good Solution: Pre-Aggregate Before the Shuffle
Approach
Add a first stage that reads clicks in any order (not keyed by ad) and sums them by (ad, minute, dimensions) for a second or two, then forwards the partial counts to the keyed stage. 30,000 clicks a second for one ad, arriving at 32 pre-aggregation tasks, become 32 messages a second carrying partial counts. The keyed task that owns the ad now does a few dozen additions per second.
This is the same as a combiner in MapReduce, and it works because counting is additive: summing partial sums gives the same total.
Challenges
Dedupe has to happen before pre-aggregation (we can't dedupe a partial count), and it's keyed by impression ID, which is naturally spread out, so that's fine. The pre-aggregation buffer adds a second or two of latency. It doesn't help when a single key is so hot that even its partial counts overwhelm one task, which is rare but possible for a very large event.
Great Solution: Salt Hot Keys, Sum on Read
Approach
For keys we know are hot, split them across several tasks by adding a salt: the key becomes (ad 77, salt 0..N-1), with the salt chosen at random per event (or per pre-aggregated batch). Each salted key is aggregated independently and written to the OLAP store as its own row, with the salt as an extra column (and part of the upsert key).
We don't need a separate step to combine the salted pieces. The OLAP store already sums rows for every query, so SELECT SUM(clicks) ... GROUP BY ad_id, minute adds up the salted rows without knowing they were split. The upsert key just includes the salt.
Which keys are hot? A small job watches per-key throughput (Flink exposes it, or the pre-aggregation stage counts it) and publishes a list of hot ads to the job, for example through a broadcast stream. Hot ads get N = 8 or 16 salts; everything else gets none, so normal ads don't pay for the extra rows.
Challenges
Salting multiplies the rows for hot keys by N, which is fine for a few hundred hot ads but would be wasteful for all of them. If dedupe were keyed by ad, salting would break it, which is another reason to dedupe by impression ID upstream. And the hot list lags reality by a little; pre-aggregation covers the gap until a newly hot ad is detected.
Skew is the follow-up interviewers love for this question, because it shows whether you understand how partitioning works. The key insight is that the problem is one key, not too few machines. Any fix has to split that key's work, either by combining before the shuffle or by spreading the key itself.
5) How do we keep advertiser queries fast over long time ranges?
Minute-level rows are perfect for "the last six hours" and terrible for "the last year." A year at minute granularity is 525,600 buckets per ad per dimension combination.
Roll up into coarser tables. Keep three tables: clicks_1m, clicks_1h and clicks_1d. The OLAP store can maintain the hourly and daily tables automatically from the minute table (materialized views in ClickHouse, rollups in Druid and Pinot). The Query Service picks the coarsest table that matches the requested granularity, so a 90-day chart reads 90 daily rows instead of 130,000 minute rows.
Expire the fine detail. Keep minute data for 30 days, hourly for two years, and daily forever. Raw clicks stay in S3 (with a cheaper storage class after a few months) for audits and reprocessing.
Lay data out for the query. Sorting by (advertiser_id, ad_id, minute) and partitioning by day means a query for one advertiser reads only their slice of the relevant days. That's what makes a sub-second query possible on a table with billions of rows.
Protect the store from noisy tenants. One huge advertiser building an enormous custom report shouldn't slow everyone else's dashboard. Put per-advertiser query rate limits and timeouts in the Query Service, and cache recent query results for a few seconds: many people on the same team open the same dashboard.
A related skew problem lives here: a few advertisers own a large share of all ads. Since the OLAP data is sorted rather than hash-partitioned by advertiser, large advertisers simply span more data blocks, and the store parallelizes their queries across them.
Final Design
The full flow:
- A user clicks an ad. The Click Service verifies the signed URL, looks up the target from an in-memory cache, publishes the click to Kafka (or a local buffer if Kafka is down) and returns a
302. - Kafka archives every raw click to S3 and feeds the Flink job.
- Flink drops duplicate clicks per impression and obvious invalid ones, pre-aggregates and salts hot ads, then counts clicks per
(ad, minute, country, device)in event-time windows with allowed lateness. - Flink upserts full window counts into the OLAP store, which rolls them up into hourly and daily tables.
- A Spark job recomputes exact counts from S3 every hour, corrects differences, and marks rows final for billing. Fraud adjustments land as negative counts.
- Advertisers query through the Query Service, which picks the right rollup, sums salted rows, and enforces per-tenant limits.
What is Expected at Each Level?
Mid-level
You should separate the redirect from the counting with a queue, and see that querying raw clicks with GROUP BY doesn't scale. You should arrive at stream aggregation into time buckets, stored in a database suited for aggregates, with some prompting on the choice of store. Server-side redirects and why they beat client-side beacons for accuracy are good to have.
Senior
You should design for accuracy end to end: durable writes to Kafka, Flink checkpointing, idempotent upserts, dedupe by impression ID and a reconciliation job. Expect to discuss event time, watermarks and late clicks, and to handle a hot ad with pre-aggregation or salting, explaining why adding partitions doesn't help. You should propose rollups for long time ranges.
Staff+
You should frame the system as fast-and-preliminary plus slow-and-final, and design around what billing needs versus what the dashboard needs. Expect to go deep on skew (hot key detection, salting that composes with dedupe and upserts), invalid traffic handled as auditable adjustments, and operating the pipeline: lag alerts, reprocessing from S3 after a bug, keeping stream and batch logic identical, and tenant isolation on the query side.