{}DSA Atlas

Design an Ad Click Aggregator (real-time analytics)

Count billions of ad clicks per day per ad per minute for billing and dashboards — click ingestion and redirect, deduplication and fraud filtering, stream processing with event-time windows and watermarks, exactly-once aggregation, the OLAP store for queries, hot ads, lambda-style reconciliation with batch, and correctness for money-relevant data.

Advanced5 interview questions

1. Requirements

Functional

  • Users click ads → redirect to the advertiser's landing page.
  • Advertisers query click counts per ad over time ranges at minute granularity (and by dimensions: country, device, publisher).
  • Top N most-clicked ads in the last M minutes.
  • Billing-grade daily totals.

Non-functional

  • 10B clicks/day (≈ 115k/s avg, ~1M/s peak).
  • Query latency < 1 s for dashboards; data freshness ~1 minute.
  • Correctness: no double counting; exactly-once for billing; fraud filtered.
  • Fault tolerant; raw data retained for audits and recomputation.

2. Estimation

QuantityValue
Click events10B/day; ~200 B each → 2 TB/day raw
Active ads2M
Aggregates2M ads × 1,440 minutes = 2.9B rows/day before dimensions → roll up older data
Kafka~1M msgs/s peak → hundreds of partitions

3. High-level design

user click click server302 + log event Kafkaby ad_id Flinkdedupe · fraud rules1-min windows OLAP(ClickHouse) query API /dashboards raw archive(S3 / Iceberg) batch job(Spark, daily) reconcilecorrect → billing top-K(Redis) stream path = fresh, approximate-until-reconciled · batch path = authoritative for billing
Lambda-style: fast streaming aggregates plus batch recomputation from the immutable raw log.

4. Deep dives

Click redirect and event capture

The ad link points to https://click.ads.example/c?imp=<impression_id>&ad=…&sig=…. The click server verifies the signature (prevents forged parameters), logs the event to Kafka asynchronously (local buffer if Kafka is slow), and returns 302 to the landing page — the user's redirect must never wait on analytics.

Windowed aggregation

Java
DataStream<Click> clicks = env
    .fromSource(kafkaSource, WatermarkStrategy
        .<Click>forBoundedOutOfOrderness(Duration.ofSeconds(60))
        .withTimestampAssigner((c, ts) -> c.eventTimeMs()), "clicks");

clicks
    .keyBy(Click::clickId).process(new DedupeWithTtl(Duration.ofHours(24)))   // drop duplicate click IDs
    .filter(c -> !fraudRules.isInvalid(c))
    .keyBy(Click::adId)
    .window(TumblingEventTimeWindows.of(Duration.ofMinutes(1)))
    .allowedLateness(Duration.ofMinutes(5))
    .sideOutputLateData(lateTag)
    .aggregate(new CountAgg(), new EmitWindowResult())        // (ad_id, window_start, count)
    .sinkTo(clickhouseUpsertSink);                            // idempotent: key (ad_id, window_start)

Storage for queries

SQL
CREATE TABLE ad_clicks_minute (
  ad_id        UInt64,
  window_start DateTime,
  country      LowCardinality(String),
  device       LowCardinality(String),
  clicks       UInt64,
  version      UInt64
) ENGINE = ReplacingMergeTree(version)          -- re-emitted windows replace older versions
PARTITION BY toYYYYMMDD(window_start)
ORDER BY (ad_id, window_start, country, device);

-- clicks for an ad over a day, by hour
SELECT toStartOfHour(window_start) AS hour, sum(clicks)
FROM ad_clicks_minute FINAL
WHERE ad_id = 42 AND window_start >= '2026-10-07' AND window_start < '2026-10-08'
GROUP BY hour ORDER BY hour;

Roll up minute data to hourly/daily tables after a few days (materialised views) to bound storage.

Top-K most clicked ads

A second stream stage computes per-minute counts → sliding window top-K (heap per window) written to Redis for the "trending ads" dashboard; for many dimensions use count-min sketches (see probabilistic structures).

Reconciliation

Daily Spark job recomputes exact counts from the raw archive (with the same dedup and fraud logic, plus slower ML signals), compares with streaming aggregates, and writes the authoritative numbers used for invoices. Differences beyond a threshold raise alerts — they usually indicate a pipeline bug.

5. Trade-offs

DecisionChoice
ProcessingFlink event-time windows with watermarks
Semanticsdedupe by click ID + checkpointed state + idempotent sink = effectively exactly-once
Storecolumnar OLAP (ClickHouse/Druid/Pinot) for fast slice-and-dice
Hot adssalted two-stage aggregation
Correctness for moneybatch reconciliation from immutable raw data (lambda)
AlternativeKappa: single streaming pipeline, reprocess by replaying Kafka/Iceberg when logic changes

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.