Skip to content

Design an Ad Click Aggregator

Advanced 79 min read Part 17 of 18

Design a system that tracks every ad click, redirects the user, dedupes clicks and gives advertisers near-real-time, accurate per-minute metrics at scale.

The Problem#

An ad click aggregator records every click on an online ad, sends the user on to the advertiser's website, and turns the raw stream of clicks into metrics that advertisers can query: "how many clicks did my ad get, minute by minute, over the last day?" Think of the ads in a Facebook or Instagram feed, a search results page, or a banner in a mobile app. When someone taps one, the platform must count it (because the advertiser often pays per click), and it must show the advertiser how the campaign is doing, quickly and correctly.

It is a classic data-processing interview question, not a user-facing product question. The hard parts are not the screens. They are:

  • Write volume. Clicks arrive far faster than advertisers read reports. The design is driven by ingesting a firehose without losing anything.
  • Freshness versus correctness. Advertisers want numbers within seconds. Billing needs numbers that are exactly right. Those two goals pull against each other, and the design has to serve both.
  • Counting once. The same click can arrive twice (a double tap, a network retry, a replayed stream). It must be counted once, and fake clicks must not be counted at all.
  • Fast queries over huge history. An advertiser can ask for a year of data, sliced by campaign, country and device, and expect an answer in under a second.

Analogy. Think of counting votes on election night. Polling stations phone in running tallies as the evening goes on, so the news can show results within minutes. These early numbers are fast but can contain mistakes. Days later, election officials do the official count from the paper ballots, which are kept safely in a box the whole time. If the two counts differ, the official count wins and the published figures are corrected. An ad click aggregator works the same way. A stream processor keeps running tallies so dashboards are fresh. Every raw click is also stored safely, like the ballots, and a batch job recounts them later to produce the official, billing-grade numbers. The skill in this design is making the running tally good enough that corrections are rare and small.

Background: a few advertising terms#

  • Advertiser: the business paying for ads (Nike, a local bakery). An advertiser runs campaigns. A campaign contains ad groups (or ad sets), which contain individual ads (the creative: image, video, text and a destination URL).
  • Impression: one display of an ad to one user. If the same user sees the same ad in two places on a page, that is two impressions.
  • Click: a user tapping or clicking an impression. Every valid click belongs to exactly one impression.
  • Click-through rate (CTR): clicks divided by impressions. Typical display-ad CTRs are well under 1%, and search ads are higher, a few percent. This ratio matters for sizing: if impressions were in scope, they would be roughly 100 times the click volume.
  • Cost per click (CPC) and cost per mille (CPM): the two common ways to charge. CPC bills per click. CPM bills per thousand impressions. Under CPC, a click is literally money, which is why accuracy is non-negotiable.
  • Invalid traffic: clicks that should not be billed: bots, accidental double clicks, click farms, a competitor clicking to drain a budget. Detecting it is a large topic of its own. We will design hooks for it but keep sophisticated fraud detection out of scope.
  • Conversion: something valuable the user does after clicking, such as a purchase. Tracking conversions (attribution) is a separate system and out of scope here.

Clarifying Questions#

QuestionAssumed answerWhy it matters
What scale? Active ads and clicks per second?10M active ads, 10k clicks/s at peak, about 1k/s on average, so about 100M clicks per daySets the size of every tier, and shows that writes dominate reads
Do we also count impressions?No, clicks only. Impressions come up as a variant (about 100 times more volume)Impressions would turn a moderate stream into a heavy one
Who queries, and how?Advertisers, through a dashboard and an API, for their own adsQueries are always scoped by advertiser, which suggests the OLAP shard key
What granularity and range?Minimum 1-minute buckets; ranges from the last hour to several yearsNeeds minute-level data plus coarser rollups for long ranges
How fresh must metrics be?As real time as possible; seconds to a minute after the clickPushes us from batch to stream processing
How accurate? Is this used for billing?Yes. No lost clicks, no double counting. Final numbers must be exactRequires durable ingestion, idempotency and reconciliation
How are duplicates defined?One click per impression. A user who sees an ad twice may click twiceRules out naive "one click per user per ad" dedupe
Must users be logged in?No. Many clicks are anonymousWe cannot rely on a user id for dedupe
What dimensions can advertisers slice by?Ad, ad group, campaign; later country, device, placementAffects pre-aggregation and the choice of OLAP database
Do we redirect the user, or only track?We handle the click and redirect to the advertiser's URLPuts the click service on the user's critical path, so it must be fast and available
Is fraud detection in scope?Only basic filtering and hooks; advanced fraud detection is outKeeps the core design focused but leaves room for a pipeline stage
Single region or global?Users worldwide; start with one region per continentInfluences where clicks are ingested and how aggregates are merged

Requirements#

Functional#

  1. Users can click an ad and be redirected to the advertiser's website.
  2. Advertisers can query click metrics over time, with a minimum granularity of 1 minute, for their ads, ad groups and campaigns.
  3. Each click is counted at most once, even if the user double-clicks or the request is retried.

Out of scope: ad targeting and ad serving (choosing which ad to show), cross-device tracking, offline marketing channels, conversion tracking and attribution, demographic and geographic profiling, and sophisticated fraud and spam detection.

Non-Functional#

  • Scale: handle a peak of 10k clicks per second (with headroom to 10 times that), and 10M active ads.
  • Accuracy and durability: no click is ever lost after the server accepts it, and no click is counted twice. Final daily numbers must be exact because they drive billing.
  • Freshness: metrics should be queryable within seconds, and complete for a given minute within about a minute of that minute ending.
  • Query latency: advertiser queries return in under one second (p99), including year-long ranges.
  • Redirect latency: the click redirect adds very little to the user's journey: under 50 ms of server time at p99, plus network.
  • Availability: the click endpoint must be highly available (99.99% or better). If it is down, users cannot reach advertisers, and every lost click is lost revenue. The query side can tolerate brief degradation (99.9%).

What matters most. Accuracy and durability of click data come first, because clicks are money and an advertiser who sees wrong numbers loses trust in the whole platform. Next is availability of the click endpoint, because it sits on the user's path. Freshness and query speed come after that. When these conflict, we choose correct eventually, fast approximately. The real-time numbers may be slightly off for a few minutes, but the final numbers are exact.

The scale here is write-heavy. Advertiser queries are perhaps a thousand per second, while clicks arrive at ten thousand per second, and each query reads pre-computed results rather than raw clicks. That asymmetry is why this is a textbook example of Pattern: Scaling Writes.

Capacity Estimation#

Only the numbers that change the design are estimated here. See Back-of-the-Envelope Estimation for the method.

Clicks.

  • Peak 10k clicks/s. A common rule of thumb is that peak is about 10 times the average, so the average is about 1k/s.
  • 1k/s × 86,400 s/day ≈ 86M, call it 100M clicks per day, and about 36B per year.
  • Implication: 10k writes per second is too many for a single relational database doing aggregation queries on the same table, but it is modest for a partitioned log like Kafka. It is the per-query aggregation, not the raw insert rate, that breaks a naive design.

Event size.

  • A click event carries an impression id (16 bytes), ad id, ad group id, campaign id and advertiser id (8 bytes each), a server timestamp (8 bytes), a hashed device or user id (16 bytes), IP address, user agent (often 100–200 bytes), country, device type, and placement. That is about 500 bytes as JSON, or about 200 bytes in a compact binary format such as Avro or Protobuf.
  • Stream throughput: 10k/s × 200 bytes = 2 MB/s at peak. That is tiny for Kafka, which handles tens of MB/s per partition and hundreds of MB/s per broker. Even with replication factor 3, it is 6 MB/s of disk writes across the cluster.
  • Implication: we choose the number of Kafka partitions for parallelism and hot-key spread, not for raw bandwidth. If we used Amazon Kinesis instead, each shard accepts at most 1 MB/s or 1,000 records/s of writes, so 10k records/s needs at least 10 shards, and about 20 for headroom.

Raw storage.

  • 100M/day × 200 bytes = 20 GB per day of raw events. With Kafka replication factor 3 and 7 days of retention, that is about 420 GB of broker disk. Easy.
  • In the data lake, as compressed columnar Parquet files, perhaps 4–5 GB per day, so under 2 TB per year. Keeping years of raw clicks for audits and reprocessing is cheap.

Aggregated rows.

  • At the average rate there are 60k clicks per minute. Most ads get few clicks, so the number of distinct (ad, minute) pairs with at least one click is somewhat below that: say 30k–60k rows per minute, and up to a few hundred thousand per minute at peak.
  • That is roughly 50–80M minute-level rows per day before extra dimensions. In a columnar store, such a row compresses to perhaps 10–30 bytes, so 1–2 GB per day.
  • If advertisers can slice by country (about 200 values) and device type (a handful), the row count grows. The growth is not multiplicative across all combinations, because most combinations never occur in a given minute. In practice it is a few times larger.
  • Implication: minute data for a year is hundreds of GB to low TB. That is fine for an OLAP store, but scanning a year of minute rows for one query is wasteful. Hourly and daily rollups make long-range queries cheap.

Dedupe state.

  • To reject duplicate clicks, we remember recently seen impression ids. With 100M clicks per day and 16-byte ids, the raw ids are 1.6 GB per day.
  • In Redis, each key costs much more than its 16 bytes, because of per-key overhead (the dictionary entry, the object header, and the expiry entry). A realistic figure is 60–90 bytes per small key, so 6–9 GB for a 24-hour window. That is still small enough for a modest Redis Cluster.
  • Implication: dedupe is affordable as an exact set. A probabilistic structure (a Bloom filter) is an option only if memory becomes the constraint (Deep Dive 4).

Queries.

  • Suppose 1M active advertisers. Say 10% open a dashboard during the busiest hour, each refresh issues about 5 queries, and dashboards refresh every 30 seconds while open. That gives a few thousand queries per second at peak.
  • Each query reads pre-aggregated rows for one advertiser's ads, so it touches thousands to millions of rows, not billions.
  • Implication: query load is moderate. A cache in front of the OLAP store helps with repeated dashboard refreshes, but the real work is making each query read little data, through pre-aggregation and a good shard and sort key.

Click service.

  • One instance of a lightweight stateless service handles a few thousand simple requests per second. To serve 10k/s at peak with headroom and spread across three availability zones, 10–20 instances is comfortable.
  • Implication: the click service is cheap to scale horizontally. Its latency budget matters more than its count.

Core Entities#

  • Ad: an advertisement with its id, its owning ad group, campaign and advertiser, its destination URL, and its status. It is owned by the ad-serving side; we read it.
  • Impression: one display of an ad to one user, identified by a unique, signed impression id created when the ad is served.
  • Click event: the raw record of one click: impression id, ad id, timestamp, and context such as device and country. Immutable.
  • Click aggregate: the count of valid clicks for an (ad, time bucket, dimensions) combination, for example (ad 123, 10:41, US, mobile) = 57. It may also hold a sketch for approximate unique users.
  • Advertiser: the customer who owns ads and queries their metrics, and whose account, timezone and access rights scope every query.
  • Reconciliation run: a record that a batch recount covered a given time range, what it found, and which aggregates it corrected.

API Design#

The system has two very different interfaces: a public, unauthenticated click endpoint on the user's path, and an authenticated query API for advertisers.

# 1. Click (user's browser or app; no login required)
GET /click?imp={signedImpressionToken}
  -> 302 Found, Location: https://advertiser.example/landing?utm_source=...
  Idempotent by impression id: a repeated click redirects again but is counted once.

# 2. Click for apps that track separately (mobile SDK, server-to-server)
POST /v1/clicks
  body: { impressionToken, clientTs, context: { device, appVersion } }
  -> 202 Accepted   (idempotency key = impression id inside the token)

# 3. Metrics over time (advertiser dashboard and API)
GET /v1/advertisers/{advertiserId}/metrics
    ?level=ad|adgroup|campaign&ids=123,456
    &from=2026-12-01T00:00Z&to=2026-12-02T00:00Z
    &granularity=minute|hour|day&groupBy=country,device&tz=Asia/Kolkata
  -> 200 { series: [ { id, bucket, clicks, uniqueUsersApprox } ], 
           freshness: { completeUntil, preliminaryAfter } }

# 4. Totals for a list view (all my campaigns, today)
GET /v1/advertisers/{advertiserId}/summary?from=...&to=...&level=campaign
  -> 200 { rows: [ { campaignId, clicks, spend } ] }

# 5. Bulk export for large reports (asynchronous)
POST /v1/advertisers/{advertiserId}/reports
  body: { query, format: "csv" | "parquet" }
  -> 202 { reportId }
GET  /v1/advertisers/{advertiserId}/reports/{reportId}
  -> 200 { status, downloadUrl }

# 6. Internal: ad metadata lookup for redirects (cached)
GET /internal/ads/{adId}  -> { destinationUrl, status, advertiserId, campaignId }

Notes.

  • The click endpoint is a GET because it is reached by a link or a tap. It returns 302 (Found), not 301 (Moved Permanently). Browsers may cache a 301, and a cached redirect sends the user straight to the advertiser next time, with no click recorded.
  • The destination comes from the ad record, never from a URL parameter. A click endpoint that redirects to any URL passed to it is an open redirect, which attackers use for phishing ("this link is on a trusted ad domain"). The token identifies the ad, and the service looks up the destination.
  • Idempotency: the impression id is the idempotency key for both click endpoints. See Idempotency and Safe Retries.
  • Query API: it is authenticated (OAuth tokens for API clients, session cookies for the dashboard) and authorised per advertiser. The advertiserId in the path must match the caller's account or an agency that manages it. Rate limits protect the OLAP store from runaway scripts.
  • Freshness metadata: each response says up to when the data is complete (all windows closed) and after which time it is preliminary. This makes the speed-versus-accuracy trade-off visible to the user instead of hiding it.
  • Timezone: advertisers think in their own day ("clicks yesterday" in Mumbai), so the API accepts a timezone, and the storage design must support it (Deep Dive 6).

High-Level Design#

This is a data-processing problem, so it helps to state the system interface and the data flow before drawing boxes.

  • Input: click events from users' browsers and apps.
  • Output: aggregated click metrics for advertisers.
  • Data flow: a user clicks an ad, the click is recorded, the user is redirected, the click is aggregated, and advertisers query the aggregates.

We start with that simple flow and improve it one requirement at a time.

1) Users can click an ad and be redirected#

An Ad Placement Service (part of ad serving, which is out of scope) decides which ad to show and sends the creative to the page together with its metadata. We treat it as a black box. All we need from it is the ad, and a way to get the user to the advertiser's site when they click. There are two ways to handle the redirect.

Good: client-side redirect. The ad on the page carries the advertiser's URL directly. When the user clicks, the browser goes straight to the advertiser, and in parallel the page sends a tracking request to our /click endpoint (often with navigator.sendBeacon, which lets the browser finish the request even as the page unloads).

  • Why it is attractive: it is simple, and our service is off the user's critical path. If tracking is slow or down, the user still reaches the advertiser.
  • Why it falls short: we can miss clicks. The tracking request can fail, be blocked by an ad blocker or a privacy extension, or be dropped when the page unloads. A user can also copy the destination URL out of the page and visit it directly. Every missed click is unbilled revenue, and it makes our numbers disagree with the advertiser's own analytics.

Great: server-side redirect. The ad links to our endpoint, for example https://click.ads.example/c?imp=<signed token>. When the user clicks, the browser calls us. We validate the token, record the click, and answer with 302 Found and a Location header pointing at the advertiser's URL.

  • Why it wins: every click that reaches the advertiser passes through us, so tracking is complete by construction. We can also append tracking parameters to the destination (such as a click id or UTM tags) so the advertiser's analytics can tie the visit to the campaign.
  • The cost: we are now on the user's critical path. The click service must be fast (a few milliseconds of work, no slow dependencies) and highly available (multi-zone, deployed close to users). This shapes the click path: it does the minimum synchronously (validate, write to a durable stream, redirect) and leaves everything else to asynchronous processing.

Mobile apps usually behave the same way: the ad opens a URL that passes through the click endpoint. Some app-install ads and in-app formats instead report clicks with a server-to-server or SDK call (the POST /v1/clicks endpoint), and the same validation and dedupe apply.

Edge placement. The click endpoint is a good candidate to run close to users, in several regions or at edge locations, because every millisecond of redirect delay is felt by the user. The ad metadata it needs (ad id to destination URL) is small: 10M ads × a few hundred bytes is a few GB, and the hot subset fits easily in each instance's local memory, backed by Redis.

2) Advertisers can query click metrics over time at 1-minute intervals#

The user is redirected. Now the click must turn into numbers an advertiser can query quickly. Once /click receives a request, what happens next?

Bad: store and query from the same database. Insert every click as a row in a relational table, and answer queries with aggregation over the raw rows:

SELECT date_trunc('minute', ts) AS minute,
       COUNT(*)                AS clicks,
       COUNT(DISTINCT user_id) AS unique_users
FROM   click_events
WHERE  ad_id = 123
  AND  ts >= '2026-12-01 00:00' AND ts < '2026-12-02 00:00'
GROUP  BY 1
ORDER  BY 1;
  • It is simple, and it is a reasonable first sentence in an interview, but at our scale it fails. The table grows by 100M rows a day, every dashboard load re-aggregates raw rows, and an advertiser with 500 ads over a month scans hundreds of millions of rows. The same database is also absorbing 10k inserts per second. Reads and writes fight over the same disks and indexes, and query latency goes from milliseconds to minutes. It breaks both the "sub-second queries" and the "handle the write peak" requirements.
  • The deeper lesson: do not compute aggregates at read time when the same aggregates are requested over and over. Compute them once, when data arrives or shortly after, and store the result.

Good: a separate analytics database, fed by batch processing. Split storage by purpose:

  1. The click service writes raw events to an event store built for heavy writes, such as Cassandra (an LSM-tree store: each write goes to an append-only commit log and an in-memory memtable, which is flushed to sorted SSTable files; see Storage Engines: B-Trees vs LSM Trees). LSM stores absorb writes cheaply, but they are not built for large scans and aggregations, which is why we do not query them directly.
  2. Every few minutes, a scheduled batch job (Apache Spark, run by a cron or an orchestrator) reads the new raw events, groups them by (ad, minute), counts them, and writes the results to an OLAP database.
  3. Advertisers query the OLAP database, which holds compact, pre-aggregated rows: (ad_id, minute, clicks).

How much data does each batch read? At 10k clicks/s and a 5-minute interval, a batch holds 3M events. At 100 bytes or so each in compact form, that is about 300 MB. Honestly, one machine could aggregate 300 MB in seconds, so Spark is not strictly needed at this size. It is still a good choice: it gives a well-understood MapReduce model (map each event to a key (ad, minute) and the value 1, shuffle by key, reduce by summing), it parallelises automatically when volume grows, and it handles retries of failed tasks.

Why an OLAP database. Online Analytical Processing (OLAP) databases such as Snowflake, BigQuery, Redshift and ClickHouse store data by column rather than by row. A query that sums one column over millions of rows reads only that column, compressed, and processes it in vectorised batches. That makes SUM and COUNT over large ranges orders of magnitude faster than in a row store. See Data Pipelines, Warehouses and Lakes.

Why not a time-series database? A time-series database (TSDB) such as InfluxDB, TimescaleDB or Prometheus is excellent when the question is "values of metric X over time range Y" and the number of distinct series is modest. Here we have millions of ad ids (millions of series), and advertisers want to slice by several dimensions (campaign, country, device). That is a high-cardinality, multi-dimensional workload, which columnar OLAP stores handle better. If the interviewer limits the problem to simple per-ad time ranges, a TSDB is a reasonable choice, as long as you can explain the trade-off. See Time-Series Databases.

The problems with batch.

  • Latency. Data is always at least one batch interval old, plus the time the job takes to run. With a 5-minute interval, advertisers see numbers 5–10 minutes stale.
  • Spikes. A sudden burst of clicks (a big launch, a Super Bowl ad) puts write pressure on the event store, and the next batch has much more data, so it runs longer. If a batch takes longer than the interval, batches start to overlap or fall behind. The data falls further behind exactly when advertisers are watching most closely.
  • A queue between the click service and the event store absorbs write spikes, but it does nothing for latency. To fix both, we process events as they arrive.

Great: real-time aggregation with stream processing.

  1. The click service writes each click to a stream: Kafka or Amazon Kinesis. The stream is durable and replicated, and it absorbs bursts.
  2. A stream processor (Apache Flink, or Spark Structured Streaming) reads the stream and keeps running counts in memory per (ad, minute) window.
  3. When a window closes, or periodically before that, it writes the counts to the OLAP database.
  4. Advertisers query the OLAP database and see data that is seconds old.

Why Flink, and not plain Kafka consumers? You could write a consumer that keeps counts in a hash map and flushes them every minute, and for a mid-level interview that is a fair answer. Flink provides, ready-made, the parts that are hard to get right:

  • Event-time windows: a click is placed in the minute it happened, not the minute it was processed, so a click delayed in the pipeline still lands in the right bucket.
  • Watermarks: a running estimate of "event time has reached T", which tells Flink when it is safe to close a window.
  • Fault tolerance: periodic, consistent checkpoints of operator state and Kafka offsets, so a crashed job resumes without losing or double-applying events.
  • Exactly-once state semantics, and transactional or idempotent sinks for exactly-once output. See Apache Flink and Stream Processing and Batch vs Stream Processing.

Is streaming really faster than batch? It is a fair challenge. If Flink uses 1-minute windows and only writes when a window closes, and Spark runs every minute, their latencies are similar (Spark is a little slower, because of job start-up and scheduling). The difference is in the levers:

  • Shrinking a Flink window or flush interval to a few seconds is cheap. Running a Spark batch every few seconds is not, because each run pays start-up, scheduling and file-listing overhead.
  • Flink can aggregate on minute boundaries but emit early results every few seconds (an early-firing trigger). The current minute's number then grows live on the dashboard and becomes final when the minute closes. This is the behaviour advertisers expect: the latest minute is incomplete until it ends.

3) Each click is counted at most once#

Duplicates come from many places: a double tap, a browser retry after a timeout, a user pressing Back and clicking again, a client SDK retrying a POST, and replays inside our own pipeline after a crash. The design has two halves:

  • Define what "the same click" means. The right unit is the impression. The Ad Placement Service gives every display of an ad a fresh, unique impression id, signed so it cannot be forged. One impression can produce at most one billable click. A user who is shown the same ad again later (for example, through retargeting) gets a new impression and can produce a new click.
  • Enforce it in the pipeline. The click service verifies the signature and rejects clicks whose impression id has already been seen (using a fast store of recent ids), and the downstream aggregation and recount also dedupe by impression id. Deep Dive 4 covers the options in detail.

The full high-level design#

Components:

  • Load balancer and regional entry: terminates TLS, spreads clicks across click-service instances in several availability zones, and routes users to a nearby region.
  • Click Service: stateless. It verifies the impression token's HMAC signature, looks up the ad's destination, checks the dedupe store, produces the click to Kafka, and returns the 302. It never waits on anything slow.
  • Ad metadata cache: ad id → destination URL, status and owner ids. A local in-process cache backed by Redis, filled from the ads database.
  • Dedupe store (Redis Cluster): remembers impression ids seen in the last 24 hours or so, with a TTL. It is a fast first filter for duplicates on the click path.
  • Kafka clicks topic: the durable source of truth for raw clicks. Partitioned by ad id (with salting for hot ads), replicated three times, retained for 7 days so any consumer can replay.
  • Flink job (speed layer): dedupes again by impression id (exact, with keyed state), filters obviously invalid clicks, assigns each click to its event-time minute, merges sub-counts for hot ads, and writes per-minute counts to the OLAP store, with early results every few seconds.
  • Kafka Connect S3 sink and data lake: continuously archive every raw click to object storage as Parquet, without touching Flink. This is the ballot box.
  • Spark recount and reconciliation (batch layer): re-aggregates raw clicks from the lake hourly and daily, compares the results with the speed layer's numbers, and writes corrected, final counts.
  • OLAP store: columnar tables at minute, hour and day granularity, sharded by advertiser and sorted by ad and time.
  • Query Service and cache: authenticate the advertiser, choose the right rollup table for the requested range, run the query, cache recent results briefly, and label the data as complete or preliminary.

Key Flows#

Flow 1: a click, from tap to dashboard#

  1. The click service verifies the token first. A forged or tampered token is rejected before it costs anything else: no click is produced, and the user lands on a neutral page rather than at an address the token claimed. Verification accepts the current and the previous signing key, so a key rotation never invalidates ads that are already on screen.
  2. It checks Redis for the impression id. If it was already seen, the click is a duplicate: the user is redirected, and nothing is produced.
  3. It writes to Kafka before marking the id as seen. If the process dies between the two steps, the worst case is a duplicate that later layers remove. The reverse order could mark a click as seen and then fail to record it, losing it forever. A lost click cannot be recovered. A duplicate can.
  4. Only after Kafka acknowledges (with acks=all, so the event is on all in-sync replicas) does the user get the redirect. If Kafka is slow, the service waits a few milliseconds. If Kafka is unavailable, the service spills to a local disk buffer and still redirects (Deep Dive 3).
  5. Flink counts the click into its minute window and writes the running count early and often, then the final count once the watermark says the minute is complete.

Flow 2: an advertiser opens the dashboard#

  1. Authorisation is per advertiser. The service checks that the requested campaign belongs to the caller before it queries anything.
  2. The planner picks the coarsest table that answers the question: day rows for months, hour rows for days, minute rows only for the recent edge. A 7-day hourly chart reads 168 rows per series instead of 10,080 minute rows.
  3. Closed periods do not change often (only on reconciliation), so their results are cacheable. The open period is always read fresh.
  4. The response carries freshness markers, so the dashboard can shade the preliminary part of the chart.

Flow 3: hourly reconciliation#

  1. The recount waits for a grace period so late events have arrived in the lake.
  2. It recomputes the same aggregates from the raw data, with exact dedupe over the whole period (not just a TTL window).
  3. It overwrites the speed layer's rows with a higher version, so the OLAP store now holds final numbers for that hour.
  4. The drift between the two layers is itself a key health metric. Normally it should be tiny (well under 0.1%). A jump means a bug or an incident in the speed layer.

Data Model#

The click events live in Kafka and the lake, not in a database. The minute and hour aggregates live in the OLAP store. Here is the minute table in ClickHouse, with the overwrite-friendly engine:

-- One row per (ad, minute, dimensions, part). "part" is the hot-key salt (0 for normal ads).
-- Each write carries the cumulative count and a version; the highest version wins.
CREATE TABLE clicks_minute
(
    advertiser_id UInt64,
    campaign_id   UInt64,
    ad_id         UInt64,
    minute        DateTime('UTC'),
    country       LowCardinality(String),
    device_type   LowCardinality(String),
    part          UInt16,
    clicks        UInt64,
    version       UInt64          -- e.g. emit time in ms; batch corrections use a higher range
)
ENGINE = ReplacingMergeTree(version)
PARTITION BY toYYYYMMDD(minute)
ORDER BY (advertiser_id, campaign_id, ad_id, minute, country, device_type, part)
TTL minute + INTERVAL 90 DAY;
 
-- Query: clicks per minute for one campaign over a day.
SELECT minute, sum(clicks) AS clicks
FROM clicks_minute FINAL
WHERE advertiser_id = 42 AND campaign_id = 77
  AND minute >= '2026-12-01 00:00:00' AND minute < '2026-12-02 00:00:00'
GROUP BY minute
ORDER BY minute;

Design notes.

  • Sort key first, shard key second. In a columnar store, the sort key (ORDER BY) decides which rows are physically together. Leading with advertiser_id, campaign_id, ad_id, minute means a query for one advertiser's campaign over a day reads one small, contiguous range. In a distributed setup we also shard by advertiser_id, so one advertiser's data sits on one shard and a dashboard query touches one node (with replicas for reads and failover). The very largest advertisers can be spread over several shards by hashing (advertiser_id, ad_id) instead.
  • Why ReplacingMergeTree. Flink writes the cumulative count for a row several times (early results, then the final count, then perhaps a late correction), and reconciliation writes again with a higher version. Overwriting by version makes every write idempotent: replaying the same output twice changes nothing. Background merges keep only the newest version. Until a merge happens, duplicate versions can coexist, so queries use FINAL (or an argMax(clicks, version) pattern) to see only the latest. FINAL costs some query CPU, and on large ranges we avoid it by reading the hour and day tables, which are written once per period.
  • The part column holds the salt for hot ads (Deep Dive 2). Normal ads always use 0. The query sums across parts, so the salt is invisible to users.
  • Partitions by day and a TTL. Daily partitions make retention cheap (drop a whole partition) and let reconciliation rewrite one day cleanly. Minute data is kept for 90 days, hour data for about two years, and day data indefinitely.
  • LowCardinality columns dictionary-encode strings such as country and device, which saves space and speeds up filtering.
  • Hourly and daily tables are written by the recount job (or by Flink's hourly windows), not by a materialized view that fires on every minute-level insert. A summing materialized view would see each overwrite of the minute row as a new increment and count it again. This is a subtle trap: overwrite semantics and incremental rollups do not mix, so pick one per table.

Database choice. Click events are an append-only, replayable log, so they belong in Kafka (hot, 7 days) and an object-storage data lake (cold, years). Aggregates need fast filtered sums over billions of rows, so they belong in a columnar OLAP store. ClickHouse is a strong self-managed choice, Apache Druid and Apache Pinot are built for real-time ingestion from Kafka with pre-aggregation, and BigQuery or Snowflake work well for the batch-only version and for ad-hoc analysis. Ad and campaign metadata is ordinary relational data in PostgreSQL or MySQL, cached in Redis. The trade-offs are covered in Choosing a Database: A Decision Guide.

DataStoreWhy
Raw clicks (hot)Kafka, replication factor 3, 7-day retentionDurable, ordered per partition, replayable by every consumer
Raw clicks (cold)S3 or GCS data lake, Parquet, partitioned by hourCheap, years of history, input to recounts and backfills
Recent impression idsRedis Cluster with TTL, replicatedMicrosecond duplicate checks on the click path
Per-minute aggregatesClickHouse, Druid or PinotSub-second sums over many rows, high cardinality
Hourly and daily rollupsSame OLAP store, separate tablesLong-range queries read thousands of rows instead of millions
Ad and campaign metadataPostgreSQL plus Redis cacheRelational, small, read-heavy
Reconciliation runs and driftPostgreSQL or the OLAP storeSmall audit table for operators
Flink state and checkpointsRocksDB on local disk, checkpoints in S3Large keyed state with fast recovery

Deep Dives#

1. How do we scale to 10k clicks per second, and then to 100 times that?#

Walk the path a click takes and size each tier in turn. The aim is that every tier scales horizontally, and every tier is partitioned by the same key, so work stays local.

Click Service. Stateless, so it scales by adding instances behind a load balancer, with auto-scaling on CPU or request rate. The work per click is small: verify an HMAC (microseconds), a local-cache lookup for the ad, one Redis round trip (under a millisecond within a zone), and one Kafka produce (a few milliseconds with acks=all). Two habits keep it fast:

  • Batch the Kafka produces. The Kafka producer client already batches records per partition (linger.ms of a few milliseconds, batch.size of tens of KB). A small linger adds a few milliseconds of latency but cuts the request rate to brokers by orders of magnitude.
  • No synchronous calls to anything slow. The click service never calls the OLAP store, the ads database or a fraud model synchronously. Anything that can be asynchronous happens after Kafka.

Stream. Kafka scales by partitions. At 2 MB/s the bandwidth needs only a couple of partitions, but we choose more, perhaps 64, for three reasons: each partition is consumed by one Flink task, so partitions cap parallelism; hot ads need room to spread; and growing the partition count later remaps keys, which disturbs ordering and state, so it is better to start with headroom. With Kinesis, the limits are per shard (1 MB/s or 1,000 records/s for writes, 2 MB/s for reads), so 10k records/s needs at least 10 shards, and we would provision about 20.

Partition key. We key the stream by ad id. All clicks for one ad then land in one partition and are processed by one Flink task, so the per-ad, per-minute count is computed in one place, with no cross-task merging. Partitions are independent, so they are processed in parallel. The catch is hot ads, which Deep Dive 2 handles.

Stream processor. A Flink job's parallelism (the number of parallel instances of each operator) is set to match the partition count, or a divisor of it. Each task holds the windows for its ads. The state is small: tens of thousands of active (ad, minute) counters at a time, plus the dedupe state (Deep Dive 4). If load grows, we raise the parallelism and restart from a savepoint. Flink redistributes keyed state across the new tasks through key groups (a fixed number of hash buckets, set by the job's maximum parallelism, that can be reassigned to tasks).

OLAP store.

  • Managed warehouses (BigQuery, Snowflake) scale storage and compute for you, and you do not control placement.
  • Self-managed stores (ClickHouse, Druid, Pinot) let you choose the sharding. Shard by advertiser id, because nearly every query is "my ads". An advertiser's dashboard showing all their campaigns then hits one shard.
  • Add replicas to scale reads and survive node loss. Monitor query latency per shard, because one huge advertiser can make one shard hot. If that happens, give that advertiser's data a finer shard key, such as (advertiser_id, campaign_id).

Ingestion into OLAP. Flink writes in batches: one insert per few seconds per task, containing thousands of rows. ClickHouse in particular strongly prefers fewer, larger inserts. Each insert creates a new data part on disk that must later be merged, and many tiny inserts overwhelm the merge process ("too many parts" errors). Batching here is the Pattern: Scaling Writes technique of trading a little latency for much higher throughput.

At 100 times the scale (1M clicks/s). Nothing in the shape changes, and the numbers are still reasonable:

  • Click service: hundreds of instances across regions.
  • Kafka: 200 MB/s of produce, about 600 MB/s with replication. That is a dozen or more brokers and hundreds of partitions.
  • Flink: parallelism in the hundreds, and the dedupe state grows to hundreds of GB, which RocksDB handles on local SSDs with incremental checkpoints.
  • OLAP: more shards. The aggregate row rate grows more slowly than the click rate, because pre-aggregation collapses many clicks into one row.

The real step changes at that scale are impressions (if they come into scope, another 100 times the click volume), multi-region ingestion (Deep Dive 12), and cost.

2. How do we handle hot ads?#

Partitioning by ad id has one weakness. Suppose Nike launches a new ad with a famous athlete during a major sports final. Millions of people click it within minutes. Every one of those clicks goes to the same partition and the same Flink task. That task falls behind, its Kafka consumer lag grows, the ad's numbers go stale exactly when the advertiser is watching, and the backlog delays every other ad that shares the partition. In the worst case, a long backlog can exceed the retention window or overload the broker hosting that partition.

Two numbers make the risk concrete. A single Flink task can comfortably update simple counters at hundreds of thousands of events per second, so a single ad needs to be very hot before counting itself is the bottleneck. However, the partition also carries every other ad hashed to it, a task does more than count (dedupe lookups in RocksDB, filtering, serialisation), and Kinesis shards cap at 1,000 records/s. So hot keys are a practical concern, and the interviewer will ask.

Basic: give the partition more resources. Faster machines, or a dedicated partition for the known-hot ad. It helps a little, but a single key still cannot be processed by more than one task, so there is a hard ceiling.

Better: salt the keys of known-hot ads. For ads expected to be popular (by budget, by the advertiser's history, or flagged at campaign launch), the click service appends a random suffix to the partition key: adId:0 to adId:N-1. Clicks for that ad now spread over N partitions and N Flink tasks. Each task counts its own share, and the outputs are combined:

  • Write sub-keys and sum at query time. Each task writes its own row, (ad, minute, part=k), with its cumulative count. The query sums over part. This is the approach in our schema. It is idempotent, because each row is owned by exactly one task and is overwritten, never incremented.
  • Or merge before writing. A second, small Flink stage keyed by the real ad id receives per-part partial counts and adds them, so the OLAP store sees one row per ad and minute. The merge stage receives N small messages per ad per emission, not millions of clicks, so it is never hot.
  • A tempting third option, having each task UPSERT ... SET clicks = clicks + x into one row, is not safe. An increment is not idempotent, so any replay or retry double-counts. Use owned rows that are overwritten, or one merge stage.

Best: detect hot keys dynamically, and pre-aggregate before the shuffle.

  • Dynamic detection. A lightweight counter (for example a count-min sketch or a sampled counter per ad, refreshed every few seconds; see Probabilistic Data Structures for Big Data) spots ads whose rate crosses a threshold. The salting decision is published to the click services through a small config channel. Because the OLAP query already sums over part, turning salting on mid-minute is safe: the minute simply has rows in several parts.
  • Local pre-aggregation (a combiner). Instead of producing every click individually, a stage can count clicks per (ad, minute) locally for a second and send only the partial sums onward. In MapReduce this is called a combiner. In Flink, it is a "mini-batch" or local-aggregation step before the keyBy. A hot ad receiving 100k clicks/s across 50 upstream tasks then sends 50 partial counts per second to its key's task, instead of 100k events.
  • This is hierarchical aggregation: many small counters feed fewer bigger counters, which feed a final total. It is the same idea a vote count uses: each polling station counts its own ballots, districts add up stations, and only district totals travel to the national tally.

The trade-off. Salting costs a little query work (summing over parts) and some complexity in the pipeline. Local pre-aggregation adds up to a second of delay before the counts move on. Both are cheap compared with a partition that cannot keep up. Note also that dedupe must still be exact under salting. A duplicate click for a salted ad can land on a different partition from the original, so the dedupe check cannot be partition-local unless dedupe is keyed by impression id. That is why exact dedupe in Flink happens in its own stage, keyed by impression id, before the clicks are re-keyed by ad (Deep Dive 4).

3. How do we make sure no click is ever lost?#

"No click lost" has to hold at every hop: the user's device to the click service, the click service to the stream, inside the stream, through processing, and in the final store.

From the device to the click service. With a server-side redirect, if the click service does not respond, the user is not redirected. So the click endpoint must be very highly available: several instances in several availability zones, health-checked by the load balancer, and deployed in several regions with DNS or anycast failover. For SDK-reported clicks (POST /v1/clicks), the SDK keeps the click in a small on-device queue and retries with backoff until it receives 202. The impression id makes the retries safe.

From the click service to the stream. The click service should treat a click as accepted only when the stream has durably stored it:

  • acks=all with min.insync.replicas=2 (on a topic with replication factor 3): the leader acknowledges only once at least two replicas have the record. A single broker failure then cannot lose an acknowledged click.
  • Idempotent producer (enable.idempotence=true, the default in recent Kafka versions): the broker discards duplicate records caused by producer retries, using a producer id and per-partition sequence numbers.
  • unclean.leader.election.enable=false: never elect an out-of-date replica as leader, which would silently drop acknowledged records.
  • What if Kafka is unreachable? Most designs choose to keep redirecting users (availability of the user path matters most) and spill clicks to a local, append-only disk buffer on the click-service host, replayed to Kafka when it recovers. The buffer must survive restarts and be monitored, because a host that dies with its disk loses the spilled clicks. Keeping such outages rare (a multi-zone Kafka cluster) matters more than the buffer.

Inside the stream. Kafka replicates each partition across brokers in different availability zones. Kinesis replicates across three availability zones automatically. Data is also retained after it is consumed: we set 7 days of retention. If the Flink job breaks on a Friday night, it can be fixed on Saturday and replay from the point of failure, and nothing is lost.

Through processing: checkpoints versus replay. Flink periodically takes a checkpoint: a consistent snapshot of every operator's state and the Kafka offsets that state corresponds to, written to durable storage such as S3. After a crash, the job restores the last checkpoint and resumes reading from the stored offsets. Is checkpointing needed here? This is a good place to think rather than recite:

  • Our windows are one minute long. If the job lost all in-memory state, it could simply rewind its Kafka offsets a few minutes (to the start of the oldest open window) and recompute. Kafka retention makes that replay possible.
  • So for the counting state, checkpointing is a convenience, not a necessity. It shortens recovery from minutes to seconds and avoids reprocessing, but the system would be correct without it.
  • It matters much more for long-lived state: daily windows, or the 24-hour dedupe state keyed by impression id. Rebuilding a day of dedupe state by replaying a day of clicks is slow, so that state is checkpointed (incrementally, with RocksDB) every minute or so.
  • Saying this out loud ("checkpointing is often proposed reflexively, but with 1-minute windows replay is enough; checkpoints matter for the long-lived dedupe state") is the kind of judgement that signals seniority.

In the final store. The OLAP store is replicated (ClickHouse replicated tables via ClickHouse Keeper or ZooKeeper, Druid deep storage in S3, Pinot segment replicas), and it is rebuildable: every number in it can be recomputed from the raw clicks in the lake. That is the strongest durability guarantee in the design. The aggregates are a cache of a computation over an immutable log.

The raw archive. A Kafka Connect S3 sink (or Kinesis Data Firehose, with Kinesis) continuously writes raw clicks from the topic to object storage, partitioned by hour, in Parquet. It runs independently of Flink, so a Flink bug cannot corrupt the archive. With the lake, our 7-day Kafka window becomes years. See Object Storage and Blob Storage.

4. How do we count each click exactly once?#

There are two separate problems: duplicate clicks from outside (users, browsers, SDKs, attackers), and duplicate processing inside our pipeline (retries and replays). Both must be solved.

Basic: dedupe on user id and ad id. Require login, take the user id from the session or token, and count at most one click per (user, ad).

  • It needs every user to be logged in, which is not the case for many ad surfaces (that is a product decision to raise with the interviewer).
  • It also gets the definition wrong. Advertisers use retargeting, deliberately showing the same ad to the same person several times over days or weeks. If that person clicks on Monday and again on Friday, those are two legitimate clicks. A per-user-per-ad rule would drop the second one. The correct rule is one click per user per ad instance, that is, per impression.
  • And it must run before aggregation windows, for a reason that applies to every dedupe scheme: if dedupe lived inside a 1-minute window, a duplicate that arrived just after a minute boundary would fall in a different window and be counted again.

Better: a unique impression id, checked in a cache. The Ad Placement Service generates a fresh, unique id for every rendering of an ad (a thousand users seeing the same Nike ad means a thousand ids, and one user seeing it twice means two). It is sent with the ad, and the click carries it back. The click service checks a fast store: if the id was seen, the click is a duplicate; if not, it records the click and remembers the id.

  • The weakness: anyone can invent ids. A bot that sends clicks with random, never-seen ids gets every one counted.

Best: signed impression ids, plus layered dedupe.

  • Sign the token. When the ad is served, the Ad Placement Service creates a token containing the impression id, the ad id, the serve time, and perhaps the placement. It signs the token with an HMAC (a keyed hash, such as HMAC-SHA256) using a secret shared with the click service. On a click, the click service recomputes the HMAC and rejects any token that does not match.
  • Bind the token to the ad. Because the ad id is inside the signed token, an attacker who harvests valid tokens cannot replay them against a different ad.
  • Expire the token. The serve time lets the click service reject tokens older than, say, 24 hours, which also bounds how long the dedupe store must remember ids.
  • Cost. HMAC verification is a hash computation with no asymmetric cryptography: a few microseconds. It adds nothing measurable to the redirect.
  • Layered dedupe. Each layer catches what the one before it might miss:
    1. Click service + Redis: a fast, best-effort filter. It catches the common case (double clicks and retries seconds apart). It is not perfect: two duplicate requests arriving at the same instant on two instances can both see "not seen" (the check and the set are not atomic across the produce step), and a Redis failover can lose recently written ids.
    2. Flink, exact, keyed by impression id: the first Flink stage keys clicks by impression id and keeps a small keyed state ("seen") with a TTL of about 24 hours (matching token expiry). A second copy of an impression is dropped here, regardless of timing or partition. Because this state is checkpointed with the Kafka offsets, it is exactly consistent with what the job has processed.
    3. The batch recount: dedupes by impression id over the entire period, with no TTL limit, as the final authority.

Why write to the stream before marking the id as seen? Two possible orders on the click path:

  • Mark, then write: if the write to Kafka fails after the mark, the id is recorded as seen, the user's retry is dropped as a duplicate, and the click is lost.
  • Write, then mark: if marking fails after the write, a retry is written again, and we have a duplicate, which layers 2 and 3 remove. A duplicate is recoverable and a loss is not, so we write first.

Why not dedupe only in Flink and skip Redis? You can, and many designs do: Flink's keyed dedupe stage is exact on its own. Redis earns its place in two cases: when other consumers of the raw stream (budget pacing, fraud models, the archive) should not see obvious duplicates, and when the click service should behave differently for a duplicate (for example, not appending a fresh click id to the destination URL). If neither applies, dropping Redis removes a dependency from the user's critical path, which is a real benefit.

Sizing the dedupe state. A day of impression ids is 100M × 16 bytes = 1.6 GB of raw ids, which is about 6–9 GB in Redis with per-key overhead, or a few GB in RocksDB (compressed, on SSD). Both are small. If memory ever became the constraint, a Bloom filter (about 10 bits per id for a 1% false-positive rate, so about 120 MB per 100M ids) would shrink the store a lot. But a false positive in dedupe means a real click is discarded as a duplicate: undercounting and lost revenue. So a Bloom filter is acceptable only as the first filter, with exact dedupe behind it, or where 1% loss is explicitly acceptable. For billing, keep the exact layer.

Exactly-once inside the pipeline. The external duplicates are gone. Now our own retries must not double-count:

  • Kafka producer: idempotent, as above.
  • Flink state: checkpoints use the asynchronous barrier snapshotting algorithm, described by Carbone and colleagues in "Lightweight Asynchronous Snapshots for Distributed Dataflows" (2015) and based on the Chandy-Lamport snapshot idea. On recovery, state and input offsets roll back together, so each event affects state exactly once.
  • Flink to the OLAP store: after a recovery, Flink re-emits results computed after the last checkpoint. The sink must make that harmless. There are two ways:
    • Idempotent writes (our choice): each output row is keyed by (ad, minute, dimensions, part) and carries the cumulative count with a version. Writing it twice leaves the same final value.
    • Transactional writes: a two-phase-commit sink that commits output only when a checkpoint completes (Flink's Kafka sink works this way, using Kafka transactions). It gives exactly-once output to sinks that support transactions, at the cost of latency equal to the checkpoint interval, because results become visible only on commit.
  • The general rule, from Delivery Guarantees: At-Most, At-Least and Exactly-Once: at-least-once delivery plus idempotent processing gives effectively-once results. Exactly-once is a property of the whole pipeline, not of one component.

5. How do we keep the numbers accurate: reconciliation, Lambda and Kappa#

Even with durable streams and layered dedupe, real pipelines drift. A bad deployment miscounts for twenty minutes. A Flink job is restarted from an old savepoint by mistake. A partition's events arrive so late that the watermark has passed and they are dropped. A rule change for invalid traffic is applied to the stream from noon, but should apply to the whole day. Each produces numbers that are slightly wrong, and wrong click numbers mean wrong invoices.

Correctness and low latency pull against each other. A real-time number must be produced before all the evidence is in. So we accept that the real-time number is preliminary, and we add a periodic recount that produces the final number from the complete raw data.

How reconciliation works.

  1. Archive every raw click to the data lake, independently of the speed layer (the Kafka Connect S3 sink). This archive is the source of truth.
  2. Recount on a schedule. Every hour (with a grace period of, say, 30 minutes for late data), and again daily, a Spark job reads the raw clicks for the period, dedupes exactly by impression id, applies the current invalid-traffic rules, and aggregates by (ad, minute, dimensions).
  3. Compare with the speed layer's numbers for the same period. Record total and per-advertiser drift in a reconciliation table.
  4. Correct. Write the batch results to the OLAP store with a higher version, which overwrites the speed-layer rows, and mark the period final. Billing reads only final periods.
  5. Investigate drift above a threshold. A big number is a bug to find, not just a number to overwrite. Drift is the best end-to-end test the pipeline has.

This is the Lambda architecture. Nathan Marz named it, and described it with James Warren in the book Big Data (2015): a speed layer (here Flink) gives fast, approximate results, a batch layer (here Spark over the lake) recomputes accurate results from the immutable master dataset, and a serving layer (the OLAP store) merges the two. Its strength is that the batch layer can fix anything, because it recomputes from raw data. Its known weakness is two codebases for the same logic. If the Flink job and the Spark job count "valid click" slightly differently, the drift is permanent noise, and every rule change must be made twice.

The Kappa alternative. Jay Kreps argued in "Questioning the Lambda Architecture" (2014) that, with a durable, replayable log, you can drop the batch layer: keep one stream-processing codebase, and when you need to recompute (a bug fix, a rule change), run a second instance of the same job from an earlier offset in the log, write to new output tables, and switch readers over when it catches up. That needs a log retaining as much history as you may need to reprocess, which Kafka's tiered storage (old segments kept in object storage) makes affordable.

Which to choose here? A pragmatic answer, which many ad platforms resemble, is Lambda with shared logic:

  • Keep the batch recount, because billing wants an independent check computed from raw data, and auditors like a recount that does not depend on the streaming system's state.
  • Reduce the two-codebases problem by sharing the counting logic: write the dedupe and validity rules once, as a library both jobs call, or use one engine for both. Flink can run the same program in batch mode over bounded input, and Spark Structured Streaming uses the same DataFrame API for batch and streaming.
  • If the organisation's main pain is maintaining two pipelines, Kappa is a valid alternative, but say what it costs: long log retention, and replays that compete for cluster capacity.

Twitter's Summingbird is a well-known attempt to solve the duplicated-logic problem: one program compiled to both a batch and a streaming system, described by Boykin and colleagues in "Summingbird: A Framework for Integrating Batch and Online MapReduce Computations" (VLDB 2014). Google's Mesa paper (Gupta and colleagues, "Mesa: Geo-Replicated, Near Real-Time, Scalable Data Warehousing", VLDB 2014) describes the warehouse behind Google's advertising metrics. It applies updates in versioned batches, a few minutes apart, and requires that every aggregate be associative, so updates can be merged in any grouping. That is the same property our idempotent, versioned rows depend on.

Why accuracy is cheap here. The recount reads about 4–5 GB of Parquet per day. A modest Spark cluster finishes that in minutes. The batch layer is not expensive. What it costs is engineering discipline: keeping the two definitions aligned, and treating drift as a first-class metric.

6. How do advertisers get sub-second queries, even over years?#

Pre-aggregation solved most of this already: queries read per-minute counts, not raw clicks. The remaining problem is long ranges and many series. A year of minute data for one ad is 525,600 rows. For a campaign with 200 ads, it is about 100M rows. A columnar store can scan that, but not in under a second for thousands of concurrent users.

Basic: query the minute table for everything. Fine for "last hour" and "today". Too slow and too expensive for "this year, by week".

Better: rollup tables at coarser grains. Keep minute, hour and day tables. A scheduled job (or the reconciliation job, which already recomputes each period) writes hourly and daily totals once each period is final. The Query Service picks the coarsest table that gives the requested granularity:

  • A year by day: 365 rows per series.
  • A week by hour: 168 rows.
  • The last 2 hours by minute: 120 rows.

This is trading storage for query speed on the most common queries, which is a form of caching. Rollups are cheap: the hourly table is about 60 times smaller than the minute table, and the daily table about 24 times smaller again.

Best: rollups plus a query planner, and caches for closed periods.

  • Stitch ranges. "Clicks per day for the last 30 days" reads 29 closed days from the day table, plus today from the hour table (closed hours), plus the current hour from the minute table. The planner splits a range at period boundaries and unions the parts.
  • Cache closed periods. Results for final periods change only on reconciliation. A cache keyed by (advertiser, query, period) with a TTL of minutes, invalidated by a "period finalised" event, takes most dashboard load off the OLAP store. The open period is always queried fresh.
  • Bound concurrency per advertiser. One agency script requesting a thousand years of data must not slow down everyone else. Per-advertiser rate limits and per-query limits (on rows scanned, memory, and time) are standard OLAP-store settings. Large exports go through the asynchronous report API.

The timezone trap. "Clicks yesterday" means yesterday in the advertiser's timezone. A UTC day table cannot answer that for an advertiser in New York or Mumbai. Options:

  • Compute daily rollups per timezone the advertiser uses. Each advertiser account has one timezone, so this is one daily rollup per advertiser, in its own zone.
  • Or answer day queries from the hour table, summing 24 local hours. That works for whole-hour offsets, but not for zones such as India (UTC+5:30) or Nepal (UTC+5:45), whose days begin on the half or quarter hour. For those, the hour table is not fine enough, and we need 15-minute buckets (or per-zone daily rollups) as an intermediate grain.
  • Daylight-saving changes make some local days 23 or 25 hours long. Store everything in UTC, and convert at the boundaries. A good answer names the issue and picks a strategy; most designs combine per-account-timezone daily rollups with 15-minute or minute data for recent periods.

How the OLAP engines pre-aggregate. Each real-time OLAP store has its own native way to do what our rollup tables do:

  • Apache Druid: ingestion-time rollup. As rows arrive (Druid can read directly from Kafka), it groups them by a time bucket (say, one minute) and the dimension columns, and stores pre-summed rows. Compaction can later re-roll older segments to hour or day grain. Druid's original paper is Yang and colleagues, "Druid: A Real-time Analytical Data Store" (SIGMOD 2014), and it came from an advertising-analytics company (Metamarkets), so this workload is exactly what it was built for.
  • Apache Pinot: star-tree indexes, a pre-aggregated tree over chosen dimension combinations. A query such as SUM(clicks) GROUP BY campaign WHERE advertiser = 42 can be answered from pre-aggregated nodes without scanning raw rows. Pinot came from LinkedIn, where it powers user-facing analytics such as profile-view counts.
  • ClickHouse: materialized views feeding SummingMergeTree or AggregatingMergeTree tables, which maintain rollups as data is inserted. That shifts work to write time. As noted in the data model, this works with append-only increments, not with overwrite-by-version rows. If you use materialized views, make the minute table append-only and make the sink exactly-once.
  • BigQuery and Snowflake: materialized views and clustering. They are excellent for batch-loaded data and ad-hoc analysis. Their per-query cost and latency make them a less natural fit for thousands of sub-second dashboard queries per second, though caching and BI acceleration features narrow the gap.

A design that skips Flink. Druid or Pinot can ingest raw clicks straight from Kafka and roll them up to minute grain on ingest, with exactly-once ingestion based on Kafka offsets. That removes a whole tier. The cost: dedupe by impression id and invalid-traffic filtering then need to happen before the topic Druid reads from, and hot-key handling becomes the OLAP store's problem. It is a legitimate option when the interviewer prefers fewer moving parts. Be ready to explain the ingestion path in detail if you choose it.

Watch out for flaky operations. Every one of these stores has sharp edges at scale: segment or part merges falling behind, node loss forcing rebalances, compaction storms affecting query latency. If you name one in an interview, expect a follow-up such as "walk me through how ingestion works". Pick the one you can explain.

7. How do we put each click in the right minute? Event time, watermarks and late data#

Event time versus processing time. A click's event time is when it happened. Its processing time is when Flink handles it. They differ, because of network delays, producer batching, consumer lag after a restart, and replays. If we bucketed by processing time, a 5-minute consumer outage would move 5 minutes of clicks into the minute the job recovered: a false spike followed by a false dip. Advertisers would see traffic that never happened. So we bucket by event time. See Time, Clocks and Ordering.

Whose clock? For billing, the event time should be the click service's receive timestamp, taken from server clocks synchronised with NTP, not the device's clock. Device clocks can be wrong by hours, and an attacker can set them to anything. (The device timestamp can be kept as a separate field for analysis.) This choice also keeps lateness small: lateness comes only from our own pipeline, not from phones that were offline.

Watermarks. Flink cannot know for certain that all clicks for 10:41 have arrived. A watermark is its declaration that "event time has reached T, and no more events older than T are expected." A common strategy is bounded out-of-orderness: watermark = the highest event time seen minus a fixed delay, such as 10–30 seconds. When the watermark passes 10:42:00, Flink closes the 10:41 window and emits its final count. The trade-off:

  • A longer delay catches more stragglers before closing, but final numbers appear later.
  • A shorter delay gives faster finals, but more events arrive after their window closes.

With early firing (every few seconds) the delay matters less to users: they already see the running count. It affects only when a minute is labelled complete.

Idle partitions. A watermark advances only as events arrive. If a partition has no traffic (in the middle of the night, or after a rebalance), its watermark stalls and holds back every window downstream. Flink's idleness detection (withIdleness) marks such partitions idle, so they stop holding back the overall watermark.

Late events. A click whose window has already closed is late. Options, in increasing order of quality:

  • Drop it. Simple, and wrong for billing.
  • Allowed lateness. Keep window state for a while after it closes (say, 10 minutes) and, for each late event, emit an updated count. Because our sink overwrites by version, an update simply replaces the earlier total.
  • Side output and the batch layer. Events later than the allowed lateness go to a side output (a separate "late clicks" topic or table), are counted as a lateness metric, and are picked up by the hourly recount, which sees all raw data regardless of lateness.

The lifecycle of one minute's count. While it is Open, early results are emitted every few seconds. In Updated, each further late click (within the allowed lateness) emits a new cumulative count.

These ideas, separating event time from processing time, watermarks as a heuristic for completeness, and triggers for early and late results, were set out by Akidau and colleagues in "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing" (VLDB 2015), building on Google's MillWheel system (Akidau and colleagues, VLDB 2013). The title is almost a description of this problem.

8. Invalid clicks, billing-grade numbers and budget pacing#

Sophisticated fraud detection is out of scope, but a strong answer shows where it plugs in, because it shapes the numbers advertisers see and pay for.

Kinds of invalid traffic. The industry distinguishes general invalid traffic (known data-centre IP ranges, declared crawlers and bots, obviously malformed requests, which simple rules can filter) from sophisticated invalid traffic (bots imitating humans, click farms, hijacked devices, which need models and investigation). The terms come from the advertising industry's measurement guidelines (the Media Rating Council's guidance on invalid traffic).

Where filtering happens.

  • On the click path (synchronous, microseconds): reject unsigned or expired tokens, malformed requests, and clicks from blocklisted IPs or user agents. Nothing slow belongs here.
  • In the stream (seconds): Flink applies rules that need a little state, such as more than N clicks per device per minute, clicks arriving implausibly soon after the impression was served (a human rarely clicks within 100 ms of render), or bursts of clicks from one IP range on one ad. It tags clicks as valid or invalid with a reason, rather than deleting them. Counts for invalid clicks are kept separately, so advertisers and auditors can see what was filtered.
  • In batch (hours to days): heavier models and investigations find patterns no single click reveals, such as coordinated rings. Their verdicts arrive late, and they change past numbers. The recount picks them up and rewrites final counts. That is one more reason the system must support corrections to "closed" periods.

What the advertiser sees and what they pay. Real ad platforms typically show near-real-time numbers that may later be adjusted, and they bill on filtered, final numbers. Google Ads, for instance, reports invalid clicks separately and does not charge for those it detects. Our design makes that natural: the dashboard shows preliminary counts with a freshness marker, and invoices are generated only from periods marked final by reconciliation, with credits issued for invalid traffic found later. The money itself moves through a separate ledger-based billing system, the subject of the payment-system case.

Budget pacing: a second consumer with different needs. An advertiser sets a daily budget, say $1,000 at $0.50 per click. The ad-serving system must stop showing the ad once about 2,000 billable clicks have happened. If pacing used the final, hourly-reconciled numbers, the platform could overspend for an hour. So pacing reads the speed layer (a Flink job or a Redis counter per campaign, updated within seconds) and accepts small overshoot, which the platform typically absorbs or caps. This is a useful interview point: the same click stream feeds consumers with different freshness and accuracy needs, and the stream architecture lets each read at its own pace (billing from final data, pacing from real-time counters, fraud models from raw events).

9. How do we report unique users?#

Advertisers often want "unique users who clicked", not just clicks. Counting distinct things is harder than counting.

The problem: distinct counts do not add up. Clicks are additive: clicks for 10:00–11:00 equal the sum of the 60 minute counts. Unique users are not: a user who clicked at 10:05 and 10:50 appears in two minute buckets, but is one unique user for the hour. You cannot sum per-minute unique counts to get the hourly unique count. And the exact approach, keeping the set of user ids per bucket and taking unions, means storing every id in every bucket.

Basic: exact COUNT(DISTINCT) over raw data. Correct, and fine for an offline report, but it needs raw events (or per-bucket id sets) at query time. That is far too slow for dashboards over long ranges.

Better: exact distinct counts for fixed periods, computed in batch. The daily recount computes exact unique users per ad per day. Dashboards can show daily uniques exactly. But a custom range ("unique users from Tuesday to Thursday") still cannot be built from daily numbers.

Best: mergeable sketches. HyperLogLog (HLL), introduced by Flajolet, Fusy, Gandouet and Meunier in "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm" (2007), estimates the number of distinct items using a small, fixed array of registers:

  • Hash each user id. Use the first few bits to pick a register, and record in that register the longest run of leading zeros seen in the remaining bits. A long run of zeros is rare, so it suggests many distinct items have been hashed. Combining all registers with a harmonic mean gives the estimate.
  • With m registers, the standard error is about 1.04/√m. With m = 16,384 (2^14), that is about 0.81%, using about 12 KB of 6-bit registers. Redis's PFADD and PFCOUNT use this configuration.
  • The key property: sketches merge. The sketch of a union is the register-wise maximum of the sketches. Store one sketch per (ad, hour), and the unique users for any range is the merge of the hourly sketches in that range. Distinct counts become composable, like clicks.
  • HyperLogLog++ (Heule, Nunkesser and Hall, Google, 2013) adds a sparse representation for small cardinalities and bias correction. This matters here, because most (ad, hour) buckets have only a handful of users, and 12 KB per bucket would be wasteful. A sparse sketch for 5 users is a few dozen bytes.
  • In practice: ClickHouse's uniqCombined state in an AggregatingMergeTree, Druid's and Pinot's HLL or Theta sketch columns, and BigQuery's HLL_COUNT functions all store mergeable sketches.

The trade-off. Unique users become approximate (within 1–2%) for arbitrary ranges. Billing never uses unique users (it uses clicks), so approximation is acceptable for this metric. Say that explicitly. If the interviewer requires exact uniques for arbitrary ranges, the honest answer is that it costs storing ids per bucket, and it is usually not worth it. See Probabilistic Data Structures for Big Data.

Which user id? For logged-out traffic there is no stable user id, only a device id or cookie, and privacy rules (consent requirements, browser limits on cookies and tracking) restrict what may be used. Count uniques on a hashed, consented identifier, and label the metric accordingly ("unique devices" if that is what it is).

10. How do we let advertisers slice by many dimensions?#

Advertisers will soon ask: clicks by country, by device type, by placement (feed, stories, search), by age band, by hour of day. Each dimension multiplies the number of possible aggregate rows.

The cube problem. Pre-aggregating every combination of d dimensions means up to 2^d groupings (every subset of dimensions), each with as many rows as the product of their cardinalities. With country (about 200), device (5), placement (10) and age band (6), the full grid is 60,000 combinations per ad per minute. Most of them never occur in a given minute, so storage is driven by the combinations that do. Even so, pre-aggregating every subset in advance is wasteful.

Basic: pre-aggregate only the base grain with all dimensions. Store one row per (ad, minute, country, device, placement) combination that actually occurred. Any coarser view (by country only, or campaign total) is a GROUP BY over these rows at query time. A columnar store does that quickly when the rows for one advertiser are contiguous, which our sort key ensures.

Better: add targeted rollups for the common views. The campaign-level total by hour, with no dimensions, is by far the most requested view. Give it its own small table. Breakdown views ("by country this week") read the dimensional table at hour grain.

Best: let the engine choose, and keep raw for the long tail.

  • Pinot's star-tree index pre-aggregates exactly the dimension combinations you configure, with a threshold so that only combinations with enough rows get pre-aggregated nodes. Druid's rollup does the same at ingest for the dimensions you declare.
  • Rare, ad-hoc questions (clicks by browser version for one ad last Tuesday) are answered from the raw data in the lake, with a warehouse engine (Spark SQL, Trino, BigQuery), through the asynchronous report API. They take seconds to minutes. Not every question needs a sub-second answer, and pretending it does inflates the cost of the whole design.

High-cardinality dimensions (a user id, a URL, a search keyword) should not be dimensions of the minute table. They would make nearly every click its own row, so pre-aggregation would save nothing. Keyword-level reports for search ads, for example, are computed per day, or served from the raw data.

11. How do we fix the past? Reprocessing, backfills and schema changes#

Production systems need to change history: a bug in the speed layer for two hours, a fraud verdict covering last week, a new dimension that advertisers want back-filled for 90 days. The design must make this routine, not an emergency.

Reprocess a window. Because every aggregate is a deterministic function of the raw clicks, any period can be recomputed: run the batch job over the lake for that period, with the fixed code, and write the results with a new, higher version. The ReplacingMergeTree keeps the newest version. Readers switch atomically (per row), and nothing is deleted until the merge.

Replay the stream. For a recent bug (within Kafka's 7 days), we can also start a corrected Flink job from an earlier offset or savepoint, writing with higher versions. This is the Kappa way. It is quicker to set up for recent data, but it competes with the live job for capacity, so it is throttled.

Backfill a new dimension. Add the column with a default value, deploy the stream job that fills it for new data, and run the batch job over the lake to fill history. The raw lake data must contain the field, which is the argument for archiving rich raw events, not just the fields today's aggregates use.

Schema evolution. Click events are written by one team's service and read by several consumers. Use a schema format with explicit evolution rules (Avro or Protobuf, with a schema registry that enforces compatibility). New fields are added as optional with defaults. Fields are never renamed or reused. A producer change that would break consumers is rejected at deploy time, not discovered in a 3 am incident.

Deletion requests. Privacy laws (such as the GDPR) give users the right to erasure. Aggregates contain no personal data, but the raw lake does (device ids, IPs). Partition the lake by hour, keep personal fields hashed or tokenised, and either rewrite affected files when deletion requests arrive (in batches), or keep raw personal data only for a limited period and drop the fields after that. See Data Lifecycle, Tiering and Retention.

12. How do we run globally, and survive losing a region?#

Users click ads all over the world, and the redirect must be fast everywhere. Advertisers, however, want one set of numbers.

Ingest regionally, aggregate centrally (or regionally, then merge).

  • Regional click path. Deploy the click service, its ad-metadata cache and its dedupe store in several regions. Users are routed to the nearest one (latency-based DNS or anycast). Each region writes to its own Kafka cluster, so a click never waits on a cross-ocean round trip.
  • Option A: replicate raw clicks to one aggregation region. MirrorMaker 2 (or a managed equivalent) copies each regional topic into the central cluster, where one Flink job aggregates everything. It is simple, and the global numbers are produced in one place, but the central region is a dependency for freshness, and cross-region bandwidth is used for raw events (modest here: about 2 MB/s at peak).
  • Option B: aggregate in each region, then merge. Each region runs Flink and produces per-minute partial counts keyed by (ad, minute, region). The partials are replicated to the serving region, where queries sum over regions, just as they sum over hot-key parts. Bandwidth is lower (aggregates instead of raw events), and a region's outage affects only its own partial. This is hierarchical aggregation again, one level up.
  • Dedupe across regions. Could a duplicate click arrive in two regions? It is rare (the same user would have to be routed to two regions within seconds), but possible during failover. The batch recount, which reads all regions' raw data, catches it.

Losing a region.

  • Click path: DNS or anycast routes users to the next-nearest region within a minute or so. Clicks that were in the failed region's Kafka but not yet replicated are delayed (or, if the region's storage is lost entirely, lost back to the last replication point). A short replication lag keeps this exposure to seconds.
  • Serving: the OLAP store has replicas in a second region. If the serving region fails, queries move there. The dashboard may be a few minutes stale while partials catch up.
  • Correctness: once the region recovers, its archived raw data flows into the lake, and the recount fixes any gap. A region outage becomes a temporary freshness problem, not a permanent accuracy problem, which is the right failure mode for this system. See Multi-Region and Global Data.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Viral ad sends millions of clicks to one partitionOne Flink task lags, that ad's numbers go stale, neighbours delayedSalt hot ad keys, local pre-aggregation before the shuffle, sum over parts at query time
Kafka unavailable or slowClick service cannot durably record clicksMulti-zone cluster, acks all with min ISR 2, local disk spill buffer, redirect anyway
Click service slow or downUsers stuck before reaching the advertiser, clicks lostStateless multi-zone fleet, no synchronous slow calls, multi-region routing, strict latency budget
Duplicate clicks (double taps, retries, replays)Over-counting and over-billingSigned impression ids, Redis fast filter, exact keyed dedupe in Flink, exact recount in batch
Forged clicks with invented impression idsInflated counts, advertiser budgets drainedHMAC-signed tokens bound to the ad id, token expiry, invalid-traffic rules
Flink job crash or bad deploymentReal-time numbers stall or are wrong for a periodCheckpoints and savepoints, replay from Kafka, versioned idempotent writes, canary jobs, recount corrects
Late events after the watermarkMinutes undercountedServer-side event time, allowed lateness with updates, side output, hourly recount
Idle partitions stall the watermarkNo windows close, dashboards stop advancingIdleness detection on sources, monitoring of watermark lag
Too many small inserts into the OLAP storeMerge backlog, too-many-parts errors, slow queriesBatch inserts every few seconds per task, fewer larger parts
Long-range queries scanning minute dataSlow dashboards, overloaded OLAP nodesHour and day rollups, query planner, cache for closed periods, per-advertiser limits
Speed and batch layers disagreeConfusing numbers, wrong invoicesShared counting logic, drift metric and alerts, billing only from final periods
Region outageClicks delayed or briefly lost in that regionRegional ingestion with fast replication, failover routing, recount from the global lake

What Interviewers Expect#

Mid-level. States the input (clicks) and output (metrics) clearly, and designs the redirect, preferably server-side with a 302. Recognises that querying raw clicks does not scale and pre-aggregates, at least with a periodic batch job writing to an analytics database. Handles probing questions about duplicate clicks (an idempotency key per click) and database choice (why a columnar store) sensibly, perhaps with help.

Senior. Moves quickly through the basic design to the interesting parts. Contrasts batch and stream processing and chooses streaming (Kafka plus Flink) for freshness, explaining event time, windows and watermarks at a high level. Scales each tier and partitions by ad id, and handles hot ads with key salting. Designs dedupe with impression ids and explains why dedupe cannot live inside a window. Discusses durability (replication, retention, replay) and the OLAP store, with a couple of these topics covered in real depth.

Staff and above. Frames the core tension, freshness against billing-grade correctness, and resolves it deliberately: a speed layer for preliminary numbers, an independent recount from an immutable archive for final numbers, and drift as a monitored signal (and can argue Lambda against Kappa). Makes every write idempotent (versioned cumulative rows rather than increments) and explains why that matters for replays, hot-key merges and rollups. Questions reflexive choices ("do we really need checkpoints with 1-minute windows?"). Covers signed impression tokens, late data, timezone-correct rollups, distinct counts with mergeable sketches, multi-region aggregation, and how invalid-traffic verdicts change past numbers. Ideally teaches the interviewer something from experience, for example the trap of mixing overwrite semantics with incremental materialized views.

Deep Dive: the click handler, step by stepShow

TypeScript-style pseudo-code for the click endpoint. Everything slow is kept off this path.

async function handleClick(req: Request): Promise<Response> {
  const tok = parseToken(req.query.imp);                 // base64url payload + signature
  if (!tok || !verifyHmac(tok, keys.current, keys.previous)) return neutralPage();
  if (Date.now() - tok.servedAtMs > 24 * 3600_000) return neutralPage(); // expired
 
  const ad = adCache.get(tok.adId) ?? (await adStore.fetch(tok.adId));   // local, then Redis
  if (!ad || ad.status === "deleted") return neutralPage();
 
  const event = {
    impressionId: tok.impressionId, adId: ad.id, adGroupId: ad.adGroupId,
    campaignId: ad.campaignId, advertiserId: ad.advertiserId,
    serverTs: Date.now(), device: hashDevice(req), country: geo(req.ip),
    userAgent: req.headers["user-agent"],
  };
 
  const seen = await redis.exists(`imp:${tok.impressionId}`).catch(() => false); // fail open
  if (!seen) {
    const key = hotAds.has(ad.id) ? `${ad.id}:${randInt(hotAds.parts(ad.id))}` : `${ad.id}`;
    try {
      await kafka.produce("clicks", key, encodeAvro(event)); // acks=all, idempotent producer
    } catch {
      await spillBuffer.append(key, event);                  // durable local disk, replayed later
    }
    redis.set(`imp:${tok.impressionId}`, "1", { NX: true, EX: 86400 }).catch(() => {});
  }
  return redirect302(withTracking(ad.destinationUrl, tok.impressionId));
}

Points worth saying aloud:

  • Fail open on Redis. If the dedupe store is down, the click is still recorded. Exact dedupe happens later, and a missing click cannot be recovered.
  • The Redis SET is not awaited. It is a best-effort marker, and the user does not wait for it.
  • The spill buffer is the only place the click service holds state, and it must be monitored (its size should be zero almost always).
  • Neutral page: an invalid token never redirects to a URL the token claims. That prevents open redirects.
Deep Dive: the Flink job, stage by stageShow

The job has four stages. The keying changes between them, which is the important design idea.

DataStream<Click> clicks = env
    .fromSource(kafkaSource("clicks"),
        WatermarkStrategy.<Click>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner((c, t) -> c.serverTs)
            .withIdleness(Duration.ofMinutes(1)),
        "clicks");
 
// Stage 1: exact dedupe, keyed by impression id, 24h TTL state
DataStream<Click> unique = clicks
    .keyBy(c -> c.impressionId)
    .filter(new FirstSeenFilter(Duration.ofHours(24)));   // ValueState<Boolean> with TTL
 
// Stage 2: validity rules (may need small per-device state)
DataStream<Click> valid = unique
    .keyBy(c -> c.deviceHash)
    .process(new InvalidTrafficTagger());                 // tags, routes invalid to side output
 
// Stage 3: per-minute counts, keyed by (ad, part, dims), early results every 5 s
DataStream<MinuteCount> counts = valid
    .keyBy(c -> c.adId + ":" + c.part + ":" + c.country + ":" + c.device)
    .window(TumblingEventTimeWindows.of(Time.minutes(1)))
    .allowedLateness(Time.minutes(10))
    .sideOutputLateData(LATE_TAG)
    .trigger(EarlyFiringTrigger.every(Duration.ofSeconds(5)))
    .aggregate(new CountAgg(), new ToMinuteCount());      // cumulative count + version
 
// Stage 4: batch rows and write idempotently to the OLAP store
counts.sinkTo(olapSink("clicks_minute").batchEvery(Duration.ofSeconds(5)));
counts.getSideOutput(LATE_TAG).sinkTo(kafkaSink("clicks-late"));
  • Stage 1 is keyed by impression id, so a duplicate meets its original no matter which partition, window or salt it came through. The TTL state is the 24-hour memory, stored in RocksDB and checkpointed incrementally.
  • Stage 3 is keyed by ad and part, so hot ads are spread across tasks. Because each key is owned by one task and the output is the cumulative count, the sink can overwrite.
  • EarlyFiringTrigger is not a built-in name. Flink provides continuous event-time and processing-time triggers, and custom triggers are a few dozen lines. The point is to fire every few seconds and once more at the window end.
  • The re-keying between stages causes network shuffles. At 10k events per second that is trivial, and at 1M per second it is the main cost of the job, which is where local pre-aggregation (Deep Dive 2) earns its keep.
Deep Dive: the hourly recount in SQLShow

The batch layer can be expressed as plain SQL over the lake (Spark SQL, Trino or a warehouse). It is deliberately simple, because it is the reference implementation.

-- Recount one hour: exact dedupe by impression id, then count per ad and minute.
WITH raw AS (
  SELECT * FROM lake.clicks
  WHERE dt = '2026-12-01' AND hr = 10                -- hour partition, plus a late file sweep
),
first_click AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY impression_id ORDER BY server_ts) AS rn
  FROM raw
  WHERE impression_id NOT IN (SELECT impression_id FROM lake.clicks_seen_prev_24h)
),
valid AS (
  SELECT f.* FROM first_click f
  LEFT JOIN ivt.verdicts v ON v.impression_id = f.impression_id
  WHERE f.rn = 1 AND v.impression_id IS NULL         -- not flagged invalid
)
SELECT advertiser_id, campaign_id, ad_id,
       date_trunc('minute', server_ts) AS minute,
       country, device_type, 0 AS part,
       COUNT(*) AS clicks
FROM valid
GROUP BY 1, 2, 3, 4, 5, 6;
  • Cross-hour duplicates: a duplicate of a click from the previous hour must also be removed, hence the check against impression ids seen in the preceding 24 hours. Dedupe by impression id is exact here, with no TTL compromise.
  • Late files: events that arrived after the hour closed are written to later lake partitions, so the recount reads the target hour by event time, sweeping a few later partitions too.
  • Output: the results are written with part = 0 and a version above any speed-layer version. Rows from the speed layer with other parts for the same (ad, minute) are deleted or zeroed in the same operation, so the sum over parts is correct.
  • The job also writes the reconciliation record: totals from both layers, and the top drifting advertisers.
Deep Dive: a worked example of windows, lateness and correctionsShow

Follow ad 123 through one minute, 10:41:00–10:42:00, with a 20-second watermark delay, early results every 5 seconds, and 10 minutes of allowed lateness.

  • 10:41:05 (processing time): 40 clicks with event times in 10:41 have arrived. Flink emits (123, 10:41) = 40, version v1. The dashboard shows 40.
  • 10:41:30: 310 clicks. Emits 310, v2. The bar grows.
  • 10:42:00: 655 clicks, but the watermark is only at 10:41:40 (the latest event time minus 20 seconds), so the minute is still open. Emits 655, v3.
  • 10:42:20: the watermark passes 10:42:00. The window fires its final result: 671, v4. The dashboard marks 10:41 complete.
  • 10:44:10: a click from 10:41:58 arrives late, delayed by a consumer rebalance. It is within the allowed lateness, so Flink emits 672, v5, which overwrites v4.
  • 10:55:00: another click for 10:41 arrives. Allowed lateness has expired, so it goes to the side output and the clicks-late metric increments.
  • 11:30:00: the hourly recount for 10:00–11:00 runs over the lake, which has every raw click regardless of lateness. It finds 673 valid-looking clicks for the minute (the 672 above plus the very late one). Exact dedupe finds no duplicates the speed layer missed. The batch invalid-traffic model, which looks across many ads at once, flags 2 clicks from a ring of devices that clicked dozens of unrelated ads within seconds. Final: 671, written with a batch version, and the minute is marked final. The recorded drift is -1: plus 1 for the very late click, minus 2 for the invalid ones.

Why is this worth walking through in an interview? It shows that every number the advertiser sees has a version and a status (preliminary, complete, final), that corrections are overwrites, not increments, and that the final authority is the recount from raw data.

Deep Dive: variant, counting impressions tooShow

If the interviewer adds impressions ("advertisers want CTR"), the volume changes by about two orders of magnitude: with a CTR around 1%, 10k clicks/s at peak means about 1M impressions/s, about 10B per day.

  • Ingestion: impressions are usually logged by the ad server when it serves the ad, plus a client-side "viewable impression" beacon (the ad was actually on screen, under the industry's viewability standards: for display ads, at least half the ad's pixels visible for at least one second). The beacon endpoint is like the click endpoint, but it does not redirect, so it can be fire-and-forget (sendBeacon, 204 No Content).
  • Throughput: 1M events/s × 150 bytes = 150 MB/s into Kafka, 450 MB/s with replication. That is dozens of brokers and hundreds of partitions. It is a real cluster, but an ordinary one for large companies.
  • Pre-aggregation pays off even more. 10B impressions a day collapse into far fewer (ad, minute, dims) rows. Local pre-aggregation in the beacon collectors (count for one second, then send partials) can cut Kafka volume dramatically, at the cost of losing per-event raw data for those events. Usually raw impressions are still archived for audits, but sampled or compacted.
  • Joining clicks to impressions. CTR needs both counts, which is easy: they are separate counters in the same (ad, minute) row. Attribution, linking each click to its impression (to verify the click, compute time-to-click, or attribute conversions), is a stream join. Google's Photon paper (Ananthanarayanan and colleagues, "Photon: Fault-tolerant and Scalable Joining of Continuous Data Streams", SIGMOD 2013) describes joining ad clicks with the queries that produced them, at Google scale, exactly once, across data centres.
  • Dedupe for impressions is usually by impression id at the logging tier, and the tolerance for approximation is often higher, because impressions are billed per thousand and an error of a few per million is immaterial. Clicks are billed individually.
Deep Dive: what this costs, roughlyShow

Order-of-magnitude cloud costs for the base design (10k peak, 100M clicks per day), to show the design is not over-built. Prices vary a lot by provider and contract, so treat these as relative sizes, not quotes.

  • Click service: 10–20 small instances across three zones, the cheapest tier.
  • Kafka: 3–6 brokers (for zone redundancy, not throughput), with a few TB of disk. Often the biggest fixed cost at this scale, and a managed service trades money for operational effort.
  • Redis dedupe: a small cluster with about 10 GB of memory, plus replicas.
  • Flink: a handful of task managers, with SSDs for RocksDB state.
  • Lake: about 2 TB per year of Parquet in object storage, which costs very little per month.
  • OLAP: a small ClickHouse, Druid or Pinot cluster (3–6 nodes with replicas). Usually the second-biggest cost, driven by query concurrency rather than data size.
  • Batch recount: minutes of Spark per hour.

Where cost grows at 100× scale: Kafka brokers and cross-zone replication traffic (often billed per GB), Flink shuffle and state, and OLAP query compute. Typical savings: compact binary encoding (Avro or Protobuf instead of JSON roughly halves bytes), producer compression (zstd or lz4), local pre-aggregation before Kafka for impressions, tiered storage for long Kafka retention, and caching closed-period query results.

Deep Dive: the simpler path, plain Kafka consumers instead of FlinkShow

An interviewer may ask, "Can you do this without Flink?" Yes. Knowing what you would have to build yourself shows you understand what Flink provides.

A consumer group reads the clicks topic. Each consumer owns some partitions and keeps a hash map (ad, minute) → count in memory:

  1. For each click, increment the counter for its event-time minute.
  2. Every few seconds, write the cumulative counts for open minutes to the OLAP store (idempotent overwrite), then commit the Kafka offsets. The order matters: commit after the write. A crash between the two causes a re-read and re-write of the same cumulative values, which is harmless.
  3. Treat a minute as closed when the consumer's own "watermark" (the highest event time seen, minus a delay) passes its end. Write the final value and evict it from memory.

What you now own:

  • Rebalances. When a consumer dies, its partitions move to another consumer, which starts with an empty map. It must rebuild the counts for open minutes. So it either reads the current values back from the OLAP store and continues from the committed offset, or rewinds the offset to the start of the oldest open minute and recounts. The second is simpler and works because the windows are short.
  • Dedupe state. A 24-hour impression-id set per partition, kept in an embedded store (RocksDB) or in Redis. After a rebalance it must be restored, which is the hard part, and it is exactly what Flink's checkpointed keyed state does for you. Keying the topic by impression id would help dedupe but break per-ad counting, so you would need two consumer stages and an intermediate topic.
  • Watermarks across partitions, late data, idle partitions, and hot keys: all hand-built.

For 10k events per second this is all feasible, and Kafka Streams (a library for exactly this kind of consumer, with local state stores backed by changelog topics) gives you much of it. Flink is the choice when the state is large, the logic is rich, or exactly-once guarantees must be strong. Saying "I would start with Flink, but here is what it saves us" is a good answer.

Deep Dive: the batch-only version, MapReduce worked throughShow

Some interviewers want to see the batch version in detail, as the "good" baseline. Every 5 minutes (or every minute), a job runs over the new raw events.

  • Input: the files for the last interval in the event store or lake, about 3M events at peak (300 MB).
  • Map: each event becomes a key-value pair. The key is (ad_id, minute) (plus dimensions), and the value is 1. Duplicate removal by impression id is done first, as a group-by on impression id keeping the earliest row.
  • Combine: each mapper sums its own pairs per key before sending anything. A mapper that saw 5,000 clicks for one ad sends one pair, (ad, minute) → 5,000, instead of 5,000 pairs. This is the local pre-aggregation of Deep Dive 2.
  • Shuffle: pairs are routed by hash of the key, so all partial sums for one (ad, minute) meet at one reducer.
  • Reduce: each reducer sums the partials and writes the totals to the OLAP store.

Worked numbers. 3M events across, say, 30 map tasks is 100k events per task. With roughly 50k distinct (ad, minute) keys per batch, each mapper emits at most 50k pairs after combining, and usually far fewer. The shuffle moves at most 1.5M small pairs, a few tens of MB. Each reducer writes its share. Total job time is dominated by start-up and scheduling (tens of seconds), not computation, which is why batch cannot be pushed below a minute or so, and why streaming wins on freshness.

Window edges in batch. A batch that covers 10:40–10:45 by arrival time will miss clicks for 10:44 that arrive at 10:45:03. Either delay each batch (process events for 10:40–10:45 at 10:47, accepting more staleness) or let each batch re-aggregate the previous interval too, overwriting it. This is the batch version of watermarks and allowed lateness, and it shows that the streaming concepts exist in batch as well, only less visibly.

Deep Dive: observability, the numbers that tell you the pipeline is healthyShow

A data pipeline can be "up" while producing wrong or stale numbers. Monitor correctness and freshness, not just process health. See Observability: Logs, Metrics and Traces.

  • Click path: request rate, p50/p99 server latency for /click (alert above about 50 ms p99), error rate, the share of invalid tokens (a sudden rise suggests an attack or a key-rotation bug), the Redis duplicate-hit rate (normally a small, stable percentage), and the spill buffer size (should be zero).
  • Stream: produce error rate, under-replicated partitions, and broker disk.
  • Processing: consumer lag per partition (in records and in seconds), watermark lag (wall clock minus the current watermark, which is the true measure of how stale the final numbers are), checkpoint duration and failures, late-event rate, and per-task throughput, which reveals hot partitions.
  • Serving: query latency per shard, rows scanned per query, cache hit rate, and the OLAP store's merge backlog or part count.
  • Correctness: reconciliation drift per hour (total and for the top advertisers), the number of periods not yet final, and the age of the oldest non-final period.
  • End-to-end canary: a synthetic advertiser whose test ad is clicked by a probe at a known rate, say 10 clicks per minute. If the dashboard for that ad does not show 10 per minute, something is broken somewhere, even if every component's metrics look fine. This one check catches whole classes of silent failures.
Deep Dive: testing a counting pipelineShow

Counting bugs are silent. Nothing crashes, the numbers are just wrong. Tests must assert numbers.

  • Deterministic replays. Record a production-like hour of clicks (anonymised) and keep it as a fixture. Every change to the Flink job or the batch job is run against it, and the output must match the expected totals exactly.
  • Layer equivalence tests. Feed the same input to the streaming job and the batch job, and require identical outputs. This guards against the two codebases drifting apart, the main risk of a Lambda architecture.
  • Adversarial inputs. Duplicates (same impression id, same and different partitions, seconds and hours apart), out-of-order and late events, events exactly on minute boundaries, idle partitions, a salted hot key turned on mid-minute, clock skew between click-service hosts, forged and expired tokens.
  • Failure injection. Kill Flink task managers during a window, restore from a checkpoint and from an older savepoint, kill a Kafka broker, make Redis unavailable, and fill the click service's spill buffer. After each, the final counts must still be exact.
  • Property checks in production. The sum of minute counts for an hour must equal the hour row, clicks can never exceed impressions for the same ad (if both are counted), and counts for final periods do not change except through an audited correction.
Deep Dive: a 45-minute interview planShow
  • 0–5 min: clarify. Scale (10k/s peak, 10M ads), what is counted (clicks), granularity (1 minute), freshness, accuracy for billing, and whether dedupe is per impression.
  • 5–8 min: interface and data flow. Input: clicks. Output: metrics. Flow: click, record, redirect, aggregate, query. Quick numbers: 100M per day, 2 MB/s, dedupe state in GB.
  • 8–18 min: high-level design. Server-side redirect with 302. Reject the single-database design and explain why. Present batch (event store, Spark, OLAP), then streaming (Kafka, Flink, OLAP). Draw the full design with the archive and recount.
  • 18–38 min: deep dives (pick 3 or 4, or follow the interviewer). Scaling and hot ads (salting, pre-aggregation). Dedupe (signed impression ids, write-then-mark, exact Flink dedupe). No data loss (acks, retention, replay, the checkpoint question). Reconciliation (Lambda, drift, final versus preliminary). Fast queries (rollups, OLAP choice, timezones).
  • 38–43 min: failures and trade-offs. Walk two or three rows of the failure table aloud.
  • 43–45 min: wrap up. One sentence on what you would build first, and one on what you would add with more time (impressions, unique users with HLL, multi-region).
Deep Dive: real-world notesShow

Facts from published papers and well-documented systems; details of any company's current internal stack change over time.

  • Google described its advertising data infrastructure in several papers: Mesa (VLDB 2014), the geo-replicated warehouse storing ad metrics, with versioned batch updates and associative aggregation; Photon (SIGMOD 2013), joining ad clicks with search queries in real time, exactly once, across data centres; and MillWheel (VLDB 2013) and the Dataflow model (VLDB 2015), which shaped how the industry thinks about event time, watermarks and triggers. Apache Beam is the open-source descendant of the Dataflow model.
  • Apache Druid was created at Metamarkets for interactive analytics on advertising data, and its design (real-time ingestion, rollup, columnar segments, deep storage) maps directly to this problem.
  • Apache Pinot was created at LinkedIn for user-facing, low-latency analytics, and is used by other companies with similar needs (Uber has written about its use).
  • Twitter's Summingbird (VLDB 2014) tackled the Lambda architecture's two-codebases problem for real-time counting.
  • ClickHouse originated at Yandex for web analytics (Yandex.Metrica), a workload very similar to click aggregation: billions of events a day, aggregated into reports queried interactively.
Deep Dive: common follow-up questions, with short answersShow
  • "Why 302 and not 301?" Browsers may cache a 301, and the next click goes straight to the advertiser without passing through us. 302 (or 303 or 307) is not cached by default.
  • "What if the user clicks, but the advertiser page never loads?" The click was still a valid click on our side. Landing-page reachability is the advertiser's concern, though we may monitor destination URLs for errors and alert them.
  • "Can a click be counted before Flink sees it?" Only through the speed path. Budget pacing may count it from the raw stream within seconds. The dashboard sees it after Flink's next early firing, within about 5 seconds.
  • "What is the end-to-end freshness?" About 1–5 seconds for preliminary numbers (producer linger, consumer poll, early-firing interval, OLAP insert batch), about 20–40 seconds for a minute to be marked complete (watermark delay plus the window), and about an hour for final numbers.
  • "Why not write clicks to the OLAP store directly and aggregate there?" You can with Druid or Pinot (ingest raw from Kafka with rollup), as Deep Dive 6 discusses. Writing raw rows into ClickHouse and aggregating at query time also works at this volume, but every dashboard query then scans raw data, so add rollups anyway.
  • "How do you handle an advertiser with 100,000 ads?" Shard their data more finely, by (advertiser, campaign). Rely on campaign-level rollups for list views. Paginate ad-level queries.
  • "What if Redis loses the dedupe data?" Duplicates pass the first filter, Flink's keyed dedupe catches them, and the recount is the final authority. Redis is an optimisation, not the guarantee.
  • "What if the HMAC key leaks?" Rotate it. Verification accepts the current and the previous key during rotation, so ads already on screen keep working. Tokens signed with a revoked key are rejected after the overlap. Keep keys in a secrets manager, never in code.
  • "How would you add conversions?" As a separate event stream (pixel fires or server-to-server events from advertisers), joined to clicks by a click id that the redirect appended to the destination URL, within an attribution window (for example, 7 days). That is a stream-stream join with long-lived state, a design of its own.

Key Takeaways#

  • Start from the data flow. Input clicks, output metrics. Record, redirect, aggregate, query. Then grow the design one requirement at a time.
  • Never aggregate at read time what you can aggregate once at write time. Pre-aggregate per minute in a stream processor, roll up to hours and days, and query compact rows in a columnar OLAP store. See Pattern: Scaling Writes and Data Pipelines, Warehouses and Lakes.
  • Fast and correct come from two layers. A Flink speed layer gives preliminary numbers within seconds. An independent recount over an immutable raw archive gives final, billing-grade numbers. Measure the drift between them. See Batch vs Stream Processing and Apache Flink and Stream Processing.
  • Count once by design. Use a signed, per-impression id as the idempotency key, write before marking, dedupe exactly by impression id outside of windows, and make every write an overwrite of a cumulative, versioned value, not an increment. See Idempotency and Safe Retries.
  • Partition by the aggregation key, and plan for hot keys. Key by ad, salt hot ads, pre-aggregate locally, and merge hierarchically.
  • Never lose a click. Use a server-side redirect, acks=all with replicated, retained streams, a raw archive, and replay. Think before adding machinery: with 1-minute windows, replay can replace checkpoints for counts, while long-lived dedupe state still needs them.