Building a Transaction Dispute Resolution System
System DesignModel answerLast updated
Design a backend system to manage the complete lifecycle of payment disputes in an e-commerce marketplace, including evidence handling, deadline management, and financial settlements.
Problem Context
You're building a backend system for an e-commerce marketplace where buyers can formally challenge transactions when problems arise—items never delivered, significant mismatches with descriptions, or charges they didn't authorize. After informal attempts to resolve issues fail, buyers need a structured process to submit disputes, provide supporting materials, and reach resolution.
Your Task
Design the backend architecture for a transaction dispute resolution system that handles the complete dispute workflow from creation through final settlement.
System Requirements
Functional Capabilities
-
Dispute Initiation & Validation: Check whether a transaction qualifies for dispute based on purchase timing, current order state, and platform policies before allowing dispute creation.
-
Supporting Materials Management: Enable both parties to submit documents and written statements within time-bound windows (example: sellers get 5 business days to respond).
-
Lifecycle Management & Time Enforcement: Track disputes through defined stages (
OPEN,AWAITING_SELLER_RESPONSE,PLATFORM_REVIEW,RESOLVED_FOR_BUYER,RESOLVED_FOR_SELLER,CLOSED). Automatically progress or close cases when response periods expire. -
Temporary Funds Handling & Final Settlement: Issue temporary credits to buyers or freeze seller funds as needed, then execute final money movement based on resolution outcome. All financial operations must be idempotent.
-
Payment Gateway Integration: Communicate dispute information with external payment processors (credit card networks, third-party payment services) using reliable, retry-safe interfaces.
-
Change Tracking & Notifications: Record every action and state change in an immutable log while sending asynchronous updates to participants at important milestones.
Scale & Performance Targets
- User base: 50 million marketplace users
- Dispute volume: 200,000 new cases monthly (~5,000 daily)
- File uploads: Up to 15 MB per file for evidence submission
- Consistency requirement: Financial operations and state transitions must prevent duplicate refunds or credits
- Security requirement: Uploaded files must be screened for threats; customer information must have strict access controls
Expected Design Elements
Your solution should address:
- API Interface: Key endpoints for creating disputes, submitting evidence, checking status, and resolving cases
- Data Schema & State Tracking: Database design for disputes, evidence metadata, deadlines, and state progression
- Component Architecture: System diagram showing request handling, background processing, storage, and external service integration
- Failure Scenarios: How to handle gateway timeouts, simultaneous file uploads, state transition conflicts, and malicious file uploads
Hints
Hint 1
The challenge is correctness, not scale—200K disputes per month is manageable with a single database. Focus on preventing duplicate financial operations and ensuring state transitions are atomic.
Hint 2
Use optimistic concurrency control (version numbers) to handle concurrent state updates safely. A conditional UPDATE that checks current state and version will naturally serialize competing transitions.
Hint 3
Separate side effects (notifications, gateway calls) from state changes using the transactional outbox pattern—write an event row in the same transaction as the state change, then process it asynchronously.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Transaction Dispute Resolution System Design
Initial Scope & Scale Analysis
The first insight: this is a correctness problem, not a scale problem. At 200K disputes per month, we're looking at roughly 77 writes per hour or ~0.02 per second on average. Peak traffic might reach 2-5 requests per second. Including status queries, evidence uploads, and gateway callbacks, total load stays comfortably under 100 QPS—well within single-database capacity.
Key Numbers:
- Active disputes at any time: ~300K (assuming 45-day average lifecycle)
- Evidence storage: ~8 MB average per dispute × 200K/month = 1.6 TB monthly, ~20 TB annually with retention
- Pending timers: ~500K deadline events in flight
- Critical requirement: Strong consistency for money movement and state changes; eventual consistency acceptable for notifications and search
The hard problems are preventing duplicate refunds, ensuring state machine integrity, and coordinating with unreliable external payment gateways.
API Design
All mutation endpoints require an Idempotency-Key header to enable safe retries.
POST /disputes
Body: {transaction_id, reason, description}
Returns: {dispute_id, current_state, response_deadlines}
Errors: 409 if ineligible or duplicate active dispute exists
POST /disputes/{id}/evidence/init-upload
Body: {filename, mime_type, size_bytes}
Returns: {evidence_id, upload_url, expiration}
POST /disputes/{id}/evidence/{evidence_id}/confirm
POST /disputes/{id}/statements
Body: {statement_text, submitter_role}
GET /disputes/{id}
Returns: current_state, timeline, evidence_summary, deadlines
POST /admin/disputes/{id}/resolve
Body: {outcome, refund_amount, state_version}
POST /webhooks/gateway/{provider}
(signature verification, fast acknowledgment)
Data Model (PostgreSQL)
disputes table:
id,transaction_id,buyer_id,seller_id,reason_codeamount,currency,current_state,state_versionexternal_reference_id,payment_gateway,created_at,updated_at- Constraint:
UNIQUE(transaction_id) WHERE current_state NOT IN ('RESOLVED_FOR_BUYER', 'RESOLVED_FOR_SELLER', 'CLOSED')prevents multiple active disputes per transaction
deadline_timers table:
dispute_id,deadline_type,fire_at,timer_status,required_state- Indexes on
(fire_at, timer_status)for efficient polling
evidence_items table:
id,dispute_id,submitter_id,submitter_role,storage_keyfile_hash,mime_type,size_bytes,scan_result,upload_status
state_change_log (append-only audit trail):
id,dispute_id,sequence_number,event_typeprevious_state,new_state,actor_id,timestamp,metadata_jsonprior_event_hash,current_event_hash(creates tamper-evident chain)
financial_ledger table:
id,account_identifier,amount,entry_type,dispute_id,operation_category- Constraint:
UNIQUE(dispute_id, operation_category)physically prevents duplicate provisional credits or settlements
message_outbox table:
id,aggregate_id,message_type,payload_json,processed_at
request_idempotency table:
idempotency_key,request_fingerprint,response_data,created_at- TTL of 24 hours
System Architecture
Client Applications
↓
API Gateway (authentication, rate limiting)
↓
Dispute Service (validation, state machine logic)
↓ (single transaction)
PostgreSQL ← [disputes + state_change_log + deadline_timers + financial_ledger + message_outbox]
↓
Outbox Processor → Message Queue (Kafka/SQS)
↓
┌───┴───┬──────────┬──────────┐
↓ ↓ ↓ ↓
Settlement Gateway Notification Audit
Worker Adapter Service Archiver
↓ ↓ ↓ ↓
Ledger External Email/Push Immutable
System Gateways Storage
Deadline Service (separate):
- Polls
deadline_timersevery 30 seconds forfire_at <= now() AND status = 'PENDING' - Calls Dispute Service to trigger timeout transitions
- Handles business-day calculations using holiday calendar data
Evidence Pipeline:
- Pre-signed upload URLs point to quarantine bucket
- S3 event triggers scanning: AV engines + content sanitization (re-render PDFs, strip image metadata)
- Clean files move to production bucket; status updates to
evidence_items
Webhook Ingestion:
- Verifies cryptographic signatures
- Stores raw payload with deduplication on
(gateway, event_id) - Acknowledges within 100ms
- Asynchronous processing handles out-of-order events
Critical Design Decisions
1. State Machine with Optimistic Concurrency
Each transition validates the current state and increments a version:
UPDATE disputes
SET current_state = :new_state,
state_version = state_version + 1
WHERE id = :dispute_id
AND current_state = :expected_state
AND state_version = :expected_version;
If the update affects zero rows, another process already changed the state. The loser re-reads current state and usually treats its event as a no-op. Terminal states reject all transitions.
2. Financial Operations as Saga
Money movement happens in stages, all tracked in financial_ledger:
On dispute creation (if policy allows):
- Insert
PROVISIONAL_CREDITfor buyer - Insert
SELLER_FUNDS_HOLD
On resolution:
- For buyer win:
FINALIZE_REFUND+PERMANENT_SELLER_DEBIT - For seller win:
REVERSE_PROVISIONAL_CREDIT+RELEASE_FUNDS_HOLD
The unique constraint on (dispute_id, operation_category) makes duplicate operations impossible at the database level. External payout calls use idempotency keys like {dispute_id}:{operation_type}. Nightly reconciliation compares internal ledger against gateway settlement reports.
3. Transactional Outbox Pattern
Side effects (gateway calls, notifications) must never execute without the corresponding state change, and state changes must never be lost. Solution:
BEGIN;
INSERT INTO state_change_log (...);
UPDATE disputes SET current_state = ... WHERE ...;
INSERT INTO financial_ledger (...);
INSERT INTO message_outbox (dispute_id, 'NOTIFY_SELLER', ...);
COMMIT;
A separate outbox processor polls for unprocessed messages and publishes to the message queue. If processing fails, it retries. If the database transaction fails, nothing happens—no partial state, no orphaned notifications.
4. Gateway Coordination
Each payment gateway gets an adapter behind a common interface. Key patterns:
Outbound calls: Include deterministic idempotency tokens. On timeout, query the gateway's status endpoint before retrying—never blindly resubmit.
Inbound webhooks: Verify HMAC signatures, deduplicate on external event ID, persist raw payload, acknowledge immediately. Process asynchronously, handling out-of-order arrivals by checking current dispute state.
Reconciliation: Hourly job polls open cases at the gateway to catch missed webhooks or discrepancies.
5. Evidence Security Pipeline
- Pre-signed upload URL scoped to specific key, 15 MB max, allowed MIME types only
- File lands in quarantine bucket
- Validation workers verify magic bytes match declared type
- Run AV scanning (ClamAV + commercial engine)
- Content sanitization: flatten/re-render PDFs, re-encode images (strips macros, EXIF, embedded scripts)
- Move to production bucket with KMS encryption
- Update
scan_resultfield
Concurrent uploads are safe because each evidence item has a unique ID and storage key.
6. Deadline Enforcement
Business-day calculations use a stored holiday calendar per region. Deadlines are computed at creation and stored explicitly. Timer service polls for expired deadlines and invokes the state machine. Accuracy within 1-2 minutes is sufficient for business processes.
Edge Cases & Failure Modes
Concurrent state changes: Optimistic locking ensures only one wins; loser rechecks and usually no-ops.
Duplicate dispute creation: Unique constraint on transaction_id blocks it at database level.
Gateway timeout during settlement: Mark operation as UNCERTAIN, query gateway status, then retry or complete based on actual state.
Missed webhook: Periodic polling of open gateway cases detects and reconciles.
Malicious file upload: Quarantine + multi-layer scanning + content sanitization prevents execution.
Database failure during commit: Transaction rolls back completely; client retries with same idempotency key and gets consistent outcome.
Message loss after outbox insert: Outbox processor retries until message is successfully published; downstream consumers must be idempotent.
This design prioritizes correctness through database transactions, idempotency, and eventual consistency for side effects while keeping the architecture simple enough to operate reliably at moderate scale.