CodingNodes Space play · ←→ step · R restart

The problem

Most of the systems in this course are lookups: a request goes in, a record comes out, roughly one for one. An ad-click counter is the opposite. It is a counting system. A flood of tiny events comes in — each one a click on some ad, by some user, at some moment — and a handful of numbers comes out: clicks per ad per minute on the live dashboard, clicks per advertiser per day on the bill. The read path is rare and small; the write path is a firehose. That inversion is what shapes every decision below.

The interesting part is not the volume, it is the correctness. A click that is retried by the client, or relayed through a proxy, or double-tapped, can arrive more than once, and counting it twice is a billing error, not a blip. So the design has to get each click counted exactly once, at any rate, and then roll it up into the numbers people actually read. We will build the dumb stateless edge, the durable log that decouples and fans the clicks out, the recent-set that makes the count exactly-once, and the two-phase aggregation that feeds a rollup the read path never looks past.

Requirements

Functional — what it must do

  • Receive: accept click events from the ad network at a very high rate and return a fast acknowledgement, without holding a request open or touching a database.
  • Count: attribute each click to an (ad, window) pair and sum it into a running total, dropping a click that is a retry of one already seen.
  • Report: serve per-ad and per-advertiser click totals over a time window to the live dashboards, and per-day totals to billing.

Non-functional — how well it must do it

  • Throughput: absorb a burst of hundreds of thousands of clicks per second at peak — the viral-creative case — and keep the endpoint responsive.
  • Correctness: a click that is retried, relayed, or double-tapped must be counted once, not twice; a double-count is a direct billing error.
  • Latency: a live dashboard sees a click within a couple of seconds; a billing-grade total is available minutes later, exactly.
  • Availability: the ingestion endpoint stays up even if every downstream counter is down — clicks are buffered in a durable log, never dropped.

Scale — how much it must take

  • On the order of hundreds of millions of clicks per day, across on the order of a million distinct ads, with per-minute counts served to dashboards and per-day counts cut into the bill.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Ingestion
~300K clicks/s (peak)
The burst case, a viral creative. The endpoint must absorb it and return a fast ack.
Event size
~1 KB
Each click is small: an ad id, a user id, a creative id, a device id, a timestamp.
Distinct ads
~1M
The counter space is (ad, window); the ad id is the dominant key.
Window
1 minute
The smallest counting bucket. Counts roll up from the minute to the hour, day, and campaign.
Dedupe window
~5 min
How long a recent click identity is remembered. Longer than the retry horizon, short enough to hold in memory.
Read path
rollups only
Dashboards and billing read the rolled-up table, never the raw events. Pre-aggregation is the whole read path.
Billing
daily · exact
The bill is cut from the batch, batch-accurate daily total — accuracy over freshness.

Takeaways

Part 1

The shape of the problem

A click is tiny in and tiny out, with an enormous flood in between. This is a counting system, not a lookup system — and that one sentence drives the rest of the design.

  1. 1
    Counting, not looking up

    A typical web service trades a request for a record, one for one. This one trades a flood of events for a few numbers. The read path is rare and small — a dashboard refresh, a bill. The write path is a firehose. When the load shape inverts like that, the design that wins is the one that keeps the write path almost free and pushes all the real work into the rare, batchable read.

  2. 2
    The numbers are small and precious

    The thing this system is judged on is a handful of numbers: clicks per ad per minute, clicks per advertiser per day. Every click that is miscounted, dropped, or double-counted is a direct error in a number someone bills against or bets on. So the design goal is not speed — it is counting each click exactly once, at any rate, and then making those numbers easy to read.

Part 2

The click's anatomy

A click is a small record. Which fields it carries decides two things at once: how it is counted, and how a duplicate of it is recognized.

  1. 1
    What a click carries

    A click is not much: which ad, which creative version of it, who clicked, on which device, and when, to the millisecond. There is no body, no blob, no relationship to join against later. That smallness is a gift — it means the write path can be almost free, and it means the whole event fits in the cache line of whatever is counting it.

  2. 2
    The identity that makes it a duplicate

    Not every field matters for dedupe, and one of them matters more than the rest. The identity of a click is the ad, the creative, the user, and — most importantly — a client-generated click id. A retry or a relay sends the same click id back; a genuinely new click does not. That client-generated id is the anchor of the whole correctness story, because it is the one thing that is the same on a repeat and different on a new click.

Part 3

The cheap write edge

The endpoint that receives a click must be the cheapest thing in the system: stateless, horizontally scaled, and fast to acknowledge. It does not count — it hands off.

  1. 1
    The endpoint is dumb on purpose

    The click endpoint does almost nothing: it validates the payload, stamps it with a server timestamp, appends it to a durable buffer, and returns an acknowledgement. It does no counting, no dedupe, no lookup against any database. That is deliberate — the endpoint has to survive a flood, and the only way to survive a flood is to do as little as possible per request and to return the moment the click is safely written.

  2. 2
    Scale out by adding boxes

    Because the endpoint is stateless, scaling it is trivial: more instances behind a load balancer, each one appending to the shared buffer. There is no session to pin a client to one box, no database the endpoint has to keep up with, nothing that turns the endpoint into a bottleneck. The capacity of the write path is simply the number of boxes, and that number can grow with the flood.

Part 4

The durable log, and the fan-out

The buffer is a durable, append-only log. It decouples the write path from everything downstream, and it lets several independent consumers read the same clicks, each at its own pace.

  1. 1
    The log is the decoupler

    The click buffer is an append-only log: each click is written once, in order, and it stays there long enough to be read. That does two jobs at once. It protects the write path — the endpoint can acknowledge the click the moment it is durable and never wait for any counting to finish. And it fans the click out — a live counter, a batch counter, and an audit sink can all read the same log, each at its own pace, without knowing the others exist.

  2. 2
    A failure is a pause, not a loss

    Because the log is durable, a downstream failure is a pause, not a loss. If the live counter crashes, the clicks it was reading are still in the log, and the counter restarts and picks up from where it left off. The click never had to be counted once, in memory, by one fragile component — it only ever had to be written to the log once. That is the difference between holding data and buffering it.

Part 5

Counting a repeat only once

A client retry, a proxy relay, and a double-tap all mean the same click id can arrive more than once. Counting it twice is a billing error. A recent-set turns at-least-once delivery into exactly-once counting.

  1. 1
    Why the same click arrives twice

    Three things produce a duplicate. The client's network times out and it retries, sending the same click id. A proxy or an ad network relays the click, and both the relay and the origin reach the counter. And a user double-taps, which the client may or may not collapse into one. In every case the same click id arrives again within a short window, and the system cannot tell a retry from a real second click by anything except that id.

  2. 2
    Remember the recent, drop the repeat

    The counter keeps a short-lived set of recently seen click identities. When a click arrives, its identity is checked against the set: if it is already there, the click is dropped and the counter does not move; if it is new, it is added to the set and the counter goes up by one. The set expires after the dedupe window — long enough to cover the retry horizon, short enough to hold in memory. A repeat within the window is a no-op; the same id after the window is a fresh, legitimate click again.

  3. 3
    Dedupe before the add, or it is too late

    The order matters, and it is the subtle bit. An increment is not idempotent: adding one twice is two, and you cannot undo the second add by checking later. So the dedupe check has to come before the increment, and the two have to be treated as one logical step for the guarantee to hold. Getting this order right is exactly what turns a best-effort counter into one whose total you can bill against.

Part 6

Aggregation in two phases

The live total and the billing total have different requirements — freshness and accuracy — so they are built two different ways and then reconciled. The read path never touches raw clicks.

  1. 1
    Two phases, two guarantees

    The live counter sums clicks into per-(ad, minute) buckets as they arrive. It is fast, it is at-least-once, and it is good enough for a dashboard that refreshes every few seconds. The batch counter re-reads the raw log on a schedule and produces per-(ad, day) totals that are exact, because it works from the durable record rather than the stream. The two are reconciled: the bill is cut from the batch number, and the live number is what you see while the day is still in progress.

  2. 2
    The rollup is the product

    Neither phase writes a number someone reads directly. The live counter writes (ad, minute, clicks); the batch counter writes (ad, day, clicks). A rollup step sums the minute buckets into hour, day, and campaign, and that rolled-up table is the only thing the dashboards and the billing run ever query. The raw log is never read to get a number — it is read to rebuild the rollup. Pre-aggregation is the entire read path.

  3. 3
    The counter is a map, keyed by (ad, window)

    Concretely, a counter is a map from (ad, window) to a number, and the window is the sharding key. Two clicks to the same ad in the same minute land on the same counter; two clicks to different ads land on different ones. So the counter space partitions cleanly by (ad, window), and it scales out by handing different (ad, window) ranges to different machines. There is no single global counter to lock — the map, and its key, are the design.

★ Finale

End to end

One click's life: received by a dumb edge, appended to the durable log, admitted by the dedupe set, counted once into the live bucket, and — when its retry arrives — dropped. The dashboard and the bill both agree on the same number.

  1. 1
    The whole system

    Every piece in one frame. A client sends a click; the endpoint validates, stamps, and appends it to the durable log and acks. The log is read by a dedupe-aware live counter and a batch counter; both feed the rollup table; and the dashboards and the bill read only the rollup. One log, two counters, one number.

  2. 2
    A click, counted once

    A client sends a click. The endpoint validates it, appends it to the log, and acks. The dedupe reader reads the click and finds its id is new, so it admits it, and the live counter adds one to the (ad, minute) bucket. One click, one count — the counter moves exactly once.

  3. 3
    The retry, dropped

    The retry of that same click reaches the log. The dedupe reader reads it and finds its id already in the recent set, so it drops it — the live counter is never told about it. The batch counter, reading the raw log, sees two rows with the same click id and keeps only one, deduping on the same identity. Both phases agree on exactly one click.

  4. 4
    The number, on the dashboard and the bill

    The live counter's minute bucket rolls up into the rollup table, and the dashboard refreshes to show the new total — exactly one click higher than before, not two. At the end of the day, the batch counter's exact total is what the bill is cut from. The flood was absorbed, the duplicate was dropped, and the number is right.

🌐 In the wild

In the wild

Ad-click aggregation is a core building block of every advertising platform. The boxes below are anchored to the classes of well-known systems that run each piece — an illustrative mapping, not a claim about any one product's internals.

  1. 1
    The pattern, piece by piece

    Each box is a standard building block of an event-counting system. Anchoring them to the classes of production systems that run that piece turns the abstract design into the shape behind the ad dashboard an advertiser trusts with their spend.

  2. 2
    Why the same pieces keep winning

    Independent ad-tech stacks converge on the same pieces because each one removes a real failure: the durable log removes the dropped click, the recent-set removes the double-count, the two-phase split removes the wrong bill, and the rollup removes the slow dashboard. That convergence across independent systems is the evidence the design is load-bearing, not an accident.