KatInterview

Build a Fault-Tolerant Payment Execution Engine

System DesignModel answer
MediumModel answerSystem Designidempotencyfault-tolerancedistributed-systems

Last 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) -> LedgerResponse Submits 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) -> LedgerStatus Queries 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:

  1. Exactly-once payment. A worker is never paid more than once for a given payout instruction, even if process_payout is called multiple times or the process crashes mid-execution.
  2. 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, and REQUIRES_RECONCILIATION.
  3. Ambiguity resolution before retry. A TRANSIENT_ERROR or exception does not mean the payment failed. Before retrying, always call check_status to determine what actually happened.
  4. Bounded retries. If the ledger remains unreachable after max_retries attempts, mark the payout REQUIRES_RECONCILIATION so 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_id uniquely 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_payout is synchronous and durable (treat it as a database write).
  • The total number of post_payment calls for a single payout must not exceed max_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.