Exactly-Once Disbursements Across Flaky Banking Rails
System DesignModel answerLast updated
Design a payout service that never moves money twice despite client retries, parallel workers, and gateway timeouts during peak payroll bursts.
Problem
You are designing the payout backbone for a platform that pays employees and contractors on fixed schedules (for example, the 1st and 15th of each month). In those windows, scheduled batch jobs, partner API clients, and employers pressing "retry" all fire payment requests at once. The money moves over external rails such as ACH, instant-payment networks, or card-style gateways, which can be slow and can drop connections without telling you whether the transfer happened.
The core promise: no payee is ever paid twice for the same logical payment, even if clients retry aggressively, two workers pick up the same job, or the bank call times out.
Functional requirements
- Submit a payment with an idempotency key, source account, destination account, amount, and currency.
- Idempotent replay: repeating a request with the same key must return the same response as the first call (whether it succeeded or is still in progress) and must not trigger a second transfer.
- Status lookup: an endpoint that returns the current state of any payment.
- Resolve uncertain outcomes: payments whose result is unknown because of gateway timeouts or network partitions must be driven to a definitive state.
Non-functional requirements
- Correctness: zero duplicate payments under any combination of failures and concurrency.
- Availability: 99.99% for submission, 99.999% for status reads.
- Latency: the client gets an acknowledgment in under 250 ms; the actual bank interaction may be asynchronous.
Scale assumptions
- Peak: 5,000 payment requests per second during cutoff windows.
- Up to 20 million disbursements on a peak day.
- Each bank interaction takes roughly 0.5 s to 5 s to complete.
What to cover
- API and idempotency keys: request and response shapes, how keys are produced, and where idempotency records live.
- Data model and state machine: the states a payment passes through (for instance created, pending execution, sent to bank, settled, failed, indeterminate) and the schema behind them.
- Concurrency control: how two identical requests landing on different servers at the same instant are prevented from both proceeding. Compare distributed locks with database uniqueness guarantees.
- Failure handling: gateway timeouts, looking up the real outcome, reconciliation jobs, and keeping the ledger consistent.
Hints
Hint 1
Start with the invariant and the trade-off: when the system is unsure, should it retry or wait? Use Little's Law (rate x latency) to see how many bank calls are in flight at peak, and let that drive the sync vs. async decision.
Hint 2
Make the database the arbiter. A unique constraint on (tenant, idempotency key) plus compare-and-set state transitions gives you correctness without relying on a lock that can expire. Think about how batch jobs derive the same key deterministically.
Hint 3
Record intent before calling the bank, and treat a timeout as 'unknown', not 'failed'. Design a dedicated indeterminate state and the ways out of it: query the gateway by your reference, retry with the same gateway key, and daily statement reconciliation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the invariant and the numbers
- Invariant: at most one money movement per logical payment. Availability and latency matter, but when the system is unsure it waits rather than retries. A delayed payout is recoverable; a duplicate deposit often is not.
- Throughput: 20M/day averages about 230 writes/s, but bursts hit 5,000/s. Size for the burst.
- In-flight work: 5,000/s x 5 s is about 25,000 concurrent outbound calls. Holding client connections that long is impractical, so the API must be asynchronous: validate, persist, return
202 Accepted. - Storage: about 1 KB per payment including the idempotency record gives about 20 GB on a peak day and a few TB per year with audit retention.
2. API and idempotency keys
POST /v1/payments
Idempotency-Key: <key>
{ source_account_id, destination_account_id, amount_minor, currency, rail }
202 Accepted
{ payment_id, status: "PENDING_EXECUTION", created_at }
GET /v1/payments/{payment_id} -> current state and history
Key generation
- External clients generate one UUID per logical payment and reuse it on every retry.
- Internal batch jobs derive the key deterministically, for example a hash of
(tenant, payroll_run, employee, pay_period). Two workers handling the same item then produce the same key. Random per-worker keys would defeat idempotency. - Uniqueness is scoped to
(tenant_id, idempotency_key).
Payload check: store a hash of the canonicalized request body. If the same key arrives with a different body, return 422 instead of replaying, since that is a client bug.
Storage: the primary database is the source of truth. A Redis cache of completed responses can absorb retry storms, but it is never the correctness mechanism.
3. Data model
payments: payment_id, tenant_id, idempotency_key, request_hash, accounts, amount_minor, currency, state, version, gateway_ref, response_snapshot, timestamps, UNIQUE (tenant_id, idempotency_key).payment_events: append-only audit of every transition (from, to, reason, time).outbox: rows written in the same transaction as the payment, relayed to a message bus.ledger_entries: double-entry rows with a unique constraint on(payment_id, entry_type, direction)so posting is itself idempotent.
Shard by tenant_id so a payment, its idempotency record, its ledger hold, and its outbox row share a shard and commit in one local transaction.
4. State machine
CREATED -> PENDING_EXECUTION -> SENT_TO_BANK -> SETTLED
| |--> FAILED
|--> FAILED |--> INDETERMINATE -> SETTLED | FAILED
- Transitions only move forward;
SETTLEDandFAILEDare terminal. - Every transition is a compare-and-set:
UPDATE ... SET state=:new, version=version+1 WHERE payment_id=:id AND state=:expected. Zero rows updated means someone else won, so the caller re-reads and stops. - Each transition writes an event row in the same transaction.
Webhooks, pollers, and reconcilers can then race safely; a stale "pending" update can never overwrite SETTLED.
5. Architecture and request flow
- API service (stateless): in one transaction, insert the payment (conflict on the unique key does nothing), place a ledger hold on the source, and write an outbox row. Commit, return
202. This is a single-shard write and fits comfortably under 250 ms. - Outbox relay publishes to a log such as Kafka, partitioned by
payment_idfor per-payment ordering and no dual-write gap. - Executor workers:
- CAS
PENDING_EXECUTION -> SENT_TO_BANKbefore calling the gateway (write-ahead intent). - If the CAS fails, another worker owns it; drop the message. This makes at-least-once delivery safe.
- Call the gateway with
payment_idas the gateway-level idempotency key.
- CAS
- Webhook handler, poller, reconciler move payments to terminal states.
- Ledger: hold on create, post on
SETTLED, release onFAILED.
6. Concurrency
Two identical requests on different nodes both try the insert. The unique index serializes them and exactly one commits. The loser either gets a conflict or briefly blocks on the index entry, then reads the committed row and returns the stored response_snapshot (same payment_id, current status).
No distributed lock is needed. A lock (Redis or otherwise) can expire, suffer a GC pause, or lose state on failover, letting two holders proceed. Use locks only as an optimization to reduce contention, never as the guarantee.
7. Failure modes
| Failure | Handling |
|---|---|
| Crash before gateway call | Row still PENDING_EXECUTION; redelivery plus CAS lets one executor proceed. |
| Crash after CAS, during the call | Row stuck in SENT_TO_BANK; a sweeper moves stale rows to INDETERMINATE, never back to pending. |
| Gateway 504 or connection reset | Do not mark failed and do not retry under a new key. Mark INDETERMINATE. |
| Definitive 4xx | Mark FAILED, release the hold. |
| Duplicate or late webhooks | CAS makes them no-ops. |
Resolving INDETERMINATE:
- Reverse lookup by our reference at the gateway, with exponential backoff.
- Same-key retry if the gateway honors idempotency keys, within its retention window (often at least 24 h).
- Out-of-band reconciliation: match daily bank files and returns against the ledger. Mismatches go to an ops queue; items past their SLA page a human.
The ledger posts only on confirmed terminal states, so reconciliation is the final arbiter.
8. Availability
Run the API across zones with synchronous replication for the payments shard; failover must not lose acknowledged writes. Status reads can use replicas and a cache, which is how they reach a higher availability target than submission. If the bank is down, submission still succeeds (payments queue as pending), so submission availability does not depend on the rails.
Trade-offs
- Unique constraint vs. lock: the constraint costs a little throughput but is correct under every failure.
- Async
202vs. sync result: necessary at 5 s rail latency; clients poll or receive webhooks. - Indeterminate holds: some payees are delayed, which is accepted to avoid duplicates.
Common mistakes
- Relying on a Redis lock or in-memory dedup as the correctness mechanism.
- Treating a timeout as a failure and retrying with a fresh key.
- Calling the bank before durably recording intent.
- Random per-worker keys for batch jobs.
- Letting late webhooks overwrite terminal states.
- Not validating that a replayed key carries the same payload.