Systemsfor Aravinda
0 / 78 core
Week 10 · Case studies

Design ad click aggregation

1.5 hours · core path

Read first: Kafka, Stream processing, Time-series data

In one sitting

A click arrives more than once and sometimes arrives late. Ingest appends the raw event to a log, workers drop duplicate click ids, and windowed counts live in a different store the dashboard actually reads. A late event belongs to the minute it happened, and a nightly recompute overwrites that minute instead of adding to it.

A click is a fact you will see twice and sometimes see late. The advertiser wants a count per ad per minute. Those cannot be the same store. If you count in the place you append, you either throw away the replay or you add the click every time you read the log back. The raw log is the memory. The aggregate is a projection you are allowed to throw away and rebuild.

Requirements

Two users, and they never meet in the architecture. A person clicks an ad. An advertiser reads a chart. You are designing the path between the click and the chart, not the auction that chose the ad.

It must:

  • Accept a firehose of clicks, each with a click id, an ad id, and a timestamp from the client or the redirect.
  • Count each click id once inside the window you bill or display.
  • Put the count in the minute the click happened, not the minute you happened to process it.
  • Let a late click correct a minute you already showed, and label the first number as preliminary.
  • Serve the chart from the aggregate. A dashboard query does not scan the raw log.

Non-goals:

  • The auction, the bidding, and the pacing of budgets. Those produce the ad that was shown. This page starts at the click.
  • A per-person profile. A user id on the aggregate is how you blow up a time series. The raw log can carry a hashed id if a later job needs it. The rollup does not.
  • Cross-device identity and attribution arguments. The count is clicks, not “people who later bought.”
  • Invoicing. You can say the sealed daily count feeds a bill. You do not design the payment.

Latency assumption: the redirect that records the click adds a small batch delay, on the order of 10 ms, plus a produce inside the region. The chart can lag the click by a couple of minutes. An advertiser who needs a number they can invoice waits until the day is sealed. Those are two products sharing one log. Do not pretend the live chart is the bill.

Estimation

Assumptions:

  • 50,000 clicks per second on average. Peak is 3 times that, inside the 2x to 5x band. This is a large-product planning assumption, not a measured total from any company.
  • A raw record is 200 bytes: click id, ad id, event time, placement, country. No user id in the aggregate path.
  • A click id is 16 bytes in the dedup set.
  • You keep the raw log for 30 days and the streaming dedup set for 24 hours.
  • About 2 million ads exist. Most minutes for most ads are empty, and you do not store empty minutes.
  • Replica factor 3 on the raw log.

A day is 86,400 seconds. A 30-day month is about 2.6e6 seconds. Use both.

clicks per day = 50,000 * 86,400 = 4.32e9
raw per day    = 4.32e9 * 200 bytes = 8.64e11 bytes = 864 GB
30 exact days  = 30 * 864 GB = 25.9 TB
month shortcut = 50,000 * 2.6e6 * 200 bytes = 26 TB
with 3 replicas, 30 days = about 78 TB

average ingress = 50,000 * 200 = 10 MB/s
peak ingress    = 30 MB/s

dedup state, one day of ids = 4.32e9 * 16 bytes = about 69 GB

dense minute rollup, if every ad had every minute
  2e6 ads * 1,440 * 16 bytes = about 46 GB per day

Seventy-eight terabytes is the raw log, replicated, for a month. That is the store you replay. The aggregate is much smaller once empty minutes stay absent, and it is the store you query. The 46 GB figure is a ceiling you should be embarrassed to hit. It assumes every ad clicks at least once a minute, all day. Real series are sparse. The ceiling is how you notice someone materializing the cross product.

The dedup set is the awkward middle: 69 GB of ids per day, spread across workers. It is not the raw log and it is not the chart.

A million clicks a day would be about 12 per second. You are four orders of magnitude above that on ingest and still only at 10 MB/s average. The firehose is a record rate and a correctness problem. It is not a bandwidth emergency. Peak at 30 MB/s, split across 64 partitions, is under 0.5 MB/s on each partition. You pick 64 so a consumer group can run tens of members and so the dedup state per partition is about 69 GB / 64, roughly 1 GB. That 1 GB is why the partition count exists. A single process holding a 69 GB set of ids is the design you did not want.

High-level design

flowchart LR
  browser[Browser]
  ingest[Ingest]
  raw[Raw click log]
  dedup[Dedup workers]
  clean[Deduped log]
  windows[Window counters]
  series[Aggregate store]
  batch[Nightly recompute]
  dash[Dashboard]
  browser --> ingest --> raw
  raw --> dedup --> clean --> windows --> series
  raw --> batch --> series
  dash --> series

Ingest appends to the raw log and only then completes the redirect. The log is partitioned by a hash of the click id, so a retry of the same click lands on the same partition. Dedup workers are a consumer group on that log. They emit a cleaned click to a second log, partitioned by ad id, and only if the click id is new. Window counters consume the cleaned log and increment a minute bucket in the aggregate store. The dashboard reads the aggregate.

The nightly job reads the raw log for one event-time day, dedups by click id from scratch, and overwrites that day’s buckets. Overwrite. The stream is the fresh chart. The batch result is the sealed one.

Deep dive

Dedup by click id, on the right key

Browsers retry. Redirects fire twice. A client with a flaky radio sends the same click id an hour later. If you increment on every delivery, the chart is a function of your failures.

The click id is minted once, at the first hop, and stuck on every retry. The dedup worker for a partition keeps the ids it has seen in the last 24 hours. A repeat is dropped. A new id is forwarded, with its ad id and its event time, to the cleaned log.

The 24-hour set is not a 30-day set. You cannot hold a month of ids in the streaming workers at 69 GB per day. A duplicate that arrives after 24 hours can pass the streaming filter. That is acceptable for the live chart and unacceptable for a sealed number, which is why the batch job dedups from the raw log with no such window and then replaces the day’s aggregate. Two layers, two jobs. The stream is allowed to be slightly wrong. The batch is the correction.

Partition the raw log by click id so the set for an id has one home. Partition the cleaned log by ad id so all of an ad’s clicks meet in one counter. Those keys are different on purpose. If you partitioned everything by ad id, a viral ad would pin its dedup set to one worker: 10 percent of clicks is about 7 GB of ids plus the CPU of hashing them, on top of the counter. The counter itself is a cheap increment and can live on one partition. The set of ids should be spread by the id, which is close to random. A hot ad makes one counter hot. It does not make one giant set. Partitioning does not split that one counter, and it does not need to. An increment at a few thousand per second is fine. More partitions of the cleaned log would not move a single ad id anyway.

Do not use a probabilistic set if this number is heading toward a bill. A structure that sometimes says “seen” for a new id under-counts, quietly, in the advertiser’s favor or against them depending on who you ask, and you cannot explain the miss. Exact ids, partitioned, are the design. A bloom filter is a memory optimization you reach for when the product has said a small error is cheaper than the RAM. Say that trade if they push. Do not start there.

Event time, windows, and late clicks

Stream processing distinguishes event time from processing time. Event time is when the click happened. Processing time is when you handled it. A tumbling window of one minute, on event time, is the dashboard’s finest bucket. Hour and day are sums of those minutes, or they are their own buckets written alongside. Summing minutes is less storage. Writing the hour explicitly makes the dashboard query cheaper. Either is fine if you say which. This design writes the minute, and a rollup job writes the hour from minutes. The day the batch seals is written as a day total too.

A phone that was offline uploads a click 20 minutes later. If you bucket by processing time, you punch a hole in the old minute and a spike in the current one. The advertiser does not trust the chart, and they are right. Bucket by the timestamp on the event. Drop or clamp timestamps that are in the future by more than a small skew, or that are older than the raw retention. Assumption: ignore event times more than 3 days old or more than 2 minutes in the future. A clock on a phone can be nonsense. You do not let it create a bucket in 1999.

A watermark is a guess that events older than some bound are late. Assumption: the streaming job waits 2 minutes after a minute ends, then publishes the bucket as preliminary and moves on. A click for that minute which arrives inside the 2 minutes is just another increment. A click that arrives later is a late event. You can still add it to the bucket and mark the bucket corrected, or you can wait for the nightly overwrite to replace the whole day. This design does both with a bias: the stream applies late events for the open day so the chart moves, and the batch replaces the day so any double-count from a dedup miss is erased. The label on the chart matters. Preliminary means the watermark passed and the batch has not sealed the day. Sealed means the overwrite landed.

The bug that makes the chart double at midnight is a batch job that increments. The stream already counted the click. The batch counts it again and adds. Every sealed day steps up. The batch writes the count it computed, it does not add that count to whatever is there. Idempotent overwrite of a day is the whole trick. A rerun of the batch after a bug fix does the same thing and heals the day.

The raw log and the aggregate stay different. You can delete and rebuild a week of aggregates from the log. You cannot rebuild the log from the aggregates, because the aggregate threw away the click id and the long tail of dimensions. CQRS, from the event sourcing page, is this split: a write model shaped like the event, a read model shaped like the query, and lag between them. You do not need a full event-sourced domain. You need to tolerate that the chart and the log disagree until the seal.

What you refuse to tag

Tags are the indexed dimensions of the series. Raw events are not tags. The dimensions this dashboard can filter are ad id, country, and placement. Assumption: you need per-ad minute counts for everyone, and per-ad per-country counts at hour granularity for ads that actually have clicks in that country. You do not need ad times country times placement times minute as a stored cross product. Two million ads, 200 countries, and 50 placements is 2e10 combinations if you materialize the cube. Most of those combinations never occur, and the ones that occur once are why high cardinality takes the store down. Store the series you named. If a product manager wants a new cut, it is a new rollup with a cardinality you estimated, not a free tag on the existing one.

A user id as a tag is the failure mode from the time-series page, applied here. The raw log already has one row per click. Putting the same cardinality into the aggregate copies the firehose into the system you meant to keep small.

Ingest has a bound. The redirect waits for a durable append to the log, batched about 10 ms so you are not doing a round trip per click in the worst way. If the log is down, a local buffer holds a short burst. Assumption: 2 seconds of peak, 150,000 times 200 bytes times 2, which is 60 MB. When that buffer is full, the redirect fails and the click is not counted. You under-count during an outage. You do not grow the buffer until the process dies, and you do not complete the redirect and then drop the event, because that is a silent miss on a number someone may bill. The 60 MB hides a blip. It does not hide an hour. Say which failure you picked.

Tradeoffs

Choice What you gain What you spend
Raw log and aggregate as two stores Replay and rebuild, and a chart query that is a range read Lag, and a job that must overwrite rather than add
Count in the log’s consumer and nowhere else One system A replay double-counts, and the dashboard scans too much
Exact click-id set, partitioned, kept 24 hours Retries a minute later do not move the chart About a gigabyte of ids per partition, and a late duplicate can still pass
Bloom filter in front of the set Less memory Silent under-counts, a bad fit if the number is a bill
Bucket by event time, watermark of 2 minutes A late phone does not spike the current minute Preliminary buckets move after you published them
Bucket by processing time Simple code Holes in the past, spikes now, and advertisers stop believing you
Nightly overwrite from the raw log A sealed day you can rerun A day of waiting, and compute over 864 GB
Nightly increment on top of the stream None that survives contact with the chart The day doubles when the job succeeds
Fail the redirect when the buffer is full You do not count clicks you did not store, and you do not run out of memory The click is lost for good if the client does not retry with the same id

Failure modes

  • The log is down and ingest keeps accepting into an unbounded buffer. Symptom: memory grows, then the process dies and takes a large buffer of uncounted or half-counted clicks with it. Cap the buffer. Fail the redirect past the cap.
  • Clients retry and you have no click id. Symptom: an outage followed by a spike that is retries, not interest. Dedup by id absorbs a retry storm’s effect on the count. It does not absorb the bytes. The log still sees twice the ingress. Size the peak with a retry multiplier in mind, or shed at ingest when you are over a limit.
  • A viral ad, and the dedup set is partitioned by ad id. Symptom: one worker holds a multi-gigabyte set and falls behind, lag on that partition only. Partition dedup by click id. Let the counter be the hot key. An increment can take it.
  • Late events after you thought the minute was done, no label. Symptom: yesterday’s chart changes and finance thinks it is a bug. Call it preliminary until the batch seals it.
  • The batch adds to the streaming count. Symptom: a step up at midnight, every day, about equal to the day’s real clicks. Overwrite the day.
  • A worker restarts, re-reads the log, and increments again for ids that aged out of the dedup set. Symptom: a quiet double-count the batch will fix tonight and the live chart will show all day. The dedup set has to be checkpointed with the offset, or the open day is only trustworthy after the overwrite. The aside below is the checkpoint. The failure is the increment without the id.
  • Someone adds user id as a tag on the aggregate. Symptom: the series store’s memory climbs and queries time out, while ingress looks normal. The raw log was the right home for that id.
  • Watermark of zero. Symptom: every slightly delayed click is “late,” the chart jitters, and the correction path does more work than the happy path. Two minutes is an assumption. Measure the delay distribution before you shrink it.

Consistency between the live chart and the sealed day is lag, and you promised it. Durability sits on the raw log: a click you acknowledged to the redirect is in the log, replicated, or you did not acknowledge it. The aggregate can be rebuilt. Do not invert that.

In the interview

First five minutes: firehose into a log, dedup by click id, count by event time, dashboard reads a different store, batch overwrites the day. Put 50,000 clicks a second and 864 GB a day on the board, and the 69 GB dedup set next to them so you do not hand-wave the state.

Skip the auction. If they ask where the ad came from, say “not this design” and draw the click.

The question that follows is a late event, or “why not count in the database you query?” Answer with event time versus processing time, the watermark as a guess, and the overwrite. Then the midnight-doubling bug, because it shows you know the two stores can both count the same click if you let them.

Check yourself

A click from 20 minutes ago arrives now. Which minute gets the count, and what did you assume?

The event-time minute, 20 minutes ago, not the processing-time minute. The assumption is a watermark around 2 minutes, so this click is late. The streaming bucket for that minute is corrected or left for the nightly overwrite, and the chart should not pretend the number was already sealed.

The nightly job reads the raw log and adds its totals onto the streaming counters. What does the chart do at midnight?

It steps up by about a day’s clicks, because the stream already counted them. The batch has to write the count it computed for that day, replacing the buckets. A rerun then heals a bad day instead of tripling it.

Why are the raw log and the dedup set partitioned by click id, while the counters are partitioned by ad id?

The same click id must always see the same dedup set, and click ids spread. The counter needs every clean click for one ad in one place so the increment is local. A viral ad would pin a huge id set to one worker if both jobs used the ad id. The hot counter is a cheap increment. The hot set is not.

Fifty thousand clicks a second at 200 bytes, kept 30 days with three replicas. What is the raw store, and what is the 2.6e6-second shortcut for a month?

Per day, 50,000 times 86,400 is 4.32e9 clicks, times 200 bytes is 864 GB. Thirty days is 25.9 TB, times 3 is about 78 TB. The shortcut month of 2.6e6 seconds gives about 26 TB before replicas, close to the exact 30-day product. The shortcut is for the estimate, and the replica factor is what turns it into the disk you buy.

Based on: Kafka, Jay Kreps, Neha Narkhede, and Jun Rao; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.