Building a Duplicate-Safe Money Movement Service with Settlement Matching
System DesignModel answerLast updated
Design a service that moves customer funds through external bank rails without double-charging, tracks each transfer's lifecycle, and repairs mismatches using daily bank settlement files.
Problem
You are designing the backend that lets customers of a brokerage app add money to their account (deposit) or take money out (withdrawal) over bank transfer (ACH) and debit rails. The service talks to outside payment processors and partner banks.
The environment is unreliable. Connections drop mid-request, mobile clients resend requests, processors time out or answer late, and webhooks may arrive twice or in the wrong order. Despite this, your design must guarantee that:
- No customer is charged or credited twice.
- Every unit of money is accounted for.
- Every in-flight transfer is eventually resolved to a final outcome.
Functional requirements
- Initiation: Accept deposit and withdrawal requests that carry a client-supplied idempotency key.
- Provider integration: Submit transfers to external rails and capture outcomes from both synchronous responses and asynchronous webhooks.
- Lifecycle tracking: Model each transfer with an explicit set of states, for example
CREATED,PROCESSING,SUCCEEDED,FAILED, andREQUIRES_RECONCILIATION. - Reconciliation: Ingest daily settlement or clearing files from partner banks, find differences against internal records, and correct them.
Non-functional requirements
- Strict idempotency: Repeated calls, deliberate or accidental, never cause a second money movement.
- Durability and auditability: Every balance change, state change, and provider interaction is recorded in an append-only fashion.
- Availability and fault tolerance: Survive provider outages, timeouts, and out-of-order or duplicate webhooks.
Scale
- About 10 million transfers per day: roughly 120 requests/second on average, 600/second at peak.
- Up to 100,000 transfers pending settlement or asynchronous resolution at any moment.
What to deliver
- API design for initiating transfers and receiving provider webhooks.
- A state machine and data model covering transfers, idempotency keys, and transitions.
- An end-to-end architecture that handles timeouts, retries, and cross-system consistency.
- A reconciliation approach for mismatches discovered when settlement files are loaded.
Hints
Hint 1
Throughput here is modest. Ask yourself what the genuinely hard part is, and state the core invariant you want the system to uphold, such as one external money movement per payment record and one balanced set of ledger entries.
Hint 2
Think about two separate idempotency boundaries: client to your API, and your service to the provider. Also consider what a timeout actually tells you about whether money moved, and whether a timed-out payment should ever be marked failed.
Hint 3
To avoid inconsistency between your database and the provider call, consider writing the intent durably in the same transaction as the payment and dispatching it from there. For webhooks and state changes, use deduplication tables and conditional updates so late, duplicate, or reordered events become harmless no-ops.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem
At 120 rps average and 600 rps peak, throughput is not the challenge. A relational database sharded by user_id handles it comfortably. Correctness under failure is the hard part.
Rough sizing: about 1 KB per payment row plus 2-4 ledger entries gives 10-20 GB/day, or 5-7 TB/year. Use time-partitioned tables and move old partitions to cold storage; never delete audit data. With only ~100K payments in flight, a polling resolver backed by an index on (state, next_check_at) is cheap.
State the invariant up front: each external money movement maps to exactly one payment record and one balanced set of ledger entries.
2. API
POST /v1/payments
Headers: Idempotency-Key, Authorization
Body: { type: DEPOSIT|WITHDRAWAL, amount_minor, currency,
funding_source_id, rail: ACH|DEBIT }
201 first call | 200 replay of a finished request
409 original still in flight | 422 same key, different payload
GET /v1/payments/{id}
POST /internal/webhooks/{provider} (verify signature, ack fast)
Amounts are integer minor units, never floats. Hash the request body and store it with the key so a reused key with a different payload is rejected.
3. Data model
idempotency_keys(user_id, idem_key, request_hash, payment_id, response, expires_at), primary key(user_id, idem_key).payments(payment_id, user_id, type, amount_minor, currency, rail, state, version, provider_ref UNIQUE, next_check_at, ...).payment_events(append-only): from/to state, source (API, WEBHOOK, POLL, RECON, OPS), raw payload.ledger_entries(append-only, double-entry): each transaction's entries sum to zero. Balances are derived from it.outboxfor pending provider calls, andwebhook_inboxwithUNIQUE(provider, provider_event_id).
Withdrawals first move funds from user_available to user_pending_withdrawal (a hold), then to clearing_bank on success or back on failure. Corrections are always new compensating entries, never edits. Sharding by user_id keeps the idempotency row, payment, and ledger writes in one local transaction.
4. State machine
CREATED -> PROCESSING -> SUCCEEDED -> RETURNED/REVERSED (ACH returns)
-> FAILED
PROCESSING -> UNKNOWN (timeout/5xx) -> SUCCEEDED | FAILED
any state -> REQUIRES_RECONCILIATION (mismatch)
Rules:
- A timeout is not a failure. It is
UNKNOWNuntil the provider confirms the outcome. Failing early refunds users for money that actually moved. - Transitions are conditional updates, for example
UPDATE payments SET state='SUCCEEDED', version=version+1 WHERE payment_id=? AND state IN ('PROCESSING','UNKNOWN'). Zero rows updated means the transition was already applied or illegal, so it is a no-op. This neutralizes duplicate and out-of-order events. - Each transition writes its event row and ledger entries in the same transaction.
5. End-to-end flow
- API transaction: insert the idempotency key (a unique violation means a duplicate, so replay the stored response or return 409), insert the payment as
CREATED, place the ledger hold for withdrawals, insert an outbox row, commit. - Outbox dispatcher: claims the row, moves the payment to
PROCESSING, and calls the provider using ourpayment_idas the provider-side idempotency key. This makes retries across the network boundary safe. - Response handling: definitive success or decline applies a conditional transition. Timeout, reset, or 5xx moves to
UNKNOWNwith anext_check_at. - Resolver: polls the provider's status endpoint for
UNKNOWNand stalePROCESSINGitems with exponential backoff. If the provider has no record after a safe window, resubmit with the same key or fail. After N hours, escalate toREQUIRES_RECONCILIATION. - Webhooks: verify the HMAC signature, insert into
webhook_inbox(dedupes redeliveries), return 200 immediately, then process asynchronously through the same conditional-transition function.
The outbox pattern removes the dual-write problem: there is never a provider call without a durable record, nor a record that silently skips its call. Add per-provider circuit breakers; during an outage, payments wait in the outbox instead of failing.
6. Reconciliation
A daily batch pipeline:
- Ingest settlement files (NACHA returns, BAI2, processor CSVs) via SFTP. Store the raw file immutably with a checksum so reprocessing is a no-op.
- Normalize into a
settlement_recordsstaging table. - Match on
provider_ref, falling back to amount + date + trace number, and classify:- Matched: set
settled_at. - Missing internally: the bank moved money we have no record of. High severity; page on-call and create a payment in
REQUIRES_RECONCILIATION. - Missing externally: we say SUCCEEDED, the bank disagrees. Wait out an aging window (about T+3 for ACH) before flagging.
- Amount or status mismatch: flag.
- Matched: set
- Resolve: deterministic cases (such as an NSF return on a succeeded deposit, or an
UNKNOWNitem the file settles) are fixed automatically with compensating ledger entries. Everything else goes to an ops queue with the full event history. - Three-way check: internal ledger vs processor report vs bank statement, plus a check that the internal clearing account equals the bank's ending balance. Aggregate checks catch errors that row-level matching misses.
7. Trade-offs
- SQL vs NoSQL: choose a relational store with transactions for ledger and payment state; the volume does not justify giving up ACID.
- Sync vs async provider calls: async via the outbox adds small latency but gives durability and clean retry semantics.
- Auto-resolve vs manual review: automate only deterministic fixes; ambiguous cases need humans.
- Polling vs webhooks: use both. Webhooks are fast but unreliable; polling and reconciliation are the safety nets.
8. Common mistakes
- Marking a timeout as
FAILEDand refunding while the money actually moved. - Providing idempotency only at the client API and not toward the provider.
- Updating ledger rows in place instead of appending compensating entries.
- Processing webhooks inline without deduplication or ordering protection.
- Using floats for money.
- Treating reconciliation as optional rather than as the final source of truth.
- Calling the provider inside the same DB transaction that holds locks.
9. Likely follow-ups
- Poison webhooks: park in a dead-letter queue and alert, keeping the raw payload.
- Late ACH returns (days later):
SUCCEEDED -> RETURNEDvia a compensating ledger entry, with possible negative balance handling. - Hot users or provider-wide outage: per-provider rate limiting, bulkheads, and rerouting to a backup provider only if its idempotency semantics are compatible.