Keeping Courier Payouts Correct When the Processor Is Flaky
System DesignModel answerLast updated
Design a payout pipeline that stays correct and pays each courier exactly once when the downstream payment processor is slow, erroring, or down for hours.
Scenario
You are responsible for a backend service that works out how much each delivery courier is owed and then asks an external payment processor to transfer that money. Couriers receive scheduled weekly payouts, and some can also trigger an instant cash-out from the app and expect an answer within seconds.
The processor is not always healthy. It may be fully down, respond very slowly, hang until your client times out, or fail on a fraction of requests.
Question
Describe how your system should behave during such an outage. Your design should protect two things at once: financial correctness (nobody is paid twice, nobody is silently skipped) and a reasonable experience for couriers and support staff.
Cover at least the following:
- How you make payout requests safe to repeat (idempotency)
- Your retry policy, including backoff and jitter, and how you decide which errors to retry
- When a call should be retried inside the request versus handed off to background processing
- Circuit breaking and what the system does while the breaker is open
- How a queue and a dead-letter path help with recovery
- How you reconcile your records against the processor once it is healthy again
- What you monitor and when you alert
State any assumptions you make about scale and about the processor's capabilities.
Hints
Hint 1
Ask what a client timeout really tells you. Did the processor receive the request and perhaps execute it, or not? Think about a state for payouts whose outcome you do not know.
Hint 2
Separate errors into those worth retrying, those that never will succeed without human action, and ambiguous ones. Then think about which identifier must stay constant across every attempt.
Hint 3
Scheduled payouts and instant cash-outs have very different latency budgets. Think about what happens to a request that cannot finish within the user's patience, and how to avoid the user submitting again.
Hint 4
Retries and queues give at-least-once delivery. What independent process confirms that your database and the processor actually agree about every payout?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core principle
A timeout is an unknown outcome, not a failure. The design aims for at-least-once delivery made safe by idempotency, plus reconciliation as a backstop. The invariant to state up front:
Every courier is paid the correct amount, exactly once, eventually, even if the processor is down for hours.
A late payout creates a support ticket. A duplicate payout loses money and is hard to recover. So correctness beats latency.
Assumptions
- Roughly 1M couriers and 5M payout requests per day: about 60/s average, around 1,000/s at peak (weekly batch, instant cash-out spikes).
- The processor supports idempotency keys and keeps them for a bounded time (say 24h to 30d). That window caps how long I can blindly resubmit.
- Weekly payouts tolerate hours of delay. Instant cash-out expects feedback within a few seconds.
Data model
A payouts table is the source of truth: payout_id, a unique deterministic idempotency_key (for example a hash of courier, pay period and payout type), amount and currency (immutable), status, attempt_count, next_attempt_at, last_error, processor_ref, and a version column.
Statuses: PENDING → SUBMITTING → SUBMITTED → PAID, with side states FAILED, UNKNOWN, NEEDS_REVIEW.
The deterministic key means that if the calculator is re-run, the unique constraint rejects a second row for the same obligation.
Architecture
- The calculator inserts the payout and an outbox row in one DB transaction. This avoids committing a payout that is never enqueued, or enqueuing one that was not committed.
- A relay publishes outbox rows to a queue (Kafka or SQS).
- Stateless workers claim a payout with a conditional update (
status IN ('PENDING','UNKNOWN')and version match), so two workers cannot own the same payout, then call the processor through a circuit breaker. - Processor webhooks update status. A reconciler audits everything.
- Failures go to delayed-retry tiers and ultimately a dead-letter queue.
Idempotency at two layers
- Our layer: the unique key prevents duplicate creation; the conditional claim prevents concurrent submission.
- Processor layer: send the same idempotency key on every attempt for a given payout. After a timeout, a retry returns the original result rather than paying again.
If a request was sent and the connection died, mark the payout UNKNOWN, not FAILED. Resolve it by retrying with the same key or by querying the processor by key or reference. Never mint a new key for a retry; that defeats the mechanism. If your retry horizon exceeds the processor's key retention, look the transfer up before resubmitting.
Retry policy
Classify first:
| Class | Examples | Action |
|---|---|---|
| Retryable | timeouts, 5xx, 429, connection errors | retry, honor Retry-After |
| Non-retryable | invalid account, insufficient platform balance, compliance block | FAILED or NEEDS_REVIEW, notify, no retry |
| Ambiguous | timeout after sending | UNKNOWN, same-key retry or status lookup |
Use exponential backoff with full jitter: delay = random(0, min(cap, base * 2^attempt)), base about 1s, cap a few minutes. Jitter stops workers retrying in lockstep against a recovering service. Bound retries per payout (for example 5 attempts or 24h) and add a global retry budget (retries at most about 10% of traffic) so retries do not amplify the outage.
Sync vs. async
- Scheduled payouts: always async. Write rows, let the queue drain at a controlled rate. No one is waiting.
- Instant cash-out: try once, plus at most one quick retry, within a 2-3s budget. If it succeeds, show "Sent". Otherwise return
202with "Processing, we'll notify you" and continue on the async path.
Rule of thumb: retry in-request only if the total time fits the caller's budget and the call is idempotent. Never make the user wait through long backoff, and never tell them to tap again. Even if they do, the key protects against duplicates.
Circuit breaker and fallback
Open the breaker when, say, the error rate exceeds 50% over 30s with a minimum of 100 requests.
- Open: fail fast, do not call the processor, leave payouts
PENDINGand pause or delay consumption. - Half-open: after a cool-down, send a trickle of probes, close on success.
Fallback behavior: keep accepting and persisting payout requests, tell couriers "Payout delayed, your earnings are safe" with an estimate, and disable or relabel instant cash-out. If a secondary processor exists, route only payouts that were definitively never submitted. Do not fail over UNKNOWN payouts until resolved, or you risk paying twice across two providers. On recovery, ramp consumption gradually rather than releasing the whole backlog at once.
Queue and dead-letter handling
The queue absorbs the outage: the backlog grows instead of requests being lost. Use tiered delayed retries (for example 1m, 10m, 1h). Workers are safe to crash and redeliver because claims are conditional and calls are idempotent.
Messages that exhaust retries, or hit non-retryable errors, go to a DLQ with the payout ID, error history and context. Ops tooling lets a human inspect, fix (for example a bad bank account), and replay or cancel. Alert on DLQ growth and age, since each item is a courier not being paid.
Reconciliation
Because retries and webhooks can be lost or reordered, run a reconciler (hourly and daily) comparing the payouts table to the processor's reports or settlement files:
- Our
SUBMITTEDorUNKNOWNbut processor shows paid: markPAID. - Processor has no record and the payout is old: safely resubmit with the same key, or after a lookup if the key has expired.
- Processor has a payment we have no record of, or amounts differ: raise to
NEEDS_REVIEW.
After an outage, specifically sweep everything stuck in SUBMITTING or UNKNOWN first.
Monitoring and alerting
- Success rate, latency percentiles and error mix per processor endpoint.
- Breaker state changes, queue depth and oldest-message age, retry rate against budget.
- Count and age of payouts in
UNKNOWN,NEEDS_REVIEWand DLQ. - Reconciliation discrepancy counts, and an alert on any duplicate-payout detection.
- Page on breaker open beyond N minutes, oldest-pending exceeding the payout SLA, or any mismatch involving money. Ticket-level alerts for slow drift.
Common mistakes
- Treating a timeout as failure and retrying with a new key (double payment).
- "Retry three times" with no jitter, budget, or classification.
- Making the user wait on long retries or inviting resubmission.
- Failing over to a second processor with unresolved
UNKNOWNpayouts. - Skipping reconciliation, assuming the queue guarantees consistency.
- Dumping the whole backlog on a processor that has just recovered.