Design an Event Deduplication and Reconciliation Pipeline
System DesignModel answerLast updated
Design a distributed pipeline that deduplicates high-volume event streams, reconciles them against a delayed authoritative source, and produces auditable daily aggregates.
Background
You are building the data backend for a digital platform that must bill clients based on counted events (think clicks, views, or conversions). Two independent data sources feed your system:
- Raw Event Logs — emitted by a fleet of distributed servers at high volume (~100k events/second). These logs are noisy: duplicates are common, events can arrive out of order, and a small fraction never arrive at all.
- Billing Ledger — a separate, authoritative record that reflects which events are actually billable. It is reliable but slow, typically arriving 1–4 hours after the events it describes.
Your goal is to produce a daily per-client count report that accurately reflects the state of events across both sources. Each event falls into one of these states:
- Confirmed — present in both the raw logs and the billing ledger.
- Unverified — present in raw logs only; the ledger has not (yet) confirmed it.
- Ledger-only — present in the ledger but absent from the raw logs; these are billable and suggest dropped raw events.
What You Need to Design
Describe the end-to-end architecture of this pipeline. Your answer should cover:
- Ingestion and storage — how events flow in, where they land, and why.
- Deduplication strategy — how you identify and discard duplicate events before counting. Compare at least two approaches (e.g., probabilistic vs. exact) and explain the trade-offs for a billing context.
- Late-data handling — how you keep time-bucketed aggregates accurate when both raw logs and ledger records can arrive hours after the fact.
- Idempotency — how the pipeline stays safe to re-run; a failed job re-processing the same window must never produce double-counts.
- Interface between reconciliation and aggregation — how the component that joins the two sources communicates its output to the component that produces final counts.
Constraints and Assumptions
- Event volume: ~100k events/second average; ~300k/second at peak.
- Each event has a globally unique
event_id(client-generated UUID or ULID) plus aclient_id,timestamp, and a few metadata fields. Event size is roughly 400 bytes. - The ledger is always correct when it arrives. If it contradicts the raw logs, trust the ledger.
- Reports must be auditable: any count on a final report must be traceable to individual event IDs.
- The system must support restatement: if late data arrives after a day is marked final, the report should be correctable without silently mutating billed numbers.
Expected Output
A structured written answer. No code is required, but pseudocode or schema snippets are welcome. Cover all five areas above. Call out trade-offs and failure modes, not just the happy path.
Hints
Hint 1
Start with the numbers. 100k events/second × 86,400 seconds/day is ~8.6B raw events/day. At 400 bytes each that's ~3.5 TB/day before compression. Let those figures drive your storage and state-sizing decisions before picking any technology.
Hint 2
Deduplication and billing have conflicting tolerances for error. A Bloom filter is space-efficient but can produce false positives — think carefully about what a false positive means when the thing being counted is a billable event.
Hint 3
Separating 'provisional' from 'final' is the key to handling both timeliness and accuracy. Ask yourself: what is the latest the ledger can arrive, and how do I know when it's safe to close a day? Then design your watermark and finalization step around that answer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Size the Problem
Before drawing any architecture, pin down the numbers. This shapes every technology choice that follows.
Back-of-envelope estimates
| Quantity | Estimate |
|---|---|
| Daily raw events | 100k/s × 86,400 s ≈ 8.6B events/day |
| Raw storage | 8.6B × 400 B ≈ 3.4 TB/day; Parquet + Zstd at ~6× compression → ~570 GB/day |
| Annual storage | ~200 TB/year for raw; ledger is a small fraction of that |
| Dedup state window | Covering ~30 h of max lateness ≈ 11B keys; at ~40 B/key → ~450 GB of dedup state, sharded |
| Peak throughput | 3× average → ~300k events/s; ingestion layer must absorb this without back-pressure |
A common mistake is to design for the average and discover the peak kills the system at launch.
2. Ingestion and Storage
Ingestion layer: Kafka
Producers (the event servers) publish to a raw_events topic partitioned by hash(event_id). This is important: because duplicates of the same event share an event_id, they always land on the same partition. Deduplication becomes a local, stateful operation per partition rather than a distributed join.
Use idempotent Kafka producers (acks=all, enable.idempotence=true) so the network layer doesn't introduce duplicates of its own. Retention of 7 days covers reprocessing scenarios.
Storage: immutable landing zone
A raw archiver subscribes to the topic and writes events unchanged to an object store (S3/GCS) as an Iceberg or Delta Lake table, partitioned by ingest date and hour. This layer is never mutated. Every downstream computation is derived from it, which is the foundation of auditability — any number on any report can be traced back to source records.
The billing ledger lands in a separate Iceberg table via the same pattern.
3. Deduplication Strategy
This is where most candidates make the billing error. There are two realistic options:
Option A: Bloom filter (probabilistic)
- Space-efficient: ~10 bits/key gives 1% false positive rate, around 13 GB for 11B keys.
- A false positive means a real, unique event is discarded. In a billing context, that silently undercounts a client's billable activity. This is unacceptable as the primary dedup mechanism.
- Use a Bloom filter only as a negative cache: if the filter says "definitely not seen," skip the expensive exact lookup. If it says "possibly seen," go to the exact store to confirm.
Option B: Exact key-value store (RocksDB)
- Each unique
event_idis written once with a TTL covering the max lateness window (~30 hours). - RocksDB is a write-optimized LSM store that spills to local SSD, making it practical to hold 450 GB of dedup state per worker shard.
- Flink's RocksDB state backend checkpoints this incrementally, so recovery after a crash restores exactly the pre-failure state.
- False positive rate: zero. This is the right tool for billing dedup.
In the batch path, deduplication is even simpler: ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY ingest_time) = 1. Exact, cheap, correct.
4. Late Data and Watermarks
Always bucket by event time, not ingest time. Ingest time is an artifact of network conditions; event time reflects when the user action actually occurred, which is what billing cares about.
Two-layer approach (Lambda-style)
- A streaming layer (Flink) produces provisional counts within minutes. These are clearly marked
PROVISIONALin the serving layer. - A batch layer (Spark) runs once per day after a grace period and produces the authoritative result.
Watermark and grace period
The ledger can arrive up to 4 hours late, and raw logs can also straggle. Keep day D open until D+1 at 06:00 UTC (a 6-hour grace period after midnight). At that point the batch job runs, deduplicates the full day, full-outer-joins it with the ledger, assigns statuses, and writes version = 1 marked FINAL.
After finalization: restatement, not mutation
If a late record arrives for an already-finalized day, the system must not silently overwrite a number that has already been billed. Instead, a daily sweep job detects affected (client_id, date) partitions, recomputes them, and writes version = n+1 marked RESTATED. A billing adjustment delta is emitted separately. Beyond a hard cutoff (e.g., 30 days), late records go to a manual review queue.
5. Idempotency
The core principle: batch jobs are pure functions. f(raw snapshot, ledger snapshot) → output.
- Every run reads pinned Iceberg snapshot IDs, so the input is immutable and reproducible.
- Output is written with atomic partition overwrite (
INSERT OVERWRITE WHERE event_date = D). A crash leaves either the old partition or the new one — never a partial merge. - Re-running the same inputs produces byte-identical counts.
- Each run records lineage:
run_id, input snapshot IDs, aninput_checksum. An auditor can reproduce any historical report version.
The critical anti-pattern to avoid: writing aggregates as increments (count += delta). Increments are not idempotent. Any retry doubles the count. Always write aggregates as absolute values keyed by (client_id, report_date, version).
6. Interface Between Reconciliation and Aggregation
The reconciliation service (which joins raw events with the ledger) communicates its output via two Kafka topics:
reconciled_events— keyed byclient_id, carrying individual event records with their assigned status. The aggregation service consumes this to build counts.bucket_finalized— a control signal:{ event_date, version, run_id, input_checksum }. The aggregation service uses this as a trigger, not a poll. It knows a day is ready to aggregate only when it receives this signal, preventing partial aggregations.
The aggregation service stores its output as upserts keyed by (client_id, report_date, version) in a serving store (e.g., DynamoDB or Postgres), exposed via a versioned read API:
GET /v1/clients/{id}/reports/daily?date=2024-05-01&version=latest
Response includes status ∈ {PROVISIONAL, FINAL, RESTATED} so consumers always know the quality of the number they're reading.
Common Mistakes to Avoid
- Using Bloom filters as the primary dedup mechanism for billing. False positives lose revenue.
- Bucketing by ingest time. Late events land in the wrong day and corrupt counts.
- Writing counts as increments. Makes retries unsafe.
- Silently overwriting finalized reports. Destroys the audit trail and creates billing disputes.
- Skipping the
LEDGER_ONLYcase. Events the ledger knows about but the raw logs don't are billable; ignoring them undercharges clients.