Real-Time Ad Click Deduplication System
System DesignModel answerLast updated
Design a distributed system that ingests millions of ad clicks per second, eliminates duplicate events, and provides accurate near-real-time counts.
Problem
You need to architect a system that tracks advertising clicks at massive scale. The platform must ingest click events from users worldwide, remove duplicates reliably, and expose accurate aggregated counts with low latency for analytics dashboards.
Core Requirements
Functional Goals:
- Accept click events containing ad identifiers and user identifiers
- Eliminate duplicate clicks (both network retries and actual repeated user actions)
- Serve queries that return total clicks for any ad within the past hour
- Maintain data durability and counting accuracy
Scale and Performance:
- Process 10 million click events per second globally
- Acknowledge ingested events within 50 milliseconds
- Reflect new clicks in query results within a few seconds
- Handle duplicate detection correctly even during failures and retries
Expected Coverage
Your design should address:
- Interface contracts: What APIs do clients call to report clicks? What does the query endpoint return?
- Architecture: Trace the journey of a click event from arrival through storage, naming major components
- Duplicate handling: Explain your strategy for identifying and filtering both retry-based and user-based duplicates, including where deduplication state lives
- Scaling approach: How do you partition and distribute work to handle the throughput? How does the system remain available under component failures?
Hints
Hint 1
Think about the difference between a client retrying the same network request versus a user genuinely clicking twice—they require different treatment
Hint 2
Storing deduplication state locally within stream processors rather than in a remote cache can dramatically improve throughput
Hint 3
Use idempotent write patterns in your aggregation storage so that replaying events after a failure doesn't corrupt counts
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Ad Click Deduplication System
This problem tests your ability to reason about consistency and correctness in high-throughput distributed systems. The core challenge isn't raw throughput—it's ensuring accuracy when events are replayed, clients retry, and users click repeatedly.
1. Clarifications and Capacity Estimates
Start by distinguishing two flavors of duplication:
- Network-level duplicates: The exact same click event delivered multiple times due to client retries, load balancer replays, or message broker redelivery. These share a unique event identifier.
- Behavioral duplicates: A user clicking the same ad multiple times within a short period (e.g., 60 seconds). Each click has a distinct event ID but should only count once.
Both must be handled. Confirm the deduplication window—typically 60 seconds for behavioral duplicates keeps state manageable.
Capacity planning:
- Ingestion bandwidth: 10M events/sec × ~200 bytes ≈ 2 GB/sec sustained, ~170 TB/day
- Message queue partitioning: At 5–10 MB/sec per partition, you'll need 400–800+ partitions
- Deduplication state (60s window): 10M/sec × 60s = 600M active keys × ~64 bytes ≈ 38 GB total (sharded across processors)
- Aggregation cardinality: If tracking 10 million active ads with per-minute granularity, you produce ~10M aggregate updates per minute (far fewer in practice due to skew)
2. API Design
Ingestion endpoint (called from SDKs or click-redirect handlers):
POST /api/v1/clicks
Content-Type: application/json
{
"event_id": "01HZQK3M7XJQW8R2YPVN4C6D9F", // client-generated, stable across retries
"ad_id": "ad_47291",
"user_id": "usr_8832", // could be cookie/device ID
"impression_token": "eyJ0eXAi...", // cryptographically signed proof of ad impression
"timestamp": 1735689600000
}
Response: 202 Accepted
- Return 202 Accepted once durably written to the message broker—don't wait for aggregation
- The event_id serves as the idempotency key; clients generate it once and reuse on retry
- The impression_token is validated to prevent fraud (clicks without prior ad impressions are rejected)
For click-through redirects: GET /c?token=...&eid=... logs the event and returns 302 to the destination URL.
Query endpoint:
GET /api/v1/ads/{ad_id}/clicks?window=3600
Response:
{
"ad_id": "ad_47291",
"count": 15847,
"window_seconds": 3600,
"timestamp": 1735689623
}
3. System Architecture
User clicks → Edge ingestion service (stateless, regional)
↓
Kafka topic "raw_clicks" (partitioned by hash(user_id, ad_id))
↓
Stream processor (Flink/Kafka Streams) with keyed state
- Validate impression tokens
- Dedup by event_id (network duplicates)
- Dedup by (user, ad, time window) (behavioral duplicates)
- Pre-aggregate to (ad_id, minute_bucket) → count
↓
Kafka topic "aggregated_counts" OR direct sink
↓
Serving database (Cassandra/ScyllaDB)
- Schema: PRIMARY KEY (ad_id, minute_bucket)
- TTL: 2–7 days
↓
Query API (with 1-second cache for hot ads)
|
└→ Sum 60 minute buckets for 1-hour window
Side path: Raw events → Object storage (S3) → Batch reconciliation (nightly)
Key decisions:
- Stateless ingestion tier: Autoscales regionally, writes to Kafka with idempotent producer (
enable.idempotence=true,acks=all) - Partition key:
hash(user_id, ad_id)ensures all clicks from one user on one ad land on the same partition, enabling local deduplication - Storage schema:
ad_clicks_minute(ad_id, minute_bucket, count)with TTL. One-hour queries read 60 small rows from a single partition.
4. Deduplication Strategy
Where to maintain state:
Place deduplication state locally within the stream processor (e.g., Flink's RocksDB-backed keyed state, checkpointed to object storage).
- Why not remote cache (Redis)? At 10M ops/sec, every dedup check becomes a network call—adding latency, requiring massive Redis capacity, and risking lost keys during failover.
- Why local state? Lookups are in-memory/local-disk speed. State snapshots are coordinated with message broker offsets, guaranteeing exactly-once semantics on recovery.
Deduplication logic per key (user_id, ad_id):
State maintained:
- last_click_timestamp: long
- recent_event_ids: set<string> with 60s expiration
On event arrival:
1. If event_id in recent_event_ids → drop (network duplicate)
2. If (current_time - last_click_timestamp) < 60s → drop (behavioral duplicate)
3. Otherwise:
- Update last_click_timestamp = event.timestamp
- Add event_id to recent_event_ids
- Emit aggregation update: (ad_id, floor(timestamp / 60000), +1)
- Use event-time processing with watermarks (bounded lateness ~30s) to handle out-of-order arrival
- Apply state TTL matching the dedup window to prevent unbounded growth
5. Aggregation and Serving
Two-level aggregation for hot ads:
- After deduplication, events are still scattered by
(user, ad)key—good for parallelism - Each processor subtask pre-aggregates
(ad_id, minute_bucket) → partial_countin local state, flushing every 1–2 seconds - A second stage re-keys by
ad_idalone and merges partials into final per-minute counts - This reduces a viral ad's millions of events/sec into thousands of aggregate updates/sec
Idempotent writes:
The sink writes the absolute count for each (ad_id, minute_bucket) as an upsert, not a delta increment. If a stream task fails and replays from a checkpoint, it rewrites the same final value—achieving exactly-once semantics at the storage layer.
Query path:
Sum the counts across 60 minute buckets (or 61 to include the partial current minute). Cache results for ~1 second for frequently queried ads.
6. Fault Tolerance and Scaling
Handling failures:
- Message broker (Kafka) node failure: Covered by replication factor 3 and in-sync replica handling
- Stream processor task failure: Restore from last checkpoint (every 10–30s), replay events from checkpointed offsets. Local state is rebuilt from the checkpoint snapshot.
- Database node failure: Cassandra's quorum writes (RF=3, W=2) tolerate single-node loss
Geographic distribution:
Deploy regionally: each region runs its own ingestion tier, message broker, and stream processors. Minute-level aggregates either:
- Replicate to a global database (active-active)
- Remain regional, with the query layer federating across regions
GeoDNS pins users to regions, making cross-region behavioral duplicates rare. Any remaining discrepancies are caught by batch reconciliation.
Accuracy backstop:
A nightly batch job recomputes counts from archived raw events (stored in S3/HDFS) and reconciles with the real-time path. The batch result is the source of truth for billing; the streaming path is optimized for dashboard freshness.
7. Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Local processor state vs. remote cache | Sub-millisecond dedup, exactly-once on recovery | State is tied to partition assignment; rescaling requires rebalancing |
| Partition by (user, ad) | Perfect dedup locality | Hot ads still need two-stage aggregation to avoid skew |
| Minute-bucket granularity | Compact storage, fast 1-hour queries | Slight delay quantization (clicks near bucket boundaries) |
| Batch reconciliation | Guarantees billing accuracy, catches bugs | Adds operational complexity |
Common mistakes:
- Using event-ID dedup alone (misses behavioral duplicates)
- Putting dedup state in a remote cache without considering throughput and consistency
- Writing deltas (
+1) instead of absolute counts, breaking idempotence - Ignoring late-arriving events or not handling out-of-order delivery
This design balances high throughput, low latency, and strong accuracy by carefully choosing where state lives and ensuring every stage is idempotent.