Build a Fault-Tolerant Payment Execution Engine
System DesignModel answerLast updated
Implement a payout processor that guarantees exactly-once delivery against an unreliable ledger by persisting state and resolving ambiguous responses before retrying.
Context
A gig-worker platform needs to pay workers as soon as their jobs are marked complete. Payments flow through an internal service that calls an external ledger API. That ledger is unreliable: it can time out, return transient errors, or silently drop responses — and a double-payment is a serious compliance and trust violation.
You are responsible for implementing the core of a PayoutProcessor class that issues payment instructions to this ledger safely.
The External Ledger
The ledger client exposes two methods:
-
post_payment(idempotency_key, worker_id, amount_cents) -> LedgerResponseSubmits a payment. Returns one of:SUCCESS— the ledger recorded the payment.TRANSIENT_ERROR— the service was busy or the network dropped; it is unknown whether the ledger processed the request before the response was lost.TERMINAL_ERROR— permanent rejection (e.g., invalid or closed account); retrying will never help.
-
check_status(idempotency_key) -> LedgerStatusQueries the result of a prior submission. Returns one of:SUCCESS— the ledger has a confirmed record.NOT_FOUND— no record exists for this key; it is safe to resubmit.FAILED— the ledger processed the request and rejected it permanently.
Your Task
Implement PayoutProcessor with the interface below. Your implementation must satisfy four guarantees:
- Exactly-once payment. A worker is never paid more than once for a given payout instruction, even if
process_payoutis called multiple times or the process crashes mid-execution. - Durable intent. Every state transition is written to persistent storage before the next network call. Valid states are
PENDING,SUBMITTED(internal only),COMPLETED,FAILED_TERMINAL, andREQUIRES_RECONCILIATION. - Ambiguity resolution before retry. A
TRANSIENT_ERRORor exception does not mean the payment failed. Before retrying, always callcheck_statusto determine what actually happened. - Bounded retries. If the ledger remains unreachable after
max_retriesattempts, mark the payoutREQUIRES_RECONCILIATIONso an engineer or background job can inspect it safely. Never loop indefinitely.
Interface
from enum import Enum
from typing import Optional
class PayoutStatus(Enum):
PENDING = "PENDING"
COMPLETED = "COMPLETED"
FAILED_TERMINAL = "FAILED_TERMINAL"
REQUIRES_RECONCILIATION = "REQUIRES_RECONCILIATION"
class LedgerResponse(Enum):
SUCCESS = "SUCCESS"
TRANSIENT_ERROR = "TRANSIENT_ERROR"
TERMINAL_ERROR = "TERMINAL_ERROR"
class LedgerStatus(Enum):
SUCCESS = "SUCCESS"
NOT_FOUND = "NOT_FOUND"
FAILED = "FAILED"
class PayoutProcessor:
def __init__(self, ledger_client, store, max_retries: int = 3):
"""
ledger_client:
post_payment(idempotency_key: str, worker_id: str, amount_cents: int) -> LedgerResponse
check_status(idempotency_key: str) -> LedgerStatus
store:
get_payout(payout_id: str) -> Optional[dict]
save_payout(payout_id: str, data: dict) -> None # synchronous, durable
"""
pass
def process_payout(self, payout_id: str, worker_id: str, amount_cents: int) -> PayoutStatus:
pass
Constraints
amount_cents > 0- Each
payout_iduniquely identifies one payment intent globally. - The idempotency key sent to the ledger must be derived deterministically from
payout_id(e.g.,f"pay_{payout_id}"). store.save_payoutis synchronous and durable (treat it as a database write).- The total number of
post_paymentcalls for a single payout must not exceedmax_retries + 1.
Example Scenario
# Transient failure on first attempt, ledger actually succeeded
1. save_payout(payout_id, status=PENDING) # durable intent
2. post_payment(...) -> TRANSIENT_ERROR # outcome unknown
3. check_status(...) -> SUCCESS # ledger has the record
4. save_payout(payout_id, status=COMPLETED)
→ returns PayoutStatus.COMPLETED
Your answer should cover: the state-machine design and why each state exists, how you guarantee no duplicate payments, how you handle crash recovery, and a walkthrough of the complete implementation.
Hints
Hint 1
A TRANSIENT_ERROR is not a failure — it is a question mark. Your code should never retry without first asking the ledger what actually happened via check_status. Map every possible check_status response to a concrete next action before writing a single retry loop.
Hint 2
Durability ordering matters. Write PENDING to the store before the first network call. Write SUBMITTED (and increment your attempt counter) before each post_payment call. A crash at any point must leave the record in a state that lets the next run proceed correctly without double-paying.
Hint 3
Think through re-entry: what happens if process_payout is called a second time on an already-SUBMITTED record? On a COMPLETED record? On a record with a conflicting worker_id or amount? Each case needs an explicit code path, not a fallthrough.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Insight
The danger in this problem is ambiguity, not failure. A TRANSIENT_ERROR — or a network exception that prevents any response from arriving — does not mean the payment was rejected. The ledger may have processed it and then lost the connection on the way back. A naive "retry on error" loop pays the worker twice.
Three mechanisms eliminate that risk when combined:
- Write before you act. Persist intent to durable storage before any network call. If the process crashes, the next invocation can reconstruct what happened.
- One deterministic idempotency key per payout. Every attempt for the same
payout_idusespay_{payout_id}. Even if you resubmit, the ledger deduplicates on its side. - Probe before retry. After any ambiguous outcome, call
check_status. Only resubmit if the ledger confirmsNOT_FOUND.
State Machine
PENDING → SUBMITTED → COMPLETED
→ FAILED_TERMINAL
→ REQUIRES_RECONCILIATION
PENDING: record exists, nopost_paymentcall has been made yet.SUBMITTED(internal, not returned to callers): apost_paymentcall was made; outcome may or may not be known.COMPLETED,FAILED_TERMINAL,REQUIRES_RECONCILIATION: terminal states. Once reached, re-entry returns immediately without any network call.
The attempt counter is persisted alongside the state. This prevents a crash-and-restart from resetting the retry budget and making more than max_retries + 1 total attempts.
Handling Each Outcome
post_payment result | check_status result | Action |
|---|---|---|
SUCCESS | — | Mark COMPLETED. Done. |
TERMINAL_ERROR | — | Mark FAILED_TERMINAL. Done. |
TRANSIENT_ERROR or exception | SUCCESS | Mark COMPLETED. Do not resubmit. |
TRANSIENT_ERROR or exception | FAILED | Mark FAILED_TERMINAL. Do not resubmit. |
TRANSIENT_ERROR or exception | NOT_FOUND | Safe to retry if budget remains, else REQUIRES_RECONCILIATION. |
TRANSIENT_ERROR or exception | probe also fails | Mark REQUIRES_RECONCILIATION. Cannot resolve ambiguity. |
Implementation
import time
from enum import Enum
from typing import Optional
class PayoutStatus(Enum):
PENDING = "PENDING"
COMPLETED = "COMPLETED"
FAILED_TERMINAL = "FAILED_TERMINAL"
REQUIRES_RECONCILIATION = "REQUIRES_RECONCILIATION"
class LedgerResponse(Enum):
SUCCESS = "SUCCESS"
TRANSIENT_ERROR = "TRANSIENT_ERROR"
TERMINAL_ERROR = "TERMINAL_ERROR"
class LedgerStatus(Enum):
SUCCESS = "SUCCESS"
NOT_FOUND = "NOT_FOUND"
FAILED = "FAILED"
_SUBMITTED = "SUBMITTED" # internal persisted state only
_TERMINAL = {
PayoutStatus.COMPLETED.value,
PayoutStatus.FAILED_TERMINAL.value,
PayoutStatus.REQUIRES_RECONCILIATION.value,
}
class PayoutProcessor:
def __init__(self, ledger_client, store, max_retries: int = 3,
backoff_base_s: float = 0.0, _sleep=time.sleep):
if max_retries < 0:
raise ValueError("max_retries must be >= 0")
self.ledger = ledger_client
self.store = store
self.max_retries = max_retries
self.backoff_base_s = backoff_base_s
self._sleep = _sleep
# ------------------------------------------------------------------
# Public entry point
# ------------------------------------------------------------------
def process_payout(self, payout_id: str, worker_id: str,
amount_cents: int) -> PayoutStatus:
if amount_cents <= 0:
raise ValueError("amount_cents must be positive")
record = self.store.get_payout(payout_id)
if record is None:
record = {
"payout_id": payout_id,
"worker_id": worker_id,
"amount_cents": amount_cents,
"idempotency_key": f"pay_{payout_id}",
"status": PayoutStatus.PENDING.value,
"attempts": 0,
}
self._save(payout_id, record) # durable before any network I/O
else:
self._assert_no_conflict(payout_id, record, worker_id, amount_cents)
if record["status"] in _TERMINAL:
return PayoutStatus(record["status"])
if record["status"] == _SUBMITTED:
# Crashed after post_payment but before recording the outcome.
# Probe first; never blindly resubmit.
resolved = self._probe(record["idempotency_key"])
if resolved is not None:
return self._finalize(payout_id, record, resolved)
# Probe failed too — ambiguity unresolved.
return self._finalize(
payout_id, record, PayoutStatus.REQUIRES_RECONCILIATION)
return self._attempt_loop(payout_id, record)
# ------------------------------------------------------------------
# Retry loop
# ------------------------------------------------------------------
def _attempt_loop(self, payout_id: str, record: dict) -> PayoutStatus:
key = record["idempotency_key"]
max_attempts = self.max_retries + 1
while record["attempts"] < max_attempts:
# Persist the attempt count and SUBMITTED state BEFORE posting.
record["attempts"] += 1
record["status"] = _SUBMITTED
self._save(payout_id, record)
# Optional exponential backoff on retries (first attempt skipped).
if record["attempts"] > 1 and self.backoff_base_s > 0:
self._sleep(self.backoff_base_s * (2 ** (record["attempts"] - 2)))
try:
resp = self.ledger.post_payment(
key, record["worker_id"], record["amount_cents"])
except Exception:
# Any exception is treated as TRANSIENT_ERROR:
# we do not know whether the ledger received the request.
resp = LedgerResponse.TRANSIENT_ERROR
if resp is LedgerResponse.SUCCESS:
return self._finalize(payout_id, record, PayoutStatus.COMPLETED)
if resp is LedgerResponse.TERMINAL_ERROR:
return self._finalize(
payout_id, record, PayoutStatus.FAILED_TERMINAL)
# Ambiguous outcome — resolve via check_status before retrying.
resolved = self._probe(key)
if resolved is not None:
return self._finalize(payout_id, record, resolved)
# resolved is None means the probe itself failed.
# Fall through to try again if budget allows, otherwise escalate.
return self._finalize(
payout_id, record, PayoutStatus.REQUIRES_RECONCILIATION)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def _probe(self, key: str) -> Optional[PayoutStatus]:
"""
Calls check_status and maps the result to a terminal PayoutStatus,
or returns None if the probe itself raised or returned an unknown value.
"""
try:
status = self.ledger.check_status(key)
except Exception:
return None # cannot resolve ambiguity
if status is LedgerStatus.SUCCESS:
return PayoutStatus.COMPLETED
if status is LedgerStatus.FAILED:
return PayoutStatus.FAILED_TERMINAL
if status is LedgerStatus.NOT_FOUND:
return None # safe to retry; caller decides whether budget remains
return None # unknown value: treat conservatively
def _finalize(self, payout_id: str, record: dict,
outcome: PayoutStatus) -> PayoutStatus:
record["status"] = outcome.value
self._save(payout_id, record)
return outcome
def _save(self, payout_id: str, record: dict) -> None:
self.store.save_payout(payout_id, record)
@staticmethod
def _assert_no_conflict(payout_id, record, worker_id, amount_cents):
if record["worker_id"] != worker_id or record["amount_cents"] != amount_cents:
raise ValueError(
f"Conflicting instruction for payout {payout_id}: "
f"stored ({record['worker_id']}, {record['amount_cents']}) "
f"vs received ({worker_id}, {amount_cents})"
)
Why This Is Correct
No duplicate payments. post_payment is only called again after check_status returns NOT_FOUND, confirming the ledger has no record for this key. The shared idempotency key provides a second layer of protection even if two calls race.
Crash safety. The write ordering guarantees that after any crash, the record is either PENDING (nothing was sent) or SUBMITTED (something may have been sent). Both cases are handled on re-entry: PENDING falls into the attempt loop; SUBMITTED probes first.
Bounded execution. The attempt counter is persisted before each post_payment. A process restart cannot reset it. The loop exits after at most max_retries + 1 posts.
Complexity
- Time: O(R) where R =
max_retries. Each iteration makes at most two ledger calls and two store writes. - Space: O(1). The record is a fixed-size dict regardless of retry count.
Common Mistakes
- Retrying on
TRANSIENT_ERRORwithout probing. This is the core error the problem is designed to catch. - Not persisting
SUBMITTEDbefore the network call. Without this, a crash between the call and saving the result leaves the system with no knowledge that a post may have gone out. - Resetting the attempt counter on restart. Allows more than
max_retries + 1total calls across process restarts. - Treating
check_statusfailures asNOT_FOUND. If you cannot confirm safety, escalate — never assume it is safe to repost. - Silently accepting conflicting payout instructions. If the same
payout_idarrives with a different amount or worker, raise immediately. Ignoring this hides upstream bugs and could result in paying the wrong amount.