Designing a Fault-Tolerant Courier Payout Pipeline
System DesignModel answerLast updated
Design the hand-off from a courier pay calculation to an external payment service so every courier is paid the correct amount exactly once, even through outages and ambiguous timeouts.
A delivery marketplace calculates earnings for its couriers from order events. Earnings accrue per minute, scaled by how many orders the courier has in progress at that moment, and minutes in peak periods are paid at double the rate. Once an amount has been calculated, the platform calls a separate payment service to move the money to the courier.
The calculation logic is already written. You are now asked: what happens if the payment service is down or behaving badly?
Design the hand-off between the pay calculation and the payout so that every courier is eventually paid the correct amount, exactly once, even during outages, slow responses, and ambiguous failures.
In your answer, cover:
- The different ways the payment call can fail, and why they need different handling.
- What the platform stores, and when, so that no obligation is lost.
- How retries work without ever paying twice, and how you avoid overloading the payment service when it comes back.
- How you detect and repair mismatches between your records and the payment service's records.
- What couriers see in the app and how operators learn that payouts are stuck.
State any assumptions you make. Good questions to raise: how often couriers are paid (per order, daily, weekly, instant cash-out), whether the payment service supports idempotency keys and status lookup, how much delay is tolerable, and whether the service is internal or a third party with rate limits.
Hints
Hint 1
Separate three outcomes of a payment call: a definite failure, a definite success, and a timeout where you do not know what happened. The third one is the dangerous one for double payment.
Hint 2
Write the amount owed to your own database before calling the payment service, give it a stable unique identifier, and send that identifier with every attempt so the receiver can recognize repeats.
Hint 3
Think about what happens when the service returns after hours of downtime: thousands of queued payouts retry at once. Consider backoff with jitter, a circuit breaker, and a rate-limited drain. Also plan a periodic reconciliation job as the safety net.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Payouts are batched per courier (for example daily) plus an optional instant cash-out. The design works for either.
- The payment service is a separate system, possibly third party. I will ask whether it supports idempotency keys and status lookup. If it does not, I add a wrapper or rely more heavily on reconciliation.
- Delay of hours is acceptable, but lost or duplicated money is not.
What can go wrong
- Definite failure (connection refused, 503, validation error). Nothing was paid. Transient errors can be retried. Permanent errors (invalid bank account) go to a manual or courier-action queue.
- Timeout or dropped connection (unknown outcome). The service may have paid and failed to reply. Blindly retrying risks a double payment. Not retrying risks a missed payment. This is the core problem.
- Slow responses. These tie up threads and can cascade into the pay pipeline itself unless bounded.
- Crash on our side between "calculated" and "called" or between "called" and "recorded". Without durable state we lose or repeat work.
Core design
Decouple calculation from payment with a durable ledger and outbox.
- The pay calculation writes a
payoutrow in the same transaction as its result:payout_id(a UUID or deterministic key such ascourier_id + pay_period),courier_id,amount,currency,status,attempt_count,next_attempt_at,created_at,provider_ref. - Initial status is
PENDING. The calculation never calls the payment service directly, so an outage cannot block or lose it. - A separate payout worker polls (or consumes from a queue fed by the outbox) rows that are
PENDINGand due, and calls the payment service.
Deterministic key. The idempotency key is the payout_id, created once and reused on every retry. A unique constraint on (courier_id, pay_period) prevents the calculation from creating two obligations for the same period if it reruns.
State machine: PENDING -> IN_FLIGHT -> SUCCEEDED | FAILED_RETRYABLE | FAILED_PERMANENT | UNKNOWN. Mark IN_FLIGHT before calling, using a lease (compare-and-set with a timeout) so only one worker handles a payout at a time and a crashed worker's lease expires.
Retries without double payment
- Idempotency key on every call. If the service supports it, retrying with the same key returns the original result instead of paying again.
- Unknown outcomes: on timeout, set
UNKNOWN, notFAILED. Before retrying, query the payment service by key. If it reports success, record it. If it reports not found, retry. If it has no lookup and no idempotency support, do not auto-retry; leave it to reconciliation. - Backoff: exponential with jitter (for example 1 min, 2, 4, up to a cap of an hour or so), with a maximum attempt count before escalating to an operator.
- Record success atomically: update status and
provider_refin one transaction. If we crash after a successful call but before recording it, the next attempt with the same key is harmless.
Protecting the service on recovery
- Circuit breaker: after N consecutive failures or timeouts, stop sending for a cool-down period, then probe with a single request (half-open).
- Rate-limited drain: the worker pool has a fixed concurrency and requests-per-second cap, so a backlog of, say, 200k payouts drains steadily rather than as a thundering herd. At 200 per second this takes about 17 minutes.
- Jitter on
next_attempt_atprevents synchronized retries. - Timeouts: short per-call timeouts (a few seconds) so a slow dependency does not exhaust workers.
- Prioritization: older payouts first, or instant cash-outs ahead of batch, so courier-visible delays are minimized.
Reconciliation
Retries handle the common cases, but reconciliation is the safety net.
- Periodic job (hourly, plus a daily full pass): compare our payouts against the payment service's report or API for the same window.
- Cases: we say
SUCCEEDED, they have nothing (alert, investigate); they say paid, we sayPENDING/UNKNOWN(mark succeeded, stop retries); amounts differ (alert); duplicate payments for one key (alert and claw back or offset in the next period). - Invariant checks: the sum of paid amounts per courier and period must equal the calculated earnings. Verify this independently of the payout flow.
- Keep the ledger append-only. Corrections are new adjustment entries, never edits.
What couriers and operators see
Couriers: the app shows earnings as "calculated" and the payout as "pending" with an expected date, not an error. Once the outage is long (for example over 24 hours), show a short message that payment is delayed and will arrive automatically. Never show a failed state for something we will retry. Permanent failures prompt an action (update bank details).
Operators:
- Metrics: count and total value of payouts by status, age of the oldest pending payout, retry rate, error rate by type, circuit breaker state, and reconciliation mismatches.
- Alerts: oldest pending older than the SLA, UNKNOWN count above a threshold, any reconciliation mismatch, payouts exhausting retries.
- A dead-letter or manual queue with tooling to retry, cancel, or adjust safely (still going through the idempotent path).
Trade-offs
- Exactly-once is really at-least-once delivery plus idempotent processing. We cannot get it from the network, so we build it from keys, state, and reconciliation.
- Batching reduces call volume but increases the blast radius of one failure. Per-payout calls give finer retries but more load.
- Strict "no auto-retry on unknown" is safer for money but slower to resolve; lookup-by-key makes it both safe and fast.
- A queue (Kafka, SQS) adds throughput and decoupling, but the database remains the source of truth.
Common mistakes
- Calling the payment service inline from the calculation, so an outage loses or blocks pay.
- Generating a new idempotency key per retry, which defeats the purpose.
- Treating a timeout as a failure and retrying blindly.
- Marking success only in memory or after a non-atomic step.
- Retrying with no backoff or cap, hammering a recovering service.
- Having no reconciliation, so silent mismatches persist.
- Showing couriers a scary error or zero balance during a delay.