Case Study 33 โ€” Ad Click / Impression Aggregation

Design a real-time ad analytics pipeline like Google Ads reporting or Meta Ads Insights at billions of impressions and clicks per day: ingest high-volume events, deduplicate, aggregate in time windows, detect fraud, and serve billing-grade rollups to advertisers and auction systems.

1. Problem

When users view or click ads, the system emits events:

  • impression { adId, campaignId, userId, timestamp, placement, bidId }
  • click { adId, clickId, userId, timestamp, referrer }

Advertisers need:

  • Counts per campaign/ad/creative per hour and day
  • Unique users (reach) and CTR
  • Near-real-time dashboards (minutes lag)
  • Billing based on verified impressions/clicks

Challenges: extreme volume, duplicate events (retries, client bugs), late arrivals, bot/fraud traffic, and exactly-once billing semantics (or strong idempotent approximations).

2. Requirements

Functional (MVP)

  • Ingest impression and click events from ad servers and pixels
  • Dedupe by (eventType, eventId) or composite key
  • Rolling aggregates: counts per (campaignId, hour) and (adId, day)
  • Unique user estimates per campaign (HyperLogLog acceptable for reach)
  • Fraud signals: IP velocity, device fingerprint anomalies โ†’ flag or drop
  • Query API: campaign stats for date range; real-time last-hour counters
  • Export to data warehouse for billing reconciliation

Out of scope (initially)

  • Attribution modeling (multi-touch, view-through conversion windows)
  • ML bid optimization feedback loop (only raw features export)
  • Sub-second alerting on spend caps (near-real-time minute granularity OK)
  • Per-user cross-device identity graph

Non-functional

  • Ingest: 500Kโ€“2M events/sec peak globally
  • Ingestion ack p99 < 50 ms (async pipeline after ack)
  • Aggregation lag: < 5 minutes for dashboards; daily billing by T+1
  • Durability: no silent loss โ€” at-least-once ingest + idempotent agg
  • Accuracy: billed clicks within 0.01% of audited reconciliation
  • Cost-efficient: tier hot vs cold; compress raw events

3. Back-of-the-envelope

These numbers are rough order-of-magnitude math โ€” not a Google Ads billing spec. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ‰ˆ 86,400 requests/day (86,400 seconds in a day). Ad pipelines are extreme ingest volume with dedup accuracy requirements โ€” peak is often 3โ€“5ร— average during prime-time browsing.

Why we estimate

Ad click/impression aggregation sits between firehose ingestion and billing-grade accuracy. Estimates tell us:

  • Whether ingest ack latency or dedup store size is the real bottleneck
  • If we need a durable log first (never block ingestion on aggregation)
  • How to split fast counters (Redis, minutes lag) from authoritative OLAP (ClickHouse, T+1 billing)

Assumptions

AssumptionValueWhy it matters
Impressions/day10BDominates event volume (~98% of events)
Clicks/day200M2% CTR โ€” still huge; billing-critical
Avg event size400 BJSON with adId, campaignId, userId, timestamps
Peak multiplier5ร— averageEvening prime time, holiday campaigns
Regions3Partition dedup and aggregation
Dedup window24 hoursRetries and client bugs replay same eventId
Active ads100KDrives rollup row count

Step A โ€” Traffic (QPS / throughput) with labeled arithmetic

Impression rate:

Impressions/day   = 10,000,000,000
Avg impression QPS = 10B รท 86,400
                   โ‰ˆ 115,700 impressions/second

Click rate:

Clicks/day        = 200,000,000
Avg click QPS     = 200M รท 86,400
                  โ‰ˆ 2,300 clicks/second

Combined ingest (impressions + clicks):

Combined avg QPS  = 115,700 + 2,300
                  โ‰ˆ 118,000 events/second

Peak ingest QPS   = 118,000 ร— 5
                  โ‰ˆ 590,000 events/second

Per-region peak (3 regions, uneven load):

If US carries 50% of traffic:
  US peak โ‰ˆ 295,000 events/s
  โ†’ Each region needs independent ingest + dedup partition

Step B โ€” Storage

Daily raw event volume (before compression):

Total events/day  = 10B impressions + 200M clicks โ‰ˆ 10.2B events
Bytes per event   = 400 B

Raw/day           = 10.2B ร— 400 B โ‰ˆ 4 TB/day uncompressed
Compressed (~5ร—)  โ‰ˆ 800 GB/day in object storage (cold tier)

Dedup store (24-hour TTL โ€” must fit in fast storage):

Event IDs in 24h  = 10.2B unique eventIds
Hash per ID       = 16 B (UUID or composite hash)

Dedup memory      = 10.2B ร— 16 B โ‰ˆ 163 GB
  โ†’ Redis Cluster or DynamoDB with TTL partitioned by hour
  โ†’ Cannot use a single Redis node; shard by eventId hash

Hourly rollup rows (OLAP โ€” manageable):

100K active ads ร— 24 hours ร— 30 days โ‰ˆ 72M rows/month
  โ†’ ClickHouse / BigQuery territory, not the ingest bottleneck

Unique user reach (HyperLogLog โ€” approximate):

~12 KB per campaign per day ร— 10K campaigns โ‰ˆ 120 MB/day
  โ†’ Exact distinct counts at 10B/day are prohibitively expensive

Step C โ€” Bandwidth / other

Ingest bandwidth (peak):

590,000 events/s ร— 400 B โ‰ˆ 236 MB/s peak ingest
  โ†’ HTTP/gRPC from ad servers and click pixels across 3 regions
  โ†’ Ack within 50 ms p99; processing is async after ack

Aggregation lag budget:

Dashboard counters  โ†’ < 5 minutes lag (stream processors โ†’ Redis)
Billing rollups     โ†’ T+1 authoritative (OLAP reconciliation)
  โ†’ Two tiers: fast approximate vs slow exact

Step D โ€” Ratios and capacity table

MetricAveragePeakNotes
Impression QPS~115,700/s~578,500/s~98% of ingest volume
Click QPS~2,300/s~11,500/sBilling-critical โ€” dedup mandatory
Impression:click ratio~50:1~50:12% CTR
Raw storage/day~4 TBโ€”~800 GB compressed
Dedup store (24h)~163 GBโ€”Sharded TTL store
Rollup rows/month~72Mโ€”OLAP, not hot path

What the numbers tell us

  • ~118K events/s average, ~590K/s peak โ†’ durable log first (Kafka/Kinesis); never block ingest on aggregation
  • Impressions dominate 50:1 over clicks โ†’ optimize impression path; clicks get stricter dedup and audit
  • 163 GB dedup store for 24h โ†’ partition by hour + TTL; Redis Cluster, not one node
  • 4 TB/day raw โ†’ tier hot (hours) vs cold (months); compress before object storage
  • 72M rollup rows/month is manageable โ†’ separate fast counters (Redis) from authoritative OLAP
  • Billing accuracy 0.01% โ†’ idempotent aggregation keyed by (eventType, eventId); at-least-once ingest is OK if dedup is correct

Common mistake for this problem

Blocking ingestion on aggregation โ€” trying to update campaign counters synchronously before returning HTTP 200. Interviewers want: ack fast โ†’ durable log โ†’ async stream processor โ†’ idempotent dedup + windowed aggregation. Another mistake: using exact distinct user counts at 10B events/day โ€” HyperLogLog or sampled sketches are the pragmatic choice for reach metrics.

4. High-Level Design (HLD)

Components

ComponentRole
Ingestion APIStateless; validate; partition by campaignId or adId
KafkaDurable buffer; separate topics for raw vs clean
Dedup processorFlink/Streams; TTL store keyed by eventId
EnrichmentJoin geo, device, campaign metadata (async broadcast state)
Window aggregatorTumbling/sliding windows; emit partial + final results
Fraud scorerRules + ML; route suspicious events to quarantine topic
RedisSub-minute live counters for dashboards
ClickHouseAuthoritative hourly/daily aggregates; fast SQL
Data lakeParquet for audit replay and billing reconciliation
Query APIMerges Redis (live) + ClickHouse (historical)
Billing reconcilerBatch job compares OLAP vs finance ledger

Flows

Impression path

  1. Ad server fires impression with unique impressionId
  2. Ingestion validates, adds receivedAt, produces to Kafka
  3. Dedup: if impressionId seen in 24h โ†’ drop
  4. Enrich with campaign/advertiser from cache
  5. Aggregate into 1-min window โ†’ increment Redis
  6. On window close โ†’ upsert ClickHouse impressions_hourly

Click path (billing-sensitive)

  1. Pixel sends click with clickId (UUID from redirect)
  2. Dedup strictly on clickId โ€” duplicates from retry must not double-count
  3. Fraud check: IP > 10 clicks/min โ†’ tag suspicious
  4. Clean clicks increment counters; suspicious go to quarantine for review
  5. Daily job produces billable_clicks excluding quarantined

Late events

  1. Hourly window with allowed lateness 2 hours (configurable)
  2. Late event triggers retraction + correction or side-output to correction stream
  3. Billing uses closed day only after lateness window passes

Trade-offs

  • Exact dedup vs Bloom filter โ€” Exact TTL store (DynamoDB/Redis) for billing; Bloom OK for non-billing metrics
  • HyperLogLog vs exact unique โ€” HLL for reach dashboards; exact sets only for small campaigns
  • Lambda vs Kappa โ€” Single stream pipeline (Kappa) with replay from lake for backfill
  • At-least-once + idempotent agg vs exactly-once Flink โ€” Idempotent upserts simpler ops; EOS Flink reduces correction complexity
  • Sync fraud vs async โ€” Async quarantine avoids blocking hot path; pre-bill filter for obvious bots

5. Low-Level Design (LLD)

APIs

POST /v1/events/impression
Body: {
  "impressionId": "imp-uuid-...",
  "adId": "ad_4421",
  "campaignId": "camp_88",
  "userId": "u_hash_abc",
  "timestamp": "2026-07-20T10:00:01.123Z",
  "placement": "feed",
  "bidId": "bid_991"
}
โ†’ 204 No Content

POST /v1/events/click
Body: {
  "clickId": "clk-uuid-...",
  "impressionId": "imp-uuid-...",
  "adId": "ad_4421",
  "userId": "u_hash_abc",
  "timestamp": "2026-07-20T10:00:05.456Z"
}
โ†’ 204

GET /v1/stats/campaigns/:id?from=2026-07-19&to=2026-07-20
โ†’ {
  "impressions": 12450000,
  "clicks": 249000,
  "ctr": 0.02,
  "uniqueUsersEstimate": 8200000,
  "billableClicks": 248500
}

GET /v1/stats/campaigns/:id/live
โ†’ { "lastHour": { "impressions": 52000, "clicks": 1040 }, "asOf": "..." }

Internal aggregation key:

aggKey = hash(campaignId, adId, windowStart, eventType)

Schema

ClickHouse (authoritative rollups):

impressions_hourly (
  campaign_id   UInt64,
  ad_id         UInt64,
  hour          DateTime,
  impressions   UInt64,
  unique_users  AggregateFunction(uniqCombined, userId),
  version       UInt64              -- for ReplacingMergeTree
)
ENGINE = ReplacingMergeTree(version)
PARTITION BY toYYYYMM(hour)
ORDER BY (campaign_id, ad_id, hour)

clicks_hourly (
  campaign_id     UInt64,
  ad_id           UInt64,
  hour            DateTime,
  clicks          UInt64,
  billable_clicks UInt64,
  fraud_clicks    UInt64,
  version         UInt64
)

clicks_daily_billing (
  campaign_id     UInt64,
  day             Date,
  billable_clicks UInt64,
  amount_micros   Int64,
  reconciled      Boolean
)

Dedup store (DynamoDB / Redis):

dedup (
  pk = eventType#eventId,
  ttl = epoch + 86400
)

Raw lake (Parquet):

s3://ads-events/year=2026/month=07/day=20/hour=10/
  part-000.parquet  -- all fields + ingestMeta

Fraud quarantine:

fraud_events (
  event_id, reason_code, score, payload_json, created_at
)

Modules

IngestionController
EventValidator
SchemaRegistryClient
KafkaProducer
DedupFunction                 (Flink ProcessFunction)
EnrichmentBroadcastJoin
WindowAggregator
LateEventHandler
FraudRuleEngine
RedisCounterSink
ClickHouseSink
QueryService
BillingReconciler
BackfillJob

Algorithm โ€” ingestion with partition key

function ingest(event):
  validateSchema(event)
  if event.timestamp skew > 7 days: reject

  key = hash(event.campaignId) mod numPartitions
  kafka.produce(
    topic = event.type,
    key = key,
    value = event,
    headers = { receivedAt: now() }
  )
  return 204

Algorithm โ€” exact dedup (24h TTL)

function dedup(event):
  pk = event.type + "#" + event.eventId

  // atomic set-if-not-exists with TTL
  isNew = dedupStore.setNX(pk, "1", ttl=86400)

  if not isNew:
    metrics.increment("dedup_dropped")
    return DROP

  return EMIT(event)

State backend (Flink): ValueState<Boolean> keyed by eventId with TTL 24h โ€” same semantics.

Algorithm โ€” tumbling window aggregation with allowed lateness

function aggregateByWindow(event, windowSize=1 hour, allowedLateness=2 hours):
  eventTime = parseTimestamp(event.timestamp)
  windowStart = floor(eventTime, windowSize)

  onElement(event):
    if eventTime < currentWatermark - allowedLateness:
      sideOutput(LATE_CORRECTIONS, event)
      return

    acc = state.get(windowStart, aggKey)
    acc.count += 1
    acc.userHLL.add(event.userId)
    state.put(windowStart, aggKey, acc)

  onWatermark(watermark):
    for window where windowEnd + allowedLateness <= watermark:
      emitFinal(window)
      state.clear(window)

Algorithm โ€” idempotent ClickHouse upsert

function emitFinal(window, aggKey, acc):
  row = {
    campaign_id, ad_id, hour: windowStart,
    impressions: acc.count,
    unique_users: acc.userHLL,
    version: windowStart.epoch + acc.count   // monotonic for ReplacingMergeTree
  }
  clickhouse.insert("impressions_hourly", row)

// Query uses FINAL or argMax by version for correct merge

Algorithm โ€” fraud scoring (rules + rate limit)

function scoreClick(event):
  score = 0
  ipKey = "ip:" + event.ip + ":min:" + floor(now, 60s)
  ipCount = redis.incr(ipKey, ttl=60)
  if ipCount > 10: score += 50

  if event.userAgent matches BOT_PATTERNS: score += 40
  if geoMismatch(event.ipGeo, event.deviceGeo): score += 30
  if duplicateClickSameUserAd(event, window=10s): score += 60

  if score >= 70:
    return QUARANTINE
  if score >= 40:
    return SUSPICIOUS_BUT_COUNT  // or exclude from billing only
  return CLEAN

Algorithm โ€” billing reconciliation (T+1)

function reconcileDay(day):
  olap = clickhouse.query("""
    SELECT campaign_id, sum(billable_clicks)
    FROM clicks_daily_billing FINAL
    WHERE day = ?
  """, day)

  for row in olap:
    ledger = finance.getBilled(row.campaign_id, day)
    if abs(row.clicks - ledger.clicks) / ledger.clicks > 0.0001:
      alert("billing drift", row)
      replayFromLake(day, row.campaign_id)   // audit trail

Algorithm โ€” query merge (live + historical)

function getCampaignStats(campaignId, from, to):
  historical = clickhouse.sum(campaignId, from, to)
  if to includes current hour:
    live = redis.mget(campaignId, currentHourBuckets)
    return merge(historical, live)
  return historical

Concurrency & correctness

  • Idempotent dedup โ€” same eventId always maps to one counted event
  • Monotonic version on rollup rows โ€” ReplacingMergeTree resolves duplicates from replay
  • Watermark lag โ€” allowed lateness trades freshness vs correction cost
  • Partition by campaignId โ€” ordering per campaign; hot campaigns isolated
  • Billing cutoff โ€” day closes only after lateness window; immutable billing table
  • Replay safety โ€” backfill from lake must use same dedup keys or versioned upserts

Failure modes

FailureImpactMitigation
Kafka broker downIngestion backpressureMulti-AZ cluster; producer retries
Dedup store hot partitionSlow dedupShard by hash(eventId); not campaign
Flink checkpoint failReprocess windowIdempotent sinks; EOS or upsert
Redis lossLive dashboard wrongRebuild from Kafka; OLAP authoritative
Clock skew on clientsWrong windowUse server receivedAt for windowing
Fraud false positivesRevenue lossQuarantine not drop; human review queue
Duplicate billing jobDouble chargereconciled flag + idempotent job key

6. Scale evolution

StageChange
MVPKafka + Flink + ClickHouse + Redis; single region
100K events/sIncrease partitions; scale Flink parallelism = partitions
1M events/sRegional ingest; dedup store sharded (DynamoDB)
GlobalPer-region aggregation; merge at query with timezone rules
Billing hardeningExactly-once Flink + audit lake; finance-grade reconciliation
Real-time bidding feedbackSub-second feature store branch (separate from billing path)

7. Recap

  • Ingest fast, process async โ€” Kafka buffers spikes
  • Exact dedup on billing IDs; TTL aligned to retry window
  • Windowed aggregation with watermarks handles late data
  • Redis for live, ClickHouse for truth โ€” merge at query time
  • Fraud is a side path โ€” don't block ingestion; quarantine and reconcile

Practice: compute peak QPS and dedup store size for your own assumptions; draw the dedup โ†’ window โ†’ sink pipeline and write pseudocode for dedup + hourly emitFinal with allowed lateness.