Ch.45: Ad Click System Design: Exactly Once Still Counts Twice

Outline

Transcript

0:00 Your ad dashboard shows 200 clicks. Only 100 unique click events were accepted. A worker restarted, but the stream processor promises exactly once. How did the count double? It added 100 to an outside database, then crashed before saving its processing progress. On retry, that outside increment happened again. Ah, I didn't realize that promise stopped inside the pipeline. The wrong dashboard can show 200 while the committed internal count is 100. Yes. We need three promises: what identifies a click, what the processor commits, and what repeating the database write does.

0:32 We'll fix this ad click aggregation design at the outside write, then make the corrected count survive a viral ad and delayed input. A faster counter would still add that hundred twice. We need to change what the retry repeats. That outside-write boundary belongs on the full architecture map. Our hundred accepted events enter a durable log, lose their duplicates, and become partial counts: pieces of the total. Committed output updates dashboard rows. The archive branch preserves raw input for an independent recount.

1:01 The ordinary query reads those rows, not the processor's private memory. Okay, walk me through that last write. What stops it adding the hundred again? The updater writes the committed total over the old value instead of adding it again. We'll test the lost acknowledgment against that operation. We'll return to this same map once that write survives the restart. First define what an accepted click actually means. Before we protect that write, define the functional requirements: the actions our service provides.

1:31 Accept reported click events and return an advertiser's per-ad minute counts. A trusted producer supplies identity, ad and when the interaction happened. So accepting means our replicated log acknowledges the event. It doesn't mean this aggregator witnessed somebody's finger touching a screen. Exactly. The sender reuses that click’s ID when it sends the report again. We check who sent it and reject changed data under that ID. Okay. Reads also check that the advertiser owns the ad. Knowing an ad identifier isn't permission to inspect another account's activity.

2:04 Ordinary queries cover one ad and at most a day of minutes. We count accepted telemetry; fraud decisions and billing belong to other services. Right, that's something we can test. Now choose how quickly those events must appear on the dashboard. And how much uneven traffic it must survive. One popular ad can dominate the workload even when the total seems manageable. Now define the non-functional requirements: how well those actions must work. For this fictional interview, choose a peak of 100,000 accepted events each second. One viral ad can generate 40,000 of those.

2:41 That's deliberately uneven traffic. A fleet sized for the average could still choke on that one ad. Target ordinary dashboard responses within 250 milliseconds for 99 of 100 requests. Healthy committed counts should appear within 2 seconds. If only picking the log made the latency test pass. We still have to measure it. Accepted input must survive failure; delayed counts must be recoverable. Yeah. We can show provisional totals and their age. Different parts of the count may reach the dashboard at different times.

3:13 Those freshness targets won't rescue the doubled count. Let's test the row operation first. Now walk the promised database write through a concrete case. Assume the processor has a committed count of 100 for this minute, at position 71. What exactly does the updater write? It writes count 100, with publication position 71, into the same row. A partition is one ordered lane of the log. That position orders publications in this lane; it isn't another click identifier. Why can't I just read the position, decide it's newer, then write the count?

3:48 Another updater could win between your read and write. PostgreSQL's conditional upsert keeps the comparison and replacement together. Upsert means update an existing row, or insert one if absent. A new row gets count 100 and position 71 together. Good. The same row owns the count and the evidence of which committed publication supplied it. Let's lose the acknowledgment again. Now test that write. Consider a lost acknowledgment: the database saves 100 at 71. The updater crashes before acknowledging progress, then retries 71. The positions are equal, so the condition ignores it. The row stays 100.

4:24 Oh, nice. The worker ran twice, but the row stayed at 100. Exactly. That's the outside guarantee we were missing. What happens when a real update arrives? Position 79 carries count 105, so it replaces the row. Then a delayed retry of 71 arrives. Ignore it, or it could erase those five new clicks. Right. Reject older positions as well as equal ones. A generation is one version of the counter. Call our current version live and a later rebuilt version recount. Give them different rows. Compare positions only inside one version and one log partition.

5:01 With that row protected, consider a retry at the input. Our trusted click-reporting app sends the same interaction again as a fresh request. The log can store another record, although its logical identifier hasn't changed. I'd have deduplicated by log position. Two delivery receipts can describe one parcel; two log records can describe one click. A record's position isn't the interaction's identity. Right. Keep an exact set of identifiers already counted, and route copies of one identifier to that same state.

5:31 That duplicate recognition is deduplication. Hang on. Kafka's sending library can block duplicates from its own retries. That is idempotence. Doesn't it already solve our duplicate click? It protects that library's own retries. A fresh application send isn't that same attempt, even with identical payload. The Kafka producer docs specifically warn about application-level resends. We still need our click identifier. Ah, I was giving that library our application's job. What if the reporter generates a new identifier each time? Can the aggregator spot that mistake from the ad and timestamp?

6:05 Not reliably. Two legitimate clicks can share those fields. Our guarantee requires stable event identity from the reporter. It isn't a physical-click detector. That stable identity creates a storage cost. For example, sustain the chosen peak for an hour: we'd inspect 360 million event identities. Right. Even assuming 32 bytes each, that's 11.52 gigabytes before indexes, replication and storage overhead. No tiny set in one worker. That set has to survive the restart with the count. Losing it while keeping the total would let the same identifiers contribute again.

6:40 Our producers retry for 10 minutes. Keep each identifier at least an hour after we last received it. Seeing it again restarts that hour. With that history intact, what returns after our hundred-click batch commits? For example, the engine restores 100 as the saved total. Its remembered click identifiers come back too. The saved input position also returns, so the worker resumes after those processed events. Ah, that coordinate tells the worker what to read next. 71 serves the other job: telling the database which publication wins.

7:14 For our original batch, suppose an overnight outage leaves the count at 100, but the identifier history has expired. Don't replay that batch into the live counter. Hold the hundred; use a separate recount. We'll trace that rebuild. Kafka's official docs warn that outside destinations must cooperate with processing guarantees. Links are in the description. Next, see how that limit affects our custom counter. Now return to the worker's commit boundary. Our row can hold a bad total safely. How do we keep a failed attempt's answer out?

7:49 The counter's saved state, its resume bookmark and its published records need one transaction. If that transaction fails, its result must stay out of the accepted count. So the database can handle retries correctly while accepting a result the engine rejected. Yes. Can the database updater tell which output attempt actually committed? The Kafka consumer's read-committed setting excludes aborted records before the updater receives them. A record written without a transaction still passes, though.

8:20 That setting can't make the processor's output transactional. So what do we switch on in the processor to make those results transactional? Now turn on the supported exactly-once mode in Kafka Streams, a library for processing these streams. It commits managed state changes, input progress and output Kafka records together. So that isn't its default processing mode? Right. The default, at-least-once, permits duplicate output after retries. Both modes can rerun work; they differ in whether those retries can commit duplicate output. Naming the framework doesn't select the stronger guarantee.

8:53 Imagine two drafts of our hundred-event tally. The weaker mode can publish both; exactly-once commits one outcome from that repeated work. Our updater reads only committed output. An aborted attempt can't supply the count, even if the database replacement itself is safe to retry. Yes. A function can execute again after failure. We're protecting its committed result, not one execution of every instruction. Commit visibility can add delay, so test it against our 2-second target. Oh, right. We proved the row survives repeated publication.

9:24 This commit gate protects the number we're publishing. Both boundaries need their own check. With both commits protected, put the stream counter under our concentrated load. An interviewer could ask, '40,000 clicks for one ad still land on one worker, don't they?' More workers won't automatically divide it. After duplicate recognition, use a hash of each stable click identifier to choose one of 64 fixed buckets: separate pieces of the count. Each bucket owns a separate share of the ad's events, with no overlap.

9:54 The same identifier always lands in the same bucket, including retries. Those keys can spread across workers. 64 buckets doesn't mean 64 machines, and doesn't prove the traffic balances perfectly. Right. Measure how unevenly the traffic lands. Keep bucket count and output routing fixed within live; changing that layout needs a separate migration. Okay, we moved the pressure off one counter. But the read has to combine pieces without resurrecting the duplicate-count problem. Now each database row needs a bucket identifier too.

10:24 A new partial publication replaces that bucket's contribution; the query combines the pieces. With no overlap between buckets, take a tiny example: one has 40 clicks, the other 60. Their latest partial counts sum to 100. Five unique late clicks reach the second bucket. Its next committed publication says 65. Replace 60; the total becomes 105. Adding the new 65 to the old total would give 165. Different arithmetic, same mistaken treatment of a replacement as new work. We split the writes. Does that make the dashboard query cheaper too, or more expensive? It creates more rows to read.

11:02 Keep one latest row per version, ad, minute and bucket. Use a database snapshot, a consistent view of stored values, and sum that version's latest contributions once. Extra write parallelism brings read and storage costs. Now imagine those five clicks occurring in the original minute but reaching aggregation later. Event time names the interaction's timestamp recorded by the trusted producer. Right. Processing time is when we handle the input. Think of a letter dated 10 o'clock but delivered at 10-oh-4: its arrival doesn't change its date.

11:34 Grouping clicks by arrival moves them into a later minute and hides the earlier shortfall. Right, retries keep the letter's original date too. That's how we keep them in the same event minute. The producer owns its clock and capture quality. So an accepted event that arrives late can still change that earlier total. If the source never recorded the interaction, we cannot recover it from saved input. Yes. Now we need a visible policy for how long a minute remains open to routine changes, rather than calling every current total final.

12:07 Track whether the input is advancing too. A stalled lane can leave an earlier minute short of clicks. If the input advances past that minute, can we call its count complete? Or can an earlier event still arrive? Now give those late clicks a deadline, although more can still arrive. Our chosen policy uses the server clock. The 10 o'clock minute ends at 10-oh-one. Routine revisions close at 10-11, 10 minutes after the minute ends. Those five clicks arrive 4 minutes past 10, so they revise the original minute's total.

12:39 What happens to another accepted click arriving at 10-12? The raw archive keeps it for a separate recount. The live window is closed; we haven't thrown the accepted input away or silently added it to a different minute. Then what does the watermark tell us? Does it decide whether the earlier count is complete? Beam, a data-processing framework, calls the expected progress line a watermark: earlier events are expected to have arrived. Think of our letters: the estimate says earlier-dated letters should have arrived.

13:11 A missing letter can still turn up after that estimate. Closing the desk at 10-11 is a separate rule. Expected delivery doesn't prove every letter arrived, or set our server-clock cutoff. I think I was treating expected progress as a deadline. Now I'd show data age and the closed-window policy separately. A stable number might mean the campaign stopped, or input stopped arriving. Now return that stored answer to the advertiser. Suppose every row is from one consistent database snapshot. Might that answer lag behind the clicks?

13:42 Yes. Imagine one photograph of two clocks, with 1 running 2 seconds slow. The picture captures both together without making them equally current. That's our snapshot: one consistent view can contain differently aged values. Sum each latest contribution once. Report how current the total is and whether routine late revisions remain open. So the row's publication position proves which update won, not whether every input arrived. Exactly. If saved input has moved ahead of processing, that gap is processing lag.

14:13 Dashboard freshness also depends on the database updater keeping up. Got it. For example, the query can return 100, provisional and 2 seconds behind, if those are the actual measured limits. Now take that overnight batch through a separate rebuild. Its count is still 100. What happens when its identifiers have expired? For that older replay, we've retained raw accepted input for 7 days as a chosen policy. Reconciliation means independently recounting it and comparing the result. For this trace, verify one fixed preserved input range.

14:44 Keep live's total at 100. Recount starts with fresh duplicate recognition and builds independent rows that also sum to 100 from those original events. Don't add those totals. Validate recount's hundred, then switch the stored active-version choice from live to recount. The dashboard still shows 100, never 200. Each version has its own rows and publication order. What if an old updater finishes just after readers switch? Its target still says live, so it writes only live's old rows. The next query sees the stored choice recount and sums recount's rows.

15:16 Read that choice and the rows in one database snapshot; one answer cannot mix live and recount. Oh, I see. We aren't freezing the old updater. We're keeping its writes away from recount. But an archive gap could still leave both totals wrong. Yes. The recount inherits that limit. A clean rebuild can't manufacture unsaved clicks. This fixed-range trace also hasn't proved a live migration while new events keep arriving; that needs its own catch-up plan. Agreed. Now crash the implementation at each boundary and check the count.

15:47 With recovery defined, test the boundaries. Kill the database updater after its row write but before acknowledgment. That was the exact restart that doubled our opening count. Retry the same accepted identity, expose an aborted output attempt, and lose the row's acknowledgment. The final committed rows must remain unchanged by those repetitions. Then send an old position after a newer one and check that the count stays put. Also test two different reports with 1 ID, late input for the original minute, and reads from an account that does not own the ad.

16:20 For production load testing, run the 40,000-click hot ad alongside bounded dashboard reads. Measure delay, state size and latency instead of assuming buckets solved it. Alert on a recount difference, even when throughput looks healthy. A fast pipeline that reports twice the accepted total has failed its actual job. Yeah. The throughput graph is congratulating a counter with the wrong answer. Those crash tests give the result evidence; the capture, retention and freshness limits still apply. Finally, return to the same architecture map with our hundred events.

16:54 Their identities enter the durable log; managed processing commits the correct total. The database updater reads committed output, and its atomic row replacement keeps 100 even when the acknowledgment disappears. The outside database has its own retry protection. For the hot ad, disjoint buckets contribute 40 and 60. Late input replaces 60 with 65. The dashboard now sums 105. And shows its age and live-update policy. The archive supports an independent correction if recovery exceeds the ordinary retained-state contract.

17:27 The map works because each boundary has an owner: an ID that stays with each event, a result committed inside processing, and an outside write we can safely repeat. Exactly-once processing has a scope. A complete count additionally depends on which events were captured, retained and admitted by the late-data policy. In an interview, start with the counted unit, commit boundary and read promise. They expose the double-count failure before framework selection. Each choice should fix a specific failure in the trace.

18:00 I think about what a retry repeats. Here, repeating work was acceptable; repeating an unprotected increment changed the answer. That gives your interviewer a testable promise. They can crash the worker and check the row, instead of trusting a framework name. Thanks for listening to Learning Podcasts.