Ad-click aggregation
Every click on an ad costs the advertiser money, so each click must count once, in the minute it happened. The stream gives counts within seconds; the raw log gives the final answer.
- 1Log every click with a click ID and its event time. Counts are derived data; the log can rebuild them.
- 2Drop repeats with a seen set keyed by user, cap clicks per user, then count per ad per minute by event time.
- 3Exactly-once counts need the seen set and the counts in the checkpoint, and a sink that commits with it.
- 4The stream is fast but not final. A batch recount over the raw log corrects late clicks and late repeats.
"Design a pipeline that counts ad clicks per ad per minute, in near real time, with totals that are correct."
| question | answer assumed |
|---|---|
| How many clicks? | 1 billion a day. Peak is 5 times the average. |
| How many ads? | 2 million. 200,000 get a click in a given minute. |
| How fresh? | A minute's count shows within 30 s after the minute ends. |
| How correct? | Each click counts once. Invoices use final counts, at most a day old. |
| Late clicks? | Most within seconds. Offline phones send up to 24 hours late. |
| Repeats? | Phones and servers retry, so one click can arrive twice. |
| Fraud? | Clicks over a cap per user per ad per minute are not billed. |
| Queries? | Per-minute charts for one ad; top ads for an advertiser. |
First I confirm what a click is, how late clicks can come, and which numbers are for dashboards and which are for invoices.
| functional |
|---|
| Record a click and redirect to the landing page. |
| Count clicks per ad per minute, without repeats and fraud. |
| Chart one ad by minute; list top ads in a time range. |
| Mark each count as provisional or final. |
| non-functional | target |
|---|---|
| Redirect latency | p99 < 50 ms |
| Minute end to count shown | p99 < 30 s |
| Click lost or counted twice in final counts | 0 |
| Final counts available | within 1 h, rechecked daily |
| Raw log kept | 7 days in the log, 2 years archived |
Dashboards can show a provisional count; invoices must use a count that a recount of the raw log confirms.
| quantity | arithmetic | result |
|---|---|---|
| Clicks | 1 B a day ÷ 86,400 | ≈ 12,000/s; 5× peak ≈ 58,000/s |
| Raw log | 1 B × 200 B | 200 GB a day; 7 days × 3 copies = 4.2 TB |
| Ingest bandwidth | 58,000/s × 200 B | ≈ 93 Mbit/s at peak |
| Seen set | 58,000/s × 190 s kept × 72 B (measured) | ≈ 11 M IDs, 0.8 GB over all tasks |
| Minute rows | 200,000 active ads × 1,440 minutes | 288 M rows a day; × 32 B ≈ 9.2 GB before compression |
| Row writes | 200,000 rows each minute ÷ 60 | ≈ 3,300/s into the OLAP table |
Inputs are the answers in panel A. The seen set keeps an ID for the watermark delay (10 s), the lateness (120 s) and the minute (60 s). Bytes per ID measured in a Go map. Method: R2.
Clicks average about 12,000 a second and peak near 58,000. The table gains about 288 million minute rows a day.
| call | for | retry safe by | success | errors |
|---|---|---|---|---|
| GET /c/{signed_click_id} | a click on an ad link | the click ID | 302 to the landing page | 400 bad signature |
| POST /v1/clicks [{click_id, ad_id, ts}] | batched clicks from an app | the click IDs | 202 | 400, 429 |
| GET /v1/ads/{id}/clicks?from&to&step=1m | a chart | a read | 200 + points, each final or not | 400, 403 |
| GET /v1/advertisers/{id}/top-ads?from&to&limit=10 | a leaderboard | a read | 200 + ads, clicks | 400, 403 |
- The ad server signs the click ID when it shows the ad. A forged or replayed link fails the check or repeats a known ID.
- Each point carries final: true once the batch recount has written it.
The click endpoint never waits for counting. A retried click carries the same click ID, so the pipeline drops the repeat.
| store | key | holds | kept |
|---|---|---|---|
| Click log | user | click_id, ad, user, event time | 7 days |
| Job state | user, click_id | The seen set: event time of each click ID | 190 s |
| Job state | user, ad, minute | Clicks so far, for the fraud cap | until the minute closes |
| Job state | ad, minute | The count, and the count last sent | until the minute closes |
| OLAP table | ad, minute | Clicks; who wrote it last | 90 days; hour rollups 2 years |
| Raw archive | hour | Columnar files of the raw log | 2 years |
- The log is keyed by user, so every copy of a click reaches the task that holds its user's seen set.
- A minute "closes" when the watermark passes its end plus the lateness.
-- The OLAP table: clicks per ad per minute. The stream job writes each minute; the batch recount
-- overwrites closed minutes. A column store holds the same shape, sorted by (ad, minute).
CREATE TABLE ad_clicks_minute (
ad text NOT NULL,
minute timestamptz NOT NULL,
clicks bigint NOT NULL,
source text NOT NULL CHECK (source IN ('stream', 'batch'))2,
PRIMARY KEY (ad, minute)1
);
CREATE INDEX ad_clicks_by_minute ON ad_clicks_minute (minute, ad);3
-- The last checkpoint the stream job committed, in the same transaction as its rows.
CREATE TABLE ad_sink_commits (
job text PRIMARY KEY,
checkpoint int NOT NULL4
);- 1One row per ad per minute. A chart for one ad is one range of this key.
- 2Who wrote the row last. Batch rows are final; the stream never overwrites them.
- 3Top ads in a time range: read a range of minutes, sum per ad.
- 4The last checkpoint committed, written in the same transaction as its rows.
The log holds raw events keyed by user. The job holds a seen set and counters per user. The OLAP table holds one row per ad per minute.
Step 1: Click
- The ad link carries a signed click ID, made when the ad was shown.
- The service checks the signature, appends the event to the log keyed by user, and returns 302 to the landing page.
- The event holds the click ID, ad, user, and the event time from the device.
If it fails
The log is slow: the service buffers events locally and returns the redirect anyway. A retry sends the same click ID, so the job drops it.
The click service logs the event and redirects. The stream job cleans and counts by event time and commits with each checkpoint. An hourly batch recount makes the counts final.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Kafka | Partitions by key, retention, offsets | Every copy of a click goes to one partition; a restore or a backfill reads again from an offset. | Change data capture |
| Kafka | Idempotent producer (on by default since 3.0) | A producer retry does not write the event twice. Device retries still need the click ID. | Any producer |
| Flink | Keyed state with a TTL | The seen set and the fraud counters, per user, expired by time. | Sessions, joins |
| Flink | Event-time tumbling windows, allowed lateness, side outputs | Counts per minute; late updates; very late clicks set aside. | Any rollup |
| Flink | Two-phase aggregation (local, then global) | Partial counts per task before the shuffle by ad, so the hot ad does not load one task. | Skewed group-bys |
| Flink | Checkpoints, two-phase-commit sinks | State, offsets and output commit at the same point. | Exactly-once pipelines |
| Column store | Sorted by (ad, minute), compressed columns, rollups | Sums over millions of rows in milliseconds. A replacing table engine keeps the newest version of a row. | Metrics, logs |
| Spark | Batch jobs over columnar files | The hourly recount over the raw archive, with every late click in view. | Backfills |
| Postgres | INSERT ... ON CONFLICT with a WHERE | The lab's OLAP table: the stream upserts; it never overwrites a batch row. | Idempotent sinks |
| Postgres | unnest() of arrays in one statement | The reconcile writes a whole hour in one round trip and one transaction. | Bulk upserts |
Kafka gives me a replayable log keyed by user. Flink gives me keyed state with a TTL, event-time windows and checkpoints. A column store gives me fast sums over ad and minute.
| method | where | status |
|---|---|---|
| Count every event | Service | Not approved |
| Seen set of click IDs in keyed state, with a TTL | Flink | Approved |
| Seen set in task memory | Service | Not approved |
| Bloom filter of click IDs | Service | A false positive drops a real click |
| Unique key on click ID in the database | Postgres | Low rates: one write per click |
| Cap per user per ad per minute | Flink | Approved |
| A fraud model scores clicks later | Spark | Feeds the recount |
- Key the first stage by user. The seen set and the cap are both per user, so one task owns both.
- A TTL shorter than the delay plus the lateness lets a late repeat count twice. Panel I shows how many.
- A Bloom filter saves memory but drops a real click on a false positive (B10).
on click c, keyed by c.user1:
IF c.id in seen, not expired: DROP // a repeat
seen[c.id] = c.event_time // expires after TTL2
n = clicks[c.user, c.ad, minute(c)]
IF n >= CAP: DROP to the fraud output3
clicks[c.user, c.ad, minute(c)] = n + 1
partial[c.ad, minute(c)] += 1 // task memory, not state4
on watermark w:
SEND partial[ad, m] WHERE m + 60 <= w // keyed by ad
on barrier:
SEND every partial, then save seen and clicks5- 1Every copy of a click comes from the same user, so it reaches the same task and the same seen set.
- 2Event time, not wall time, so a replay expires the same IDs. The lab kept IDs 30 s.
- 3The cap was 3. The bot in the lab clicked 40 times in each of 2 minutes.
- 4Partial counts are sent before every barrier, so the checkpoint never needs them.
- 5The seen set is state. A restore brings it back with the offsets it matches.
Tested source Go: the clean stage
// Process handles one click.
func (s *Clean) Process(c *streams.Ctx, r streams.Rec) {
id, ad, attempt, err := parse(r.Val)
if err != nil {
c.Count("bad", 1) // a malformed event goes to a side output, not a count
return
}
minute := r.At - r.At%Minute
if s.isSeen(c, r.Key, id) { // 1. a click ID seen before: drop
c.Count(fmt.Sprintf("dup@%d", minute), 1)
return
}
s.markSeen(c, r.Key, id, r.At)
f := "f" + ad + "@" + strconv.Itoa(minute) // 2. more than Cap clicks: fraud
n := c.Get(r.Key, f)
if s.counterGone(minute, c.Watermark()) {
n = 0
}
if n >= s.Cap {
c.Count(fmt.Sprintf("fraud@%d", minute), 1)
return
}
c.Set(r.Key, f, n+1)
if attempt > 1 { // a retry the seen set no longer held: it counts twice
c.Count(fmt.Sprintf("retry@%d", minute), 1)
}
if !s.PreAgg { // 3. one record per click, or one partial count per ad and minute
c.Emit(streams.Rec{Key: ad, At: minute, N: 1, D: 1})
return
}
if s.partial == nil {
s.partial = map[[2]string]int{}
}
s.partial[[2]string{ad, strconv.Itoa(minute)}]++
}
// Advance sends the partial counts of closed minutes. Every 10 s of watermark it also deletes
// expired click IDs and fraud counters, to free memory; reads treat them as gone at once.
func (s *Clean) Advance(c *streams.Ctx, wm int) {
s.send(c, func(minute int) bool { return minute+Minute <= wm })
if wm < s.swept+sweepEvery {
return
}
s.swept = wm
c.Scan(func(key, name string, v int) {
switch name[0] {
case 's':
if s.idGone(v, wm) {
c.Del(key, name)
}
case 'f':
_, at, _ := strings.Cut(name, "@")
if m, err := strconv.Atoi(at); err == nil && s.counterGone(m, wm) {
c.Del(key, name)
}
}
})
for id, v := range s.seen {
if s.idGone(v, wm) {
delete(s.seen, id)
}
}
}
// Flush sends every partial count before a barrier, so no count lives outside keyed state when
// the task saves its part of the checkpoint.
func (s *Clean) Flush(c *streams.Ctx) { s.send(c, func(int) bool { return true }) }
I drop repeats by click ID with a seen set keyed by user, and I cap clicks per user per ad per minute. In the lab that removed 418 repeats and 75 bot clicks.
| events in the log | 621 |
| repeats the seen set dropped | − 43 |
| clicks over 3 per user per ad | − 0 |
| stream count | 558 |
| of which: retries counted twice | + 8 |
| missing: clicks dropped late | − 20 |
| batch recount | 570 |
| after reconciliation | - |
- totals
- all ads: stream 5,958, batch 6,006
- minutes off
- 10 of 10
- hot ad
- ad07 at 12:00: stream 269, batch 275
- rows fixed
- 69 of 383 (ad, minute) rows
- settings
- seen set 30 s, delay 10 s, lateness 120 s
The stream: 5,958 clicks; the batch recount: 6,006. Each minute's stream count equals the batch count plus repeats counted twice, minus late clicks dropped; the lab checks this for every minute.
The stream was off in 10 of 10 minutes: 63 late repeats counted twice and 111 late clicks dropped. Reconciliation made every minute equal the recount.
| method | status | why |
|---|---|---|
| Count by arrival time | Not approved | A late click lands in the wrong minute; a replay gives another answer. |
| Event time, drop late clicks | Not approved | Offline phones are never billed. |
| Event time, lateness, updates | Approved | Late clicks within the bound update the minute. |
| Hold minutes open for 24 hours | Small key space | State for every ad and minute of a day. |
| Batch recount overwrites closed hours (Lambda) | Approved | Every late click and repeat in view. Two code paths. |
| Replay the log into a new table (Kappa) | Log keeps the range | One code path. For bug fixes and rule changes. |
- Both paths must share one rule set for repeats, fraud and minutes. Put it in one library both jobs call.
- The recount writes the whole hour in one statement. A rerun writes the same values, so it is safe to repeat.
- More on Lambda, Kappa and backfills: B7.
on partial p, keyed by p.ad:
IF p.minute + 60 + LATENESS <= watermark:
DROP to the late output1 // the recount has it
count[p.ad, p.minute] += p.n
IF the minute was sent: SEND count // an update
on watermark w:
SEND count[ad, m] WHERE m + 60 <= w // the first result3
forget m once m + 60 + LATENESS <= w- 1The lab dropped 111 clicks here. The batch recount counts them.
- 2The sink overwrites the row with the new absolute count.
- 3The watermark trails the newest event by the delay, so a minute is sent soon after it ends.
Tested source Go: count per key per window
// Process adds a record to its window, or drops it when the window's state is gone.
func (w *WindowCount) Process(c *Ctx, r Rec) {
start := r.At - mod(r.At, w.Size)
if start+w.Size+w.Lateness <= c.Watermark() {
c.Count("late", r.N)
c.Count(fmt.Sprintf("late@%d", start), r.N)
return
}
n := c.Get(r.Key, "n"+strconv.Itoa(start)) + r.N
c.Set(r.Key, "n"+strconv.Itoa(start), n)
if sent := c.Get(r.Key, "e"+strconv.Itoa(start)); sent > 0 {
c.Emit(w.result(r.Key, start, n, n-sent)) // the window already fired: send an update
c.Set(r.Key, "e"+strconv.Itoa(start), n)
}
}
// Advance fires every window the watermark has passed and forgets windows past their lateness.
func (w *WindowCount) Advance(c *Ctx, wm int) {
c.Scan(func(key, name string, n int) {
start, ok := windowOf(name, "n")
if !ok {
return
}
if start+w.Size <= wm && c.Get(key, "e"+strconv.Itoa(start)) == 0 {
c.Emit(w.result(key, start, n, n))
c.Set(key, "e"+strconv.Itoa(start), n)
}
if start+w.Size+w.Lateness <= wm {
c.Del(key, name)
c.Del(key, "e"+strconv.Itoa(start))
}
})
}
every hour, for the hour that closed LATENESS ago:
clicks = that hour of the raw log, late ones included1
drop every repeated click ID2 // no TTL here
apply the same CAP per user per ad per minute
counts = GROUP BY ad, minute
IN ONE STATEMENT: write counts, source = 'batch'3
stream sink: never overwrite a 'batch' row4- 1The archive file of an hour is read after the lateness, so clicks that came late are in it.
- 2No TTL here: the batch sees the whole hour at once.
- 369 of 383 rows changed in the lab.
- 4A late stream update after the recount cannot undo a final count.
Tested source Go: reconcile · SQL: reconcile and the stream sink
// Reconcile writes the batch recount over the stream's rows for every minute in [from, to),
// in one statement. It returns the rows it wrote.
func Reconcile(ctx context.Context, db *pgxpool.Pool, batch map[Key]int, from, to int) (int64, error) {
var ads []string
var minutes []time.Time
var clicks []int64
for k, n := range batch {
if k.Minute >= from && k.Minute < to {
ads = append(ads, k.Ad)
minutes = append(minutes, Base.Add(time.Duration(k.Minute)*time.Second))
clicks = append(clicks, int64(n))
}
}
tag, err := db.Exec(ctx, queries["reconcile"], ads, minutes, clicks)
if err != nil {
return 0, fmt.Errorf("reconcile minutes %d to %d: %w", from, to, err)
}
return tag.RowsAffected(), nil
}
-- The batch recount of closed minutes replaces the stream's rows in one statement.
INSERT INTO ad_clicks_minute (ad, minute, clicks, source)
SELECT ad, minute, clicks, 'batch'
FROM unnest($1::text[], $2::timestamptz[], $3::bigint[]) AS b(ad, minute, clicks)
ON CONFLICT (ad, minute) DO UPDATE SET clicks = EXCLUDED.clicks, source = 'batch';
-- The stream sink, inside the checkpoint's transaction: write the minute's count. A minute the
-- batch recount has corrected is never overwritten by the stream.
INSERT INTO ad_clicks_minute (ad, minute, clicks, source) VALUES ($1, $2, $3, 'stream')
ON CONFLICT (ad, minute) DO UPDATE SET clicks = EXCLUDED.clicks
WHERE ad_clicks_minute.source = 'stream';The stream holds each minute open for 2 minutes. Anything later goes to the recount, which writes final counts over the stream's rows for every closed hour.
| 4 tasks per stage | no pre-aggregation | partial counts first |
|---|---|---|
| Records into the hot ad's task | 3,429 | 442 |
| Source ticks stalled by backpressure | 1,335 | 75 |
| Ticks to read the log | 2,020 | 1,753 |
| method | status |
|---|---|
| Key by ad only | Not approved |
| Partial counts per task, then combine by ad | Approved |
| Salt the key: ad plus a number from 0 to 7 | Needs a second sum |
Each task handles 2 items a tick; a full channel stops its sender. Partial counts are sent when a minute closes and before every barrier.
Keyed by ad, the hot ad's task fell behind and stalled the sources 1,335 times. Partial counts per task cut its input from 3,429 records to 442.
| seen set in | clicks | recount | rows wrong |
|---|---|---|---|
| Keyed state, in the checkpoint | 6,006 | 6,006 | 0 |
| Task memory | 6,019 | 6,006 | 9 |
- The job restored checkpoint 2 and read 804 clicks again. The sink had committed nothing past that checkpoint.
- This run keeps every ID and accepts every late click, so the only cause of a difference is the crash.
- Sinks, barriers and rescaling in depth: C16.
After a crash and restore, the job with the seen set in keyed state matched the recount in all 383 rows. With the seen set in task memory, 9 rows were wrong.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A phone sends a click twice | Two events, one click ID. | The seen set drops the second copy. | Seen set |
| A repeat arrives after its ID expired | The stream counts it twice. | The recount drops it and overwrites the minute. | Recount |
| A click arrives hours late | The stream drops it. | It is in the archive; the next daily recount counts it. | Recount |
| A stream task crashes | Events since the checkpoint are read again. | The seen set, counters and sink all roll back to the same checkpoint. | Checkpoint |
| The sink crashes mid-commit | The transaction rolls back. | The checkpoint is not complete; the replay writes the rows again. | Transaction |
| One ad gets half of all clicks | One count task falls behind; sources stall. | Partial counts per task, then one sum per ad. | Pre-aggregation |
| A bot clicks one ad 40 times a minute | Clicks over the cap. | The cap drops them to a fraud output for review. | Cap |
| A device clock is wrong by a day | Event time far ahead of arrival. | Reject or clamp event times more than a few minutes ahead of the receive time. | Validation |
| The stream job has a counting bug | Wrong counts for days. | Fix it, replay the log into a new table, switch reads (Kappa). | Replay |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres: insert each click with a unique click ID; GROUP BY ad and minute for charts. | About 2,800 clicks a second, one per commit, in the lab. | Inserts near that rate, or charts that scan millions of raw rows. |
| 2 | A log and one consumer with a seen set, minute counts and a transactional sink. | About 14,000 rows a second at 1,000 rows per commit; the counting logic ran 85,000 clicks a second. | State outgrows one process, or one consumer falls behind the peak. |
| 3 | A stream processor: keyed state, checkpoints, partial counts per task. | Add tasks up to the partition count. This prompt's peak is about 58,000 clicks a second. | Charts and top-ads queries slow down as rows reach hundreds of millions. |
| 4 | A column store sorted by ad and minute, with hour rollups. | About 288 M rows a day. In Postgres, top ads over 60,000 rows took 26.8 ms. | Invoices need counts that survive late clicks and late repeats. |
| 5 | An hourly and a daily recount over the raw archive. | Final counts; the reconcile wrote about 37,000 rows a second in one statement. | Top of the ladder. Regions next: count per region, then merge. |
Demand from panel C. Lab rates are one client on one 8-core laptop, Postgres 16, median of 3 runs; read them as orders of magnitude. The click job is the lab's engine on one goroutine, not a cluster.
I start with a table and a GROUP BY. Next comes a log and one consumer with a seen set. Then a stream processor with partial counts and a column store, and a recount on top.
| question | answer | deeper |
|---|---|---|
| How does the job stay exactly once after a crash? | Barriers save offsets and state at one point, and the sink commits with that checkpoint. A replay then writes nothing twice. | C16 |
| How do watermarks and lateness work? | The watermark trails the newest event time by a delay, and a window fires when it passes the end. Lateness keeps the window open for updates. | B7 |
| How many partitions does the log need? | At least the number of tasks you will run, with headroom; keys stay on one partition. Adding partitions later moves keys. | B6 |
| Can you save memory on the seen set? | A Bloom filter uses a few bits per ID but drops a real click on a false positive. Keep exact IDs for billing. | B10 |
| How do you store minute counts for 2 years? | Roll minutes up to hours and days, and drop old minute partitions. Queries pick the coarsest table that answers them. | B12 |
| How do invoices use these counts? | Bill from final rows only, and post each invoice line once with an idempotency key into a ledger. | T9 |
| One advertiser's ads are all hot. Now what? | Pre-aggregate per task, and salt the key if one ad still exceeds a task. Sum the salted parts in a second step. | X2 |
| How do you know the pipeline is healthy? | Alert on consumer lag in seconds, checkpoint age, late-output rate, and the gap between stream and recount per hour. | O3 |
0 of 10 known
A phone sends the same click twice, 4 s apart. What stops a double count?
A retry arrives 90 s after the first copy. The seen set keeps IDs for 30 s. What happens?
A click arrives 4 minutes late. Lateness is 120 s. Where does it go?
Why must the seen set be in the checkpoint?
50% of clicks are on one ad. What breaks, and what fixes it?
What does reconciliation change, and how often?
Lambda or Kappa for this prompt?
Why key the first stage by user, not by ad?
Why count by event time and not by arrival time?
How do the top-ads queries stay fast?
- demand
- About 12,000 clicks a second; 58,000 at a 5× peak.
- seen set
- 72 B per ID in a Go map; about 0.8 GB for 190 s at peak.
- rows
- 288 M minute rows a day for 200,000 active ads.
- stream off
- 63 repeats counted twice and 111 late clicks dropped, of 6,562 events.
- recount
- Changed 69 of 383 rows; reconcile about 37,000 rows a second.
- hot ad
- 3,429 records into one task, or 442 with partial counts.
- queries
- One ad, one day: 1.3 ms. Top ads, 60,000 rows: 26.8 ms.
Lab: Go on one goroutine and Postgres 16 on an 8-core laptop, median of 3 runs. Recorded runs: seed 15, 4 partitions, 4 tasks per stage.