Billing-Grade Click Event Pipeline at 10M Events per Second
System DesignModel answerLast updated
Design a pipeline that records ad clicks at extreme scale, drops repeat clicks within 30 seconds, serves windowed counts per ad, and never loses billable data.
Problem
An advertising platform needs a backend that captures every click on every ad. Peak traffic reaches 10 million clicks per second. Recording a click should feel near-instant (well under a second), while the numbers shown in dashboards and used for invoices may lag slightly behind reality (eventual consistency).
Click event
Each event carries:
(click_id, user_id, ad_id, timestamp, device_info)
What the system must do
- Ingest click events reliably.
- Answer queries for the number of clicks on a given
ad_idacross different time windows (for example per minute, hour, or day). - Suppress repeats: if the same user clicks the same ad several times within a 30-second window, only one click is counted.
Quality requirements
- Availability: traffic spikes must not cause events to be dropped.
- Scalability: sustain 10M clicks/s at peak.
- Correctness: billing figures must be accurate. Losing data is not acceptable.
What to cover in your answer
- A high-level architecture (entry points, queues, processing services, storage, query path).
- The data model, separating raw events from aggregated metrics.
- How you partition and shard data so that a single viral ad does not create a hotspot.
- How you cope with failures in downstream components, and where you can realistically offer exactly-once behavior.
- Your technology and pattern choices (for example NoSQL vs. time-series/OLAP stores, streaming vs. batch) and the trade-offs behind them.
State any assumptions you make about freshness, query shapes, and late or out-of-order events.
Hints
Hint 1
Separate two kinds of duplicates: the same click_id delivered twice by retries, and different clicks from one user on one ad within 30 seconds. Each needs its own mechanism, and the 30-second rule should be judged on event time.
Hint 2
Do the back-of-envelope math first (bytes per event, GB/s at peak, Kafka partitions, size of dedup state). Then pick a partition key that spreads load evenly and keeps one user's clicks together, so dedup stays local.
Hint 3
Aggregating by ad_id concentrates a viral ad on one worker. Think about pre-aggregating locally before the shuffle, salting hot keys, and idempotent upserts. For billing, keep an immutable raw log and recompute from it in batch.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify semantics and size the problem
Two kinds of duplicates
- Technical duplicates: the same
click_idre-sent because of client retries or broker redelivery. Always drop. - Behavioral duplicates: the same
(user_id, ad_id)within 30 seconds. A click counts only if no counted click for that pair occurred in the preceding 30 seconds of event time.
Freshness: dashboards may be about a minute stale. Invoices must be exact but can be finalized hourly or daily.
Rough numbers
| Quantity | Estimate |
|---|---|
| Peak ingest | 10M/s × ~200 B ≈ 2 GB/s |
| Raw volume | ~3M/s average ≈ 250B events/day ≈ 50 TB/day raw, ~10 TB compressed columnar |
| Kafka partitions | ~5-10 MB/s each, so at least 200-400; provision ~1,000 for headroom |
| Dedup state | at most ~300M live (user, ad) keys × ~40 B ≈ 12 GB, sharded across workers |
2. API
POST /v1/clickstakes a batch of events and returns202only after the batch is durably written to the log (acks=all). That acknowledgement is where the no-loss guarantee begins.GET /v1/ads/{ad_id}/clicks?start&end&granularityreturns[{bucket_start, raw_clicks, unique_clicks}].click_idis a UUID generated at the client or edge, so retries are idempotent.
3. Architecture
Clients -> CDN/Edge -> Stateless collectors (autoscaled)
-> Kafka "clicks-raw" (RF=3, min.insync.replicas=2, key=user_id)
|-> Archiver -> object store (Parquet, hourly partitions) [source of truth]
|-> Stream job: validate -> dedup -> local pre-agg -> final agg
-> Kafka "clicks-agg" -> OLAP store (Druid/Pinot)
Batch job (hourly/daily) over the lake -> reconciled billing table
Query service -> OLAP (dashboards) / warehouse (invoices)
- Collectors validate the schema, stamp an ingest time, and batch-produce to Kafka. If Kafka is degraded they spill to a local write-ahead log and replay.
- Kafka absorbs spikes, decouples producers from consumers, and with about 7 days of retention allows replay after a bug.
- Partitioning by
user_idgives even load (viral ads do not skew it) and co-locates one user's clicks, so the 30-second dedup is a local state lookup.
4. Data model
Raw events (append-only Parquet, partitioned by date/hour):
click_id, user_id, ad_id, advertiser_id, event_ts, ingest_ts, device_type, os, country, ip_hash, is_duplicate, dedup_reason
Keep duplicates but flag them. That keeps an audit trail and lets you recompute if the rules change.
Aggregates (OLAP): dimensions ad_id, advertiser_id, minute_bucket, device_type, country; metrics raw_clicks, unique_clicks. Time-partitioned segments make range queries cheap, and the engine rolls minutes up to hours and days.
Billing table: (advertiser_id, ad_id, hour, billable_clicks, version), written by the batch job and versioned so corrections are auditable.
5. Deep dives
Deduplication
Two stages in a stateful stream processor (Flink with RocksDB keyed state):
- By
click_id: keyed state with a TTL of a few minutes (the realistic retry horizon). A Bloom filter may sit in front to skip lookups, but a hit must be confirmed against exact state, since a false positive would drop a real click. - 30-second rule: key by
(user_id, ad_id)and storelast_counted_tswith a 30-60 s TTL. Ifevent_ts - last_counted_ts < 30s, mark as duplicate; otherwise count and update.
Use event time with watermarks (for example 10 s allowed lateness) so out-of-order events are judged correctly. Very late events are caught by the batch reconciliation.
Embedded state beats an external store such as Redis here: no network hop at 10M ops/s, and state is checkpointed atomically with source offsets. Async-replicated Redis can lose recent keys on failover and cause double counting.
Hot ads
Aggregation keyed by ad_id would funnel a viral ad onto one task. Use two-phase aggregation: each task pre-aggregates (ad_id, minute) locally for 1-5 s, then emits partials keyed by ad_id#salt (salt only for known-hot ads), and a final stage merges them. Millions of events per second become thousands of upserts per second.
Exactly-once and failure handling
- Idempotent producers plus
click_iddedup on the way in. - Checkpointed state and offsets, with transactional writes to
clicks-agg, so a crash rolls back cleanly. - Sink writes are upserts of full values keyed by
(ad_id, minute, dims), not increments, so retries are harmless. - If the OLAP store is down, Kafka buffers and the job backpressures. Data is delayed, not dropped.
- Billing reconciliation (Lambda-style): the stream path serves dashboards; a batch job recomputes dedup and counts from the immutable raw log, and its output feeds invoices. Differences above a threshold alert on-call.
- Multi-AZ deployment and cross-region mirroring of the raw topic for disaster recovery.
6. Trade-offs
| Decision | Choice | Rationale / alternative |
|---|---|---|
| Buffer | Kafka | Durable, replayable, partitioned; Kinesis or Pub/Sub on managed clouds |
| Processing | Stream plus batch | Stream alone can bake bugs into invoices; batch alone is hours late |
| Aggregate store | Druid/Pinot | Columnar, time-partitioned, fast group-bys; a key-value store is cheaper for fixed counters but poor for ad hoc filters |
| Dedup state | Embedded keyed state | Fast and consistent with offsets; costs more operationally than a cache |
7. Common mistakes
- Acknowledging the client before the write is replicated.
- Partitioning by
ad_id, which creates hot partitions for viral ads. - Using processing time for the 30-second rule, which breaks under delay and replay.
- Writing increments to the sink instead of idempotent upserts.
- Treating the streaming number as the invoice number with no reconciliation against the raw log.
- Ignoring clock skew and late data.