Real-Time Ad Engagement Counting Pipeline and Advertiser Dashboard
System DesignModel answerLast updated
Design a pipeline that ingests millions of ad click events per second and serves near-real-time, windowed counts per ad to advertisers, with deduplication and late-data handling.
Scenario
You are building the measurement backbone of a large ad network. Every time a user clicks an ad, an event must be recorded, and advertisers need a dashboard that shows how their ads are performing almost immediately.
Event fields
Each click carries:
ad_iduser_idtimestampgeodevice_type
What the system must do
- Collect click events from clients.
- Roll up click counts per
ad_idinto 1-minute, 5-minute and 1-hour buckets. - Serve today's numbers to advertisers with query latency under 500 ms.
Constraints
- Peak load is 5 million clicks per second.
- At-least-once delivery is acceptable, but double-counting should be kept to a minimum.
- Dashboard values should lag reality by only a few seconds.
- History must be kept for at least 90 days for reporting.
What to cover in your answer
- A text description of the high-level architecture.
- The data model for the event stream and for the storage layers.
- How you absorb the write volume and partition the data, including what happens with very popular ads.
- How you deal with late or out-of-order events.
- Any trade-offs you are making, and how you would verify that the counts are correct.
Hints
Hint 1
Do the arithmetic first: events per second times bytes per event gives bandwidth and daily volume. This tells you raw events belong in cheap storage and dashboards must read pre-aggregated rows.
Hint 2
Duplicates come from retries under at-least-once delivery. Think about an identifier created once at the edge and a bounded-memory way to remember recently seen identifiers.
Hint 3
Separate event time from arrival time. Consider watermarks, a bounded lateness window that updates earlier results by overwriting rather than adding, and a batch job that recomputes buckets from raw data for very late arrivals.
Hint 4
One viral ad can overload the partition that owns it. Consider splitting its key across several sub-keys, aggregating partially, then merging.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing
Assume about 200 bytes per event, a 5M/s peak and roughly 1.5M/s average.
| Quantity | Estimate |
|---|---|
| Peak ingest bandwidth | 5M x 200 B = ~1 GB/s |
| Raw per day | ~130B events, ~26 TB |
| After columnar compression (~5x) | ~5 TB/day |
| 90 days of raw data | ~450 TB in object storage |
| Minute-level aggregate rows | ~1-2B/day realistically (sparse), up to ~14B worst case |
Two conclusions follow. Raw events go to cheap object storage, and the dashboard never touches raw data; it reads pre-aggregated rows only. CTR also needs impressions, which I would send through the same pipeline as a parallel stream and combine at the aggregate level.
2. Interfaces
- Click endpoint:
GET /click?ad_id&imp_id&sigreturns a redirect to the landing page and emits the event asynchronously. The server stamps aclick_id(UUID, or a hash of impression id and time) and an event timestamp. Theclick_idis the idempotency key; the signature blocks forged clicks. - Query endpoint:
GET /v1/ads/{ad_id}/metrics?start&end&granularity=1m|5m|1h&group_by=geo,device.
3. Data model
Stream event (Protobuf/Avro, keyed by ad_id): click_id, ad_id, user_id, event_ts, ingest_ts, geo, device, plus IP and user agent for fraud checks.
Serving table (Druid, Pinot or ClickHouse): primary key (ad_id, window_start, geo, device) with clicks, impressions. Keep 1-minute rows ~7 days; keep hourly and daily rollups 90+ days. The 5-minute and hourly views are rollups of the 1-minute grain.
Cold storage (Parquet on object storage, Iceberg/Hive), partitioned by date and hour. This is the source of truth for audits and recomputation.
4. Architecture
Clients -> load balancer -> stateless click servers
-> Kafka "clicks" (keyed by ad_id, RF=3, acks=all)
|-> Flink: dedup -> fraud filter -> event-time windowed aggregation
| -> OLAP store <- query service (+ short-TTL cache) <- dashboard
|-> sink to object storage (raw Parquet)
-> Spark batch: recompute aggregates, overwrite OLAP segments
The streaming path gives freshness; the batch path gives eventual exactness. Billing depends on these counts, so a correction path is essential.
5. Handling the write volume
- Click servers batch and compress before producing (a few ms of linger, lz4). If Kafka is unreachable they spool to local disk.
- Kafka: 1 GB/s at roughly 10 MB/s per partition needs at least ~100 partitions; use 1-2k for headroom and consumer parallelism.
- Partition by
ad_idso each ad's state lives on one task and no cross-node merging is needed. - Hot ads: salt the key (
ad_id+ hash ofclick_idmod N), pre-aggregate per salt, then re-key byad_idand merge partial counts. Local or mini-batch aggregation inside Flink cuts state updates dramatically. - The OLAP store receives one row per (ad, minute, geo, device) instead of one per click, reducing writes from millions per second to tens of thousands.
6. Deduplication
Retries cause duplicates. In Flink, key by click_id and keep a seen-set in RocksDB-backed state with a 10-30 minute TTL. At ~100M clicks per 10 minutes and ~16 bytes per id, that is a few GB spread across the cluster. Duplicates that arrive after the TTL are removed by batch reconciliation against raw data.
7. Late and out-of-order events
- Window on event time, using 1-minute tumbling windows.
- Watermark = max observed event time minus ~10 s. Windows fire when the watermark passes, which satisfies "within a few seconds".
- Allowed lateness (say 10 minutes): late events re-fire the window with a corrected total. The sink upserts on the primary key, so the row is replaced rather than incremented, which avoids double-counting.
- Very late events (offline devices, hours late) go to a side output and to object storage. The hourly or daily batch job recomputes the affected buckets and overwrites those segments.
- Clamp or reject timestamps far in the future relative to
ingest_tsto defend against clock skew.
8. Query path
Queries always filter on ad_id, enabling partition or segment pruning. Today's data comes from real-time segments, older data from rollups. A Redis cache with a 5-10 s TTL absorbs repeated dashboard refreshes. This comfortably meets 500 ms.
9. Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Stream + batch reconciliation | Fresh and eventually exact | Two code paths; share logic or run Flink in batch mode |
| Longer watermark delay | Fewer revisions | More staleness |
Partition by ad_id | Local aggregation | Hot keys need salting |
| Pre-aggregating by geo/device | Fast, cheap queries | No arbitrary dimensions on the real-time path |
10. Common mistakes
- Skipping the sizing and proposing per-click writes to a database.
- Saying "use Kafka" without a concrete dedup key or event-time semantics.
- Using arrival time for windows, so late data lands in the wrong bucket.
- Incrementing counters on late updates instead of upserting recomputed values.
- Ignoring hot keys.
- Having no reconciliation path, even though billing relies on the numbers.
11. Follow-ups worth preparing
- Fraud filtering: cheap inline checks (signature, rate limits per IP/user) in the stream, heavier model-based scoring asynchronously, with invalid clicks subtracted by the batch job.
- Monitoring: compare stream totals with batch totals per hour and alert on drift; track consumer lag and watermark delay.
- Backfills and replays: because raw data is retained and aggregates are idempotent upserts, a bug fix can be replayed safely.