Skip to content

    System Design

    Case Study: Ad Click Aggregation

    Design an ad click aggregation pipeline: ingest, dedupe, count per ad per minute in event-time windows, handle late data and hot ads, reconcile with batch.

    By Published 22 min read

    Share

    Case studyadvancedBackend System Design

    Before this: Case Studies: The Hard Problems Map and the Template, Stream Processing Basics

    What you'll learn: By the end of this lesson you will be able to (1) scope and size a click aggregation system, (2) count clicks per ad per minute with event-time tumbling windows and explain watermarks and grace periods with a worked example, (3) keep counts correct under duplicates, retries and late events by writing idempotent results, and (4) handle hot ads, repair with a batch reconciliation and choose what to store and query.

    This is an educational reference design of a generic ad platform, not the verified internal architecture of any company. No company is described, and every number is an illustrative assumption unless a source is named.

    Think of the turnstiles at a stadium. Each gate counts people through, and every few minutes a runner carries the tally to the control room. Some runners are slow, one gate's counter sometimes sends the same tally twice, and a gate with a broken radio delivers its numbers an hour late. The control room still has to post an accurate count for the first half hour, because the vendor paying for the stadium's sponsor board is billed on it.

    Ad click aggregation is that control room. Clicks arrive from many servers, out of order, sometimes twice, sometimes late, and the result drives both a live dashboard and an invoice. The two audiences want different things: the dashboard wants an answer in seconds, and the invoice wants the right answer eventually.

    The building blocks have their own lessons. Stream processing basics teaches windows, grace periods and state stores with a lab, analytics pipelines and Lambda versus Kappa covers the batch-and-stream trade-off, Kafka internals covers partitions and consumer groups, and idempotent consumers and deduplication covers duplicate handling. This lesson shows how they fit together in one interview-sized design. The general case-study method sits in the case-studies overview lesson, which is planned and not yet linked here.

    The core idea

    Aggregate by event time, not arrival time, and write results that can be repeated safely. Each click carries a unique id and the time it happened. The pipeline removes duplicate ids, groups clicks into fixed one-minute windows by event time, and writes each window's total as an absolute value into a table keyed by ad and window. Late clicks revise a window while it is still open. A slower batch job recomputes everything from the raw log and corrects what the stream missed. Duplicates are harmless because the sink overwrites with a newer total instead of adding to it, and lateness is bounded because a window closes after a stated grace period.

    Requirements and scope

    Functional:

    • Record each ad click (an ad is shown, the user clicks, the click is logged, the user is redirected).
    • Answer: how many clicks did ad A get in a given minute, hour or day? How many in the last N minutes?
    • Return the top N ads by clicks in the last minute or hour.
    • Support filtering and grouping by a small set of dimensions (campaign, country).

    Out of scope: bidding, impression tracking, attribution models, fraud detection (we only cap abusive rates), billing rules and invoicing. We assume a billing system that reads our final numbers.

    Non-functional (assumptions):

    • Accuracy for billing. Final counts must match the raw log. Dashboards may be briefly approximate.
    • Freshness. The dashboard shows a minute's count within about a minute (illustrative).
    • Lateness. Clicks may reach the system up to 10 minutes after they happened in normal operation, for example from mobile clients that buffer (illustrative).
    • No lost clicks once acknowledged, and no double counting of the same click.
    • Survive a consumer crash, a broker node failure and a replay without manual repair.

    Back-of-envelope estimate

    All numbers are illustrative assumptions.

    Quantity Assumption Result
    Clicks per day 1 billion about 11,600 per second on average
    Peak factor 5 times average about 58,000 per second
    Click event size 200 bytes about 200 GB per day raw, 2.3 MB per second on average
    Kafka retention 7 days, 3 replicas 200 GB x 7 x 3, about 4.2 TB
    Raw archive in object storage 200 GB per day about 73 TB per year, before compression
    Non-empty (ad, minute) pairs 300 million per day 300 million x 40 bytes, about 12 GB per day, 4.4 TB per year
    Dedup horizon 1 hour of click ids at the average rate 41.7 million ids x 16 bytes, about 670 MB
    Per-task capacity 10,000 events per second at least 6 tasks at peak; 24 partitions for headroom

    Three conclusions. Throughput is manageable with a partitioned log and a modest number of workers. The minute table is smaller than the raw log but not tiny, because most ads are long-tail and rarely have more than a click or two in a minute. The deduplication state is small (hundreds of megabytes over all tasks), so it can live in the stream processor's local state.

    API design

    POST /v1/clicks                (internal, from the tracker to the log; shown for shape)
    { "clickId": "9b2d...e1", "adId": "ad-4411", "campaignId": "c-90",
      "country": "DE", "eventTime": "2026-12-02T10:00:50Z" }
    
    GET /v1/ads/ad-4411/clicks?from=2026-12-02T10:00Z&to=2026-12-02T11:00Z&granularity=minute
    -> 200 { "adId": "ad-4411", "points": [ { "t": "10:00", "clicks": 3, "final": true }, ... ] }
    
    GET /v1/top-ads?window=1m&limit=10
    -> 200 { "windowStart": "10:00", "ads": [ { "adId": "ad-12", "clicks": 931 }, ... ] }

    Two details matter. The final flag tells the caller whether a window can still change, so billing reads only final: true rows. And eventTime is the time the tracker server received the click, not a device clock: device clocks drift and users change them. The tracker host's clock is far more trustworthy, though hosts still differ by a few milliseconds to seconds, which the grace period absorbs.

    The click id is minted by the ad-serving side when the ad is rendered and travels inside a signed token in the click URL. Because it exists before the click, a retried click request carries the same id, which is what makes deduplication possible.

    Data model

    Raw event (Kafka, then the archive):

    click_id    string   unique per click, signed token from ad serving
    ad_id       string
    campaign_id string
    country     string
    event_time  timestamp  (tracker receive time, UTC)

    Aggregate table (serving store, SQL shown for the idea; the store may be any engine that supports keyed upserts):

    CREATE TABLE ad_clicks_minute (
      ad_id        text        NOT NULL,
      window_start timestamptz NOT NULL,
      clicks       bigint      NOT NULL,
      revision     bigint      NOT NULL,
      final        boolean     NOT NULL DEFAULT false,
      PRIMARY KEY (ad_id, window_start)
    );

    The primary key is the idempotency key of the whole pipeline: one row per ad per window, whatever the number of retries. revision increases every time the stream revises the window, and the batch repair writes an even higher one. Roll-ups (hour, day) are separate tables computed from minute rows by a scheduled job.

    High-level design

    Figure 1. Click aggregation at a glance

    Ad click aggregation high-level designUser click to Click tracker; Click tracker to Kafka (append); Kafka to Stream job; Kafka to Raw archive; Stream job to Serving store (upsert); Stream job to Late events; Raw archive to Batch repair; Late events to Batch repair; Batch repair to Serving store (correct); Serving store to Query APIUser clickUser clickClick tracker: statelessClick trackerstatelessKafka: clicks-rawKafkaclicks-rawStream job: dedup and windowStream jobdedup and windowRaw archive: object storageRaw archiveobject storageServing store: minute totalsServing storeminute totalsLate events: side topicLate eventsside topicBatch repair: hourly recomputeBatch repairhourly recomputeQuery APIQuery APIappendupsertcorrect

    How to read this: the tracker is stateless and only appends to the log. Two things read the log: the stream job, which produces fast totals, and the archive writer, which keeps every raw click. The stream job sends clicks that arrive too late to a side topic. The hourly batch job recomputes windows from the archive and corrects the serving store. The query API reads only the serving store.

    The tracker does the minimum on the click path: verify the signed token, stamp the receive time, append the event to the log and redirect the user. It never queries a database. Appending uses a producer with the idempotent option, which Kafka documents as guaranteeing that resending will not create duplicate entries in the log; the broker assigns each producer an id and deduplicates with a sequence number. That removes duplicates created by producer retries, but not duplicates created by the client or a load balancer resending the HTTP request, so the pipeline also deduplicates by click id.

    Figure 2. The life of one click

    sequenceDiagram accTitle: One click from tracker to serving store accDescr: A user clicks an ad. The tracker verifies the token and appends the event to the log, then redirects the user. The stream job reads the event, drops duplicates by click id, updates the window total and upserts it into the serving store. The archive writer stores the raw event for the batch repair. participant U as User participant T as Tracker participant K as Kafka log participant S as Stream job participant V as Serving store participant A as Archive writer U->>T: GET click URL with signed token T->>T: verify token, stamp receive time T->>K: append click event, key ad id T-->>U: 302 redirect to the advertiser K->>S: click event S->>S: duplicate click id? drop. Otherwise count in window S->>V: upsert ad, window, total, revision K->>A: same event A->>A: write to raw archive

    How to read this: the user is redirected as soon as the append is acknowledged, so counting never slows the click. The stream job and the archive writer are independent readers of the same log.

    Deep dive 1: event-time windows, watermarks and grace

    A window is a fixed interval over which you aggregate. A tumbling window has a fixed size and never overlaps the next one. A sliding window overlaps if its slide is shorter than its size, and a session window has no fixed boundaries and closes after a period of inactivity. For per-minute counts, tumbling windows are the natural fit. Kafka Streams defines a tumbling window as a hopping window whose size equals its advance interval.

    Event time is when the click happened at the source. Processing time is when the pipeline happens to handle it. Engines drive progress differently. Flink advances event time with watermarks: a watermark for time t declares that event time has reached t, so no earlier events are expected. Kafka Streams uses data-driven stream time, which advances only when a new record arrives. In both, a record is late when it arrives after the engine's clock has passed its timestamp.

    You cannot wait forever, so you must choose a lateness policy. Flink's documentation says event-time processing incurs latency while waiting for out-of-order events and that it is only possible to wait for a finite time. Kafka Streams calls the waiting period the grace period: it controls how long the engine waits for out-of-order records for a window, and a record arriving after the grace period has passed is discarded. Its documentation gives an example: with a one-hour window and a ten-minute grace period, the 09:00 to 10:00 window accepts out-of-order records until 10:10, then closes. In Flink the equivalent knob is allowed lateness, which defaults to zero, so by default late elements are dropped. Elements that arrive within the allowed lateness are added to the window, and the window can fire again; after that, Flink removes the window and its state.

    A worked example. One-minute tumbling windows by event time, a grace period of 2 minutes, and stream time defined as the largest event time seen so far. A window [10:00, 10:01) closes for good once stream time passes 10:03:00. Arrival order, all illustrative:

    Arrival Click Event time Stream time after What happens
    1 k1 10:00:10 10:00:10 Counted in window 10:00, total 1
    2 k2 10:00:50 10:00:50 Counted in window 10:00, total 2
    3 k3 10:01:05 10:01:05 Counted in window 10:01, total 1
    4 k2 again 10:00:50 10:01:05 Duplicate click id, dropped before counting
    5 k4 10:00:58 10:01:05 Out of order but inside grace: window 10:00 revised to 3
    6 k5 10:04:30 10:04:30 Counted in window 10:04. Stream time now passes 10:03:00, so window 10:00 is closed
    7 k6 10:00:40 10:04:30 Too late for window 10:00: sent to the late-events topic, not counted

    At the end the stream path holds window 10:00 = 3, window 10:01 = 1 and window 10:04 = 1, while the raw log says window 10:00 truly has 4 clicks (k1, k2, k4, k6). The batch job later recomputes window 10:00 from the archive and writes 4. If the stream path used Suppressed.untilWindowCloses, which Kafka documents as emitting nothing for a window until it closes and then emitting the final result, the dashboard would see window 10:00 only when arrival 6 closes it, with a total of 3. Without suppression the dashboard sees 1, 2 and 3 as updates, because windowed computations in Kafka Streams update their results continuously.

    Figure 3. Deciding what happens to a click

    flowchart TD accTitle: Decision for each incoming click accDescr: A click is checked for a known click id. A duplicate is dropped. Otherwise its window is found. If the window is still open the window total is updated and upserted. If the window is closed the click goes to the late-events topic for the batch repair. A[Click event arrives] --> B{Click id already seen?} B -- yes --> C[Drop, count a duplicate metric] B -- no --> D[Find window from event time] D --> E{Stream time past window end plus grace?} E -- no --> F[Update window total, new revision, upsert] E -- yes --> G[Send to late-events topic] G --> H[Batch repair corrects the window]

    How to read this: each click takes exactly one of three exits: dropped, counted or sent to the late topic. Nothing is silently lost, because the late path is a topic that the batch job reads.

    Two clocks that surprise people. Stream time and watermarks move with data, not wall time. If one partition receives no traffic, an engine that tracks time per input can stall: Flink's documentation says an operator's current event time is the minimum of its input streams' event times, and Kafka Streams stream time advances only when a new record arrives. A quiet partition can therefore hold windows open. Engines offer idleness settings for this; check your engine's documentation. On the other hand, data-driven time makes replay behave like live processing: re-reading two hours of backlog advances stream time with the replayed data, not with the wall clock, so late relative to the log is what counts.

    Deep dive 2: duplicates and the exactly-once effect

    Duplicates arrive from three places: the client or a proxy resending the request, the producer retrying an append, and the consumer reprocessing after a crash. Kafka's design documentation defines at-least-once as messages never lost but possibly redelivered, and says that is its default guarantee. A Kafka Streams application defaults to at_least_once, and exactly_once_v2 is available with brokers 2.5 or newer. Kafka also supports transactions, which write to several partitions atomically, and a read_committed consumer sees only committed transactional messages. Those cover duplicates inside Kafka. They do not cover the hop from the stream job to the serving store, or the HTTP duplicates before Kafka.

    So the design uses two layers that are independent of the engine's mode:

    1. Deduplicate by click id. The stream job keeps a state store of click ids seen in the last hour (the dedup horizon). Duplicates share the same ad_id, and the log is keyed by ad_id, so they land in the same partition and the same task; no extra repartition is needed. Ids older than the horizon are purged. A duplicate that arrives after the horizon is also older than the grace period, so it would be late anyway and goes to the batch path, where the batch job deduplicates over the whole day.
    2. Write absolute totals, not increments. The sink receives (ad_id, window_start, clicks, revision) and applies a guarded upsert:
    INSERT INTO ad_clicks_minute (ad_id, window_start, clicks, revision)
    VALUES ('ad-4411', '2026-12-02 10:00:00+00', 3, 7)
    ON CONFLICT (ad_id, window_start) DO UPDATE
       SET clicks = EXCLUDED.clicks, revision = EXCLUDED.revision
     WHERE ad_clicks_minute.revision < EXCLUDED.revision;

    PostgreSQL documents that ON CONFLICT DO UPDATE guarantees an atomic insert-or-update outcome, even under high concurrency, and that the WHERE clause can read both the existing row and the proposed row through excluded. The effect: delivering the same total twice changes nothing, delivering an older total after a newer one changes nothing, and a replay after a crash converges to the same table. If the sink added increments (clicks = clicks + 1), every redelivery would inflate the count; this is why "send state, not deltas" is the rule for at-least-once pipelines. The idempotent and commutative operations lesson gives the general argument.

    With both layers, the system has an exactly-once effect on the table even though delivery is at least once. The engine's own exactly-once mode is then an optimisation (fewer duplicates to absorb), not the load-bearing correctness mechanism.

    Deep dive 3: hot ads and two-stage aggregation

    Keying by ad_id keeps one ad's clicks in one task, which makes counting and deduplication local. The cost is skew. Suppose one ad receives 5 percent of peak traffic, about 2,900 clicks per second (illustrative). That is below the assumed 10,000 per second per task, so the single-key design still works. A viral ad at 30 percent would be 17,400 per second, which exceeds one task, and its partition falls behind while others idle. The hot partitions lesson covers the general problem.

    The remedy exploits a property of counting: partial counts can be merged.

    Figure 4. Two-stage aggregation for a hot ad

    Two-stage aggregation spreads a hot ad across tasksKafka to Stage A tasks; Stage A tasks to Partials topic (partial); Partials topic to Stage B task; Stage B task to Serving store (upsert)PARALLEL, ANY KEYONE TASK PER AD AND WINDOWKafka: hot ad clicksKafkahot ad clicksStage A tasks: key = click idStage A taskskey = click idPartials topic: key = ad, windowPartials topickey = ad, windowStage B task: merge partialsStage B taskmerge partialsServing storeServing storepartialupsert

    How to read this: stage A reads the hot ad's clicks spread by click id across many tasks. Each task deduplicates its own share (the same click id always reaches the same task) and emits its running count for the window. Stage B receives at most one partial per task per flush and sums the latest partial of each task.

    Stage A is keyed by click_id, so a given click id and its duplicates still reach the same task and are deduplicated there. Each task sends a cumulative partial for (ad, window) with its own revision every few seconds (illustrative: 5 seconds), not a delta. Stage B keeps, per (ad, window), the latest partial from each stage A task and sums them. Because partials are cumulative and revisioned, a duplicated or reordered partial is harmless, for the same reason the table upsert is. Stage B's load is the number of tasks times the flush rate per ad, which is tiny.

    Use this only for ads above a threshold rate, taken from a hot list based on the last few minutes; the extra stage adds one flush interval of latency and a topic.

    Deep dive 4: batch repair and finality

    Late events beyond the grace period, lost events from outages and any bug in the stream logic all create differences between the serving store and the truth in the raw log. A reconciliation job closes the gap, which is the Lambda idea from the analytics pipelines lesson applied narrowly:

    1. Every hour, for windows that closed more than a safety margin ago (illustratively 1 hour), read the raw archive for that period.
    2. Deduplicate by click id and recompute the count per (ad, minute) from scratch.
    3. Compare with the serving store. Upsert any window that differs with a much higher revision (for example the batch run's start time in milliseconds), and set final = true for every window in the period.
    4. Record the discrepancy: windows changed, total clicks added or removed. This is a first-class metric.

    Billing reads only final = true rows. The dashboard reads everything and may show a small correction after an hour. The raw log in cheap storage makes this possible, and the same job can re-run history after a bug fix. The cost is a second implementation of the counting logic: keep it small (dedupe and group by) and test that both paths agree on the worked example above. The data warehouses and lakes lesson covers the storage side.

    Deep dive 5: the query side

    The serving store answers three kinds of question:

    • Range by ad: sum of minute rows for one ad. With a primary key on (ad_id, window_start) this is a short range scan. A day is at most 1,440 rows per ad.
    • Roll-ups: a scheduled job writes hourly and daily tables, so a month-long chart reads 30 rows, not 43,200. Keep minute rows for a limited time (illustratively 30 days) and hourly rows longer. A time-series or column store suits this; see the time-series databases lesson.
    • Top N ads in a minute: an index on (window_start, clicks DESC) serves it, or the stream job emits a small top-N result per minute. Top-N over very many ads should not scan every row at request time.

    Unique users per ad is a different kind of question, because counting distinct values needs memory proportional to the number of values. A HyperLogLog sketch estimates distinct counts in bounded memory. Redis documents its implementation as using up to 12 KB with a standard error of 0.81 percent, and sketches can be merged, so hourly sketches combine into a daily one. The result is approximate by design, so it suits dashboards and not billing. State the error in the API. Counting clicks is exact; counting unique clickers is an estimate.

    Bottlenecks and scaling

    • Log throughput: add partitions ahead of time. Changing the partition count later changes which partition a key maps to, which breaks per-key state, so plan headroom (24 partitions for a 6-task need).
    • Stream tasks: Kafka Streams creates a fixed number of tasks from the input partitions, so parallelism is capped by the partition count. For fault tolerance each state store has a replicated changelog topic, and Kafka Streams restores state to its pre-failure content; standby replicas make recovery faster.
    • Serving store: minute rows grow by about 12 GB a day (illustrative), so partition by time and drop old partitions instead of deleting rows.
    • Abuse: a bot can generate millions of clicks on one ad. Cap clicks per source per ad at the tracker and send suspicious clicks to a separate topic. Fraud scoring itself is out of scope.

    Failure modes

    Failure Effect Defence
    Tracker fails before the append is acknowledged Click may not be logged Bounded retry, then redirect anyway and count a lost-click metric, because the user must not wait
    Duplicate HTTP request Same click id twice Dedup by click id in the stream job and in batch
    Stream task crashes Reprocessing from the committed offset State restored from the changelog; idempotent upsert makes replay harmless
    Broker node down Appends and reads continue if replicas are in sync Replication; alert on under-replicated partitions
    One partition idle Windows stay open, dashboards freeze Idle-partition handling, alert on window close lag
    Clock skew between trackers Clicks land in the neighbouring window Stamp time at the tracker only; grace period absorbs small skew
    Burst of late events after an outage Many events pass the grace period Late topic plus batch repair; do not widen grace as the only fix
    Sink down Upserts fail Retry with backoff; dead-letter after a limit, see dead-letter queues
    Bug in counting logic Wrong totals for hours Discrepancy alerts; fix and re-run batch

    Build it

    This lesson has no lab: it is a design walkthrough. The windowing and late-event behaviour used here are shown with a traced lab in the stream processing basics lesson. No output is shown here.

    Trade-offs worth stating

    Decision Choice here Gain Cost Wrong when
    Window time Event time at the tracker Correct windows under delay and replay Needs a lateness policy Delay is irrelevant and wall-clock counts are enough
    Grace period Short (2 minutes, illustrative) plus batch repair Fast final dashboard values Some clicks arrive after close Most late data arrives within minutes and you can afford waiting
    Result writes Absolute totals with revision Duplicates and replays are harmless Revision bookkeeping The sink supports transactions with the stream engine end to end
    Partition key ad_id Local state, simple dedup Hot-ad skew A few ads dominate traffic, so use two-stage for those
    Accuracy for billing Stream plus batch repair Fast and correct Two code paths to keep equal Volume is low enough for batch only
    Distinct users HyperLogLog Constant memory About 1 percent error Exact counts are legally or contractually required

    Interview cheat sheet

    1. Clarify the audience: dashboard and billing differ in accuracy needs. State the lateness bound.
    2. Size it: clicks per second at peak, bytes per day, minute-row growth.
    3. Draw tracker, log, stream job, serving store and archive. The tracker only appends.
    4. Explain event time versus processing time, windows, watermark or grace, and give the late-event decision.
    5. Handle duplicates by click id and write absolute totals with a revision into a keyed upsert.
    6. Name the hot-key problem and the two-stage merge.
    7. Add batch reconciliation, the final flag and the discrepancy metric.
    8. Close with failure modes: idle partitions, outage replays, clock skew, abuse.

    In practice: closing the gap between dashboard and invoice

    This is a realistic scenario, not a case history. It describes an educational reference design, and every number is an illustrative assumption.

    The situation

    An advertiser reports that the invoiced clicks are about 0.4 percent higher than the dashboard total for the same hour, every day. The advertiser's own server logs match the invoice. The dashboard is wrong by a small and consistent amount.

    Starting architecture

    The design above, except that the batch repair does not exist yet. The stream job has a grace period of 2 minutes, and no side topic: clicks that arrive too late are dropped and only counted in a metric.

    Options considered

    • Widen the grace period to 30 minutes. Catches more late clicks, but every window's final value waits 30 minutes, and state for open windows grows.
    • Send late clicks to a side topic and repair in batch. Keeps dashboards quick and reaches exactness later, at the price of a second job.
    • Make the stream job's exactly-once mode the answer. It does not help: the missing clicks are late, not duplicated.

    The decision

    Add the late-events topic and the hourly reconciliation job, and keep grace at 2 minutes. The dropped-late metric shows that most late clicks come from one mobile client version that buffers clicks while offline and flushes them on reconnect, so the long tail is real and the batch path is the right place for it. Add the final flag to the API and have billing read only final rows.

    Rollout and verification

    Run the batch job in shadow mode first: compute corrections but write them to a separate table. Compare them with the advertiser's reported difference for a week. Then enable writes, confirm that the dashboard's day totals converge to the invoice, and keep the discrepancy metric on a dashboard with an alert if the hourly correction exceeds a threshold (illustratively 1 percent). Test the paths with the worked example from this lesson as a fixture: both must produce window 10:00 = 4.

    The 2 a.m. failure

    At 02:15 an alert fires: "oldest open window older than 20 minutes". One of the tracker regions has failed over, and one Kafka partition now receives no records. Because that task's stream time only advances when a record arrives, its windows never close, and final flags for those ads stop appearing. Billing exports for the night are delayed. The runbook: confirm the idle partition from the lag and end-offset metrics, enable idle-input handling or route a heartbeat record into the partition, and re-run the closing step. Afterwards, add a heartbeat producer per partition and an alert on window close lag.

    Architect's notes

    • Separate "fast" from "final". Two audiences with different accuracy needs are best served by two paths and an explicit flag, not by one path that tries to be both.
    • Send state, not deltas. An idempotent sink is worth more than an exactly-once engine mode, because it protects every hop you do not control.
    • Treat lateness as a product decision. Ask how late a click can be and what it costs the business when it is missed. Then set grace, batch margin and billing cut-off from that answer.
    • Measure the repair. A reconciliation job that never reports a discrepancy has either a perfect pipeline or a broken comparison. Alert on both zero and large.

    Common mistakes

    • Using processing time for windows, so a backlog after an outage shifts clicks into the wrong minute.
    • Adding increments at the sink, so every redelivery inflates the count.
    • Setting grace to a huge value to avoid drops, which delays every result and holds large state.
    • No side topic for late data, so late clicks vanish without a trace.
    • Deduplicating only in the stream job and not in the batch job, so the repair reintroduces duplicates.
    • Ignoring idle partitions, or promising exact unique-user counts from a sketch.

    Key takeaways

    • Count by event time in tumbling windows; the lateness policy (grace period or allowed lateness) is a stated trade-off between freshness and completeness.
    • Duplicates come from clients, producers and consumers: deduplicate by a unique click id and write absolute totals with a revision into a keyed upsert.
    • A hot key needs two-stage aggregation, which works because partial counts merge.
    • A batch reconciliation over the raw archive makes the final numbers exact and turns the stream path into a fast approximation of them.
    • Expose a final flag and make billing read only final rows.
    • Plan for idle partitions, replays and clock skew, and measure the discrepancy between stream and batch.

    Practice exercises

    1. (20 minutes) Redo the worked example with a grace period of 5 minutes. Which arrivals change? What is the cost in latency to a final value?
    2. (30 minutes) Add a session-style metric: clicks per user session with a 30-minute inactivity gap. Which parts of the design change, and what do late events do to a session?
    3. (30 minutes) Design the heartbeat that advances an idle partition's time. What event does it carry, and how do you keep it out of the counts?
    4. (40 minutes) Write the reconciliation job's comparison rule: how it picks the windows, how it chooses the revision, and how it avoids overwriting a newer stream value with an older batch value.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments