Exactly-Once Click Event Cleanup in a Streaming Lake Pipeline
System DesignModel answerLast updated
Design a Spark Structured Streaming job that removes retry-induced duplicate click events at 10M/s with a 24-hour window, handling late data, hot keys, idempotent writes, and backfills.
Scenario
An ad-tech platform collects click events from many trackers and pushes them into a message bus at roughly 10 million events per second. Every event carries:
event_id(a UUID)timestamp(set by the tracker)user_idpayload
Trackers retry on network failure, so the same event_id can show up more than once, each time with a different arrival time. You must build a Spark Structured Streaming job that removes these duplicates and writes the result to a table in an S3-based data lake.
Constraints
- Ingest volume: 10M events/second.
- The business requires duplicates to be eliminated across a 24-hour window.
- The pipeline must support backfilling historical data without creating duplicates of rows already in production.
What to cover
- A deduplication strategy keyed on
event_idthat stays performant at this scale. Include a rough sizing of the state involved. - How you treat late events that arrive after the deduplication window or watermark has already moved past them.
- How you deal with data skew, for example when certain
event_idprefixes (or specific IDs) are far more frequent than others. - How you make the sink idempotent, so that a retried or restarted Spark job does not insert duplicate rows in the destination.
Explain your trade-offs and name the pitfalls you would watch for.
Hints
Hint 1
Do the capacity math first: how many distinct event_ids exist in 24 hours, and roughly how many bytes of state does each one cost? Ask whether that fits in streaming state at all.
Hint 2
Consider two tiers: a cheap streaming dedup over a short watermark that catches almost all retries, plus a transactional insert-only check against the lake table for the long tail.
Hint 3
Think about what a random salt on the dedup key does to copies of the same event, and what truly causes skew when keys are UUIDs.
Hint 4
On a restart Spark replays the same batch with the same offsets. Ask what property the write needs so that a replay changes nothing, and how a backfill can reuse that same property.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
Three things: you do the capacity math before choosing a design, you know where Spark's exactly-once guarantees end, and you avoid tempting but wrong tricks (notably salting the dedup key).
1. Clarify, then size the problem
Questions to ask:
- Is
timestampidentical across retries? It is set by the tracker, so it should be. Only arrival time differs. - How fast do retries arrive? Typically the vast majority within minutes, with a long tail up to the 24h requirement.
- What does the source guarantee? Assume Kafka or Kinesis with at-least-once delivery.
- What latency does the lake tolerate? Assume minutes.
Sizing:
| Quantity | Estimate |
|---|---|
| Events per day | 10M x 86,400 = about 864 billion |
| State per key (UUID, timestamp, store overhead) | roughly 50-100 B |
| Exact 24h key set | roughly 40-85 TB |
Exact 24h dedup in streaming state, or in an in-memory store like Redis, is not realistic. Say that early and propose a tiered design.
2. Architecture
Trackers -> Kafka (keyed by event_id)
-> Spark Structured Streaming
Tier 1: validate -> short-window streaming dedup (RocksDB state)
Tier 2: foreachBatch insert-only MERGE into Iceberg/Delta
-> S3 table partitioned by event_hour, bucketed on event_id
Late and backfill data -> same MERGE writer, separate checkpoint
3. Deduplication (requirement 1)
Tier 1, in-stream and short window. Use the RocksDB state store with a watermark matched to the observed retry distribution, say 30-60 minutes. One hour is about 36B keys, a few TB of state, which a few hundred executors with local NVMe can hold.
deduped = (events
.withWatermark("event_time", "1 hour")
.dropDuplicatesWithinWatermark(["event_id"])) # Spark 3.5+
On older versions use dropDuplicates(["event_id", "event_time"]). This works because retries share the same event time, and having the event-time column in the key lets state expire. The classic mistake is dropDuplicates(["event_id"]) with no event-time column: state then grows forever.
Tier 2, lake-level and full 24h. In foreachBatch, run an insert-only merge:
MERGE INTO lake.events t
USING batch s
ON t.event_id = s.event_id
AND t.event_hour BETWEEN s.min_hour - INTERVAL 24 HOURS AND s.max_hour
WHEN NOT MATCHED THEN INSERT *
Keep it cheap by partitioning on event_hour plus a bucket of event_id, adding Parquet bloom filters or file-level skipping on event_id, and relying on Tier 1 to make most probes find nothing.
Why not Redis or Cassandra for the key set? Redis would need tens of TB of RAM at 10M ops/s. More importantly, a check-and-set in an external store is not atomic with the sink write: a crash between them either loses an event or keeps a duplicate. Keeping the dedup state inside the transactional table avoids that gap.
4. Late events (requirement 2)
Stateful operators silently drop rows older than the watermark, so do not rely on that.
- Split the stream before the dedup operator: in-window events go to Tier 1, older ones to a late branch (separate query or side topic).
- Send late events straight to the Tier 2 MERGE, which checks the full 24h on
event_idand needs no streaming state. - For events older than 24h, apply a business rule: quarantine to a dead-letter table, or merge against the relevant partition. Either way, emit a metric.
5. Skew (requirement 3)
Spark hash-partitions on the whole key, so uneven UUID prefixes do not skew anything because hashes remain uniform. Real skew comes from hot individual keys: a buggy tracker replaying one ID millions of times, or null and sentinel IDs such as all zeros.
Do not salt event_id for deduplication. Duplicates must land in the same partition to meet. A random suffix scatters them and deduplication silently fails. Salting suits aggregations, which can be recombined in a second stage, but not dedup.
Better mitigations:
- Filter or quarantine null and sentinel IDs before the shuffle.
- Pre-deduplicate within each micro-batch or partition, so hot keys collapse to one row before the shuffle.
- Partition Kafka by
hash(event_id)so no producer floods a single partition. - Enable AQE skew handling for the batch MERGE and backfill joins.
- Remember that the number of state-store partitions is fixed once a checkpoint exists; changing it requires a fresh checkpoint.
6. Idempotent sink and backfill (requirement 4)
On restart, Spark replays the same batch ID with the same offsets, so the writer has to make replays harmless:
- The insert-only MERGE on
event_idis naturally idempotent: rows already inserted match and are skipped. - For plain appends, use transactional batch markers. Delta supports
txnAppIdplustxnVersion = batchIdto skip a batch already committed. In Iceberg, record the batch ID in snapshot properties and check it before committing. - Table commits are atomic, so a half-finished write is never visible.
Backfill. Run it as a separate batch job with its own checkpoint, through the same insert-only MERGE, one partition range at a time. Existing production rows match and are skipped. Never use INSERT OVERWRITE on live partitions. Throttle the job and have writers touch disjoint partitions, or retry on optimistic-concurrency conflicts.
7. Operations and trade-offs
- Monitor state size, watermark lag, duplicate rate per tier, late-event rate, and MERGE duration.
- Tier 1 trades a small window of possible leakage for speed; Tier 2 closes the gap at higher per-batch cost.
- Compact small files regularly, since frequent MERGEs create many of them.
- If approximate dedup is acceptable, a Bloom filter in front of the MERGE cuts lookups, but false positives would drop real events, so use it only as a "definitely new" fast path, never as a reason to discard.
Common mistakes
dropDuplicatesonevent_idalone, causing unbounded state.- Salting the dedup key.
- Assuming a watermark handles late data rather than dropping it.
- Using an external cache that is not transactional with the sink.
- Overwriting partitions during backfill.