KatInterview

Making External Payment Integration Resilient to Retries and Network Drops

System DesignModel answer
MediumModel answerSystem Designsystem-designdistributed-systemsidempotency

Last updated

Analyze a buggy payment handler, explain why database transactions fail to solve distributed state issues, and design a resilient flow using idempotency and background reconciliation.

Consider the following ticket checkout handler used by an e-commerce platform. A client application calls this endpoint when a user attempts to complete a purchase. If the request times out (after 10 seconds) or returns a 5xx server error, the client automatically retries the operation once.

def process_checkout(user_id: str, event_id: str, quantity: int, price_per_ticket: int) -> dict:
    total_amount = quantity * price_per_ticket
    receipt = payment_gateway.charge(user_id, total_amount)  # Remote API call over HTTPS
    db.orders.insert({                                         # Single write to PostgreSQL
        "user_id": user_id,
        "event_id": event_id,
        "quantity": quantity,
        "total_amount": total_amount,
        "receipt_id": receipt,
    })
    return {"status": "success", "receipt_id": receipt}

Assume payment_gateway.charge interacts with an external payment provider to execute a financial charge and returns a transaction identifier upon success. If a known error occurs, it raises an exception. db.orders.insert persists a single record in the local database.

Answer the following three parts:

Part 1: Failure Point Analysis

Analyze the step-by-step execution path. Identify every point where a process crash, network interruption, or database error could occur. For each failure scenario, describe:

  1. The state of the customer's payment balance/card.
  2. The state of the local orders table.
  3. What happens when the client application issues an automatic retry.

Part 2: Evaluation of Database Transactions

A software engineer suggests wrapping both the payment gateway call and the database insert inside a standard database transaction block (e.g., BEGIN ... COMMIT). Explain why this solution is inadequate and what new problems it introduces.

Part 3: Architecture Redesign

Redesign the checkout flow—including API contracts, database schema, and supporting infrastructure—to guarantee that:

  • A user is never double-billed for a single intent to purchase, regardless of network failures, duplicate requests, or system crashes.
  • Every successful payment is eventually matched with an order record in the database.
  • The client app receives a clear, accurate response even when the payment status is temporarily uncertain.

State any technical capabilities you require from the external payment gateway.