Design a Dispute Record Ingestion and Daily Batch Export System
System DesignModel answerLast updated
Design a system that reliably ingests high-volume dispute events from external networks and exports a daily batch file to a downstream accounting system.
Context
You work on the platform team at a payments company. External card networks notify your system whenever a cardholder disputes a transaction — these are called dispute events. Your job is to build the backend infrastructure that accepts those events and feeds them into the company's internal accounting system on a daily basis.
What the system must do
Ingestion External networks push events to your service over HTTPS. Each event contains a transaction ID, dispute amount, currency code, merchant ID, and a timestamp. Your endpoint must respond quickly and hand off work asynchronously — it cannot block waiting for downstream processing.
No data loss Every event must be durably captured, even if your database is temporarily unavailable or a downstream service is slow. The system must also survive network timeouts without losing data.
Duplicate prevention External networks frequently retry events that didn't receive a timely acknowledgment. Your system must recognize and ignore duplicates without producing extra records.
Daily export Once every 24 hours, produce a CSV file containing all dispute records from the previous day and deliver it to the internal accounting system via SFTP.
Audit trail Each record should carry a status reflecting where it is in the pipeline — for example: received, queued, staged, and exported.
Scale
- Roughly 50,000 events per day under normal conditions
- Up to 5× that volume during high-traffic periods (major shopping events, holidays)
- Any cardholder-identifying data must be encrypted at rest
What your answer should cover
- A component-level architecture — a diagram or a clearly labeled list of services and how they connect
- A database schema covering both dispute records and export batches
- How you handle retries for failed incoming events and failed SFTP uploads
- How you keep the daily export consistent when new events are arriving at the same time the file is being generated
Hints
Hint 1
Before designing anything, size the problem. 50,000 events/day is under 1 event/second on average, even at 5× peak you're only around 3/s sustained. This is a correctness and reliability problem, not a throughput one — let that guide your architecture choices.
Hint 2
Think carefully about what makes a good idempotency key. A transaction ID alone isn't safe — one transaction can generate multiple partial disputes. The combination of network name and the network's own event ID is the right dedupe key.
Hint 3
Separate the generation of the export file from the act of uploading it. If you store the CSV in object storage first and upload from there, retrying a failed upload is trivially safe — you just resend the same bytes without regenerating anything.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the problem first
Before drawing any boxes, establish what the numbers actually demand.
- Average throughput: 50,000 events/day ÷ 86,400 s ≈ 0.6 events/s
- Peak throughput: 5× normal ≈ 3 events/s sustained; webhooks are bursty, so plan for short spikes of 50–100 rps
- Storage: ~1 KB per record → 50–250 MB/day, well under 100 GB/year. A single Postgres primary with one read replica handles this comfortably.
- Export file: up to ~250,000 rows once per day
The conclusion: this is a correctness problem, not a scale problem. The design should optimize for zero data loss, exactly-once semantics, and a clean audit trail — not raw throughput.
Clarifying questions worth asking: Does the network send a stable unique event ID per dispute? Can a single transaction produce multiple disputes (partial disputes)? Which timezone defines "end of day"? What is the accounting team's SLA — e.g., "file must arrive by 06:00"?
2. Architecture
Card Networks ──HTTPS──> [API Gateway / Load Balancer]
│
[Ingest Service]
(verify HMAC signature,
validate schema)
│ │
archive raw payload publish to queue
▼ ▼
[Object Store] [Message Queue: disputes.received]
│
[Consumer Service] ──> Dead Letter Queue
│ idempotent upsert
▼
[Postgres: disputes, export_batches]
▲
[Scheduler] ──> [Export Worker] ──> [Object Store: CSV] ──> [SFTP Uploader] ──> Accounting
The critical rule: the ingest service only returns 2xx after the event is durably written to the queue. If that write fails, return 5xx and let the network retry. The dedupe key makes those retries safe.
The queue absorbs traffic spikes. If the database slows down or restarts, consumers simply lag — nothing is lost. Archiving the raw payload to object storage enables full replay at any time.
3. Data model
disputes (
id UUID PRIMARY KEY,
network TEXT NOT NULL, -- e.g. VISA, MASTERCARD
network_event_id TEXT NOT NULL, -- the network's own stable ID
transaction_id TEXT NOT NULL,
merchant_id TEXT NOT NULL,
amount_minor BIGINT NOT NULL, -- store in cents; never use floats for money
currency CHAR(3) NOT NULL, -- ISO 4217
occurred_at TIMESTAMPTZ NOT NULL, -- the network's timestamp
received_at TIMESTAMPTZ NOT NULL, -- when we accepted it; drives export windows
pii_encrypted BYTEA, -- envelope-encrypted via KMS
status TEXT NOT NULL, -- RECEIVED | QUEUED | STAGED | EXPORTED | REJECTED
export_batch_id UUID REFERENCES export_batches(id),
version INT NOT NULL DEFAULT 0, -- optimistic locking
updated_at TIMESTAMPTZ NOT NULL,
UNIQUE (network, network_event_id)
);
CREATE INDEX ON disputes (status, received_at);
export_batches (
id UUID PRIMARY KEY,
business_date DATE NOT NULL UNIQUE, -- enforces one batch per day
status TEXT NOT NULL, -- STAGING | GENERATED | UPLOADED | FAILED
cutoff_at TIMESTAMPTZ NOT NULL,
record_count INT,
total_amount_minor BIGINT,
file_sha256 TEXT,
file_uri TEXT,
upload_attempts INT DEFAULT 0,
last_error TEXT
);
dispute_audit_log (dispute_id, from_status, to_status, occurred_at, actor);
Idempotency key: (network, network_event_id) — not transaction_id alone. A single transaction can generate several partial disputes; keying on transaction ID would silently drop real money.
The consumer runs INSERT ... ON CONFLICT (network, network_event_id) DO NOTHING. A conflict is treated as success and the queue offset is committed normally.
State machine: RECEIVED → QUEUED → STAGED → EXPORTED. Every transition is a conditional update: UPDATE ... WHERE status = 'QUEUED'. A transition from the wrong state affects 0 rows, making double-processing structurally impossible.
4. Retry strategy
Inbound (from card networks)
- Return
5xxon any durable-write failure; the provider's own retry policy becomes your safety net. - Return
4xxonly for permanently invalid requests (bad HMAC, malformed schema). Archive the raw body to a quarantine bucket so nothing is silently discarded. - Consumer-side failures (DB timeout, deadlock): retry with exponential backoff and jitter (e.g., 100 ms → ~30 s ceiling). After N attempts, route to a dead-letter queue with the error attached and fire an alert.
- A replay tool that re-publishes from the DLQ or the raw archive is safe because the upsert is idempotent. Queue retention of 7 days covers even prolonged database outages.
Outbound (SFTP upload)
- Generate the CSV once and store it in object storage. Retries resend the same bytes — never regenerate the file.
- Use an atomic upload pattern: write to a
.tmpfilename, verify the remote size and checksum, then rename to the final deterministic name. Before any retry, check whether a file with a matching checksum already exists. This handles the case where the upload succeeded but the acknowledgment was lost. - Retry schedule: exponential backoff with jitter (1, 2, 4 … capped at 30 min) plus a circuit breaker. Records remain in
STAGEDstatus until the upload is confirmed, so nothing falls through.
5. Consistency during file generation
The scheduler must guarantee only one active job per day. The UNIQUE(business_date) constraint on export_batches is the lock — a duplicate job simply fails to insert and exits cleanly.
Generation sequence:
INSERT INTO export_batches (business_date=D, cutoff_at=D+1 00:00, status='STAGING')- Claim records atomically in a single transaction:
This freezes batch membership. Events arriving after the cutoff stayUPDATE disputes SET status = 'STAGED', export_batch_id = :batch_id, version = version + 1 WHERE status = 'QUEUED' AND received_at < :cutoff_at;QUEUEDand land in tomorrow's file — no event is ever lost. - Generate the CSV deterministically:
SELECT ... WHERE export_batch_id = :batch_id ORDER BY id. Include a trailer row with the total record count and amount sum per currency. Store the file, compute its SHA-256, and mark the batchGENERATED. - Upload as described above.
- In a single transaction: mark the batch
UPLOADEDand all its recordsEXPORTED.
Common mistakes
- Using transaction ID as the idempotency key. Partial disputes mean one transaction can legitimately produce multiple dispute events. A collision on transaction ID silently drops real money.
- Storing monetary amounts as floats. Always use integer cents (or the smallest currency unit). Float arithmetic loses precision at scale.
- Regenerating the CSV on each upload retry. If records arrive between two generation attempts, the two files will differ, causing non-deterministic exports. Generate once, upload many times.
- Skipping the raw payload archive. Without it, there's no way to replay or investigate quarantined events. Storage is cheap; missing audit trails are not.