KatInterview

Harden a Two-Step Charge-and-Record Payment Flow

System DesignModel answer
MediumModel answerSystem Designidempotencydistributed-systemspayments

Last updated

Diagnose every failure mode in a naive charge-then-write endpoint, then redesign it to survive crashes, timeouts, retries, and concurrent duplicates.

Hardening a Two-Step Charge-and-Record Payment Flow

Your team owns a payment endpoint that does two things in sequence: it asks an external payment processor to collect money from a customer, then records that payment in the application's own database. The current implementation looks roughly like this:

def pay(order_id, user_id, amount):
    charge = processor.charge(user_id, amount)   # outbound HTTP call
    db.insert_payment(order_id, user_id, amount, charge.id, status="paid")
    return {"status": "paid"}

The processor supports three things you can rely on:

  • An idempotency key on charge requests, so the same key sent twice does not produce a second charge.
  • A status lookup endpoint that lets you query the outcome of a prior charge by its key.
  • Webhooks that push the final result of a charge to your server asynchronously.

Always confirm what a real processor actually offers before depending on any of these in production.


Clarifying questions to consider before answering

Before designing a solution, think through:

  • Who can retry a timed-out request — the client, your server, or both?
  • Can a charge land in a "pending" state, or does every call resolve to success or decline immediately?
  • How long does the processor remember an idempotency key, and what does it return on a duplicate submission?
  • Does one order always map to exactly one charge attempt?

Part 1 — Enumerate the failure modes

Walk through every way the code above can fail. For each failure, describe the resulting state: what happened to the customer's money, and what is (or is not) in your database.

Your answer should address:

  • What happens when the process crashes or the network times out between the processor call and the database write
  • What happens when the exact same payment is submitted twice — by the client retrying, by the server retrying, or both happening at once
  • Why wrapping both steps in a local database transaction does not solve the problem

Part 2 — Make the operation retry-safe

Redesign the flow so that any number of retries of the same payment — whether they originate from the client, the server, or a load balancer — never produce a second charge or a duplicate database record.

Your answer should address:

  • Where the payment attempt identity comes from, who generates it, and how long it should be retained
  • How the server recognises a duplicate request, including two identical requests that arrive simultaneously
  • How the idempotency key is threaded through to the processor call

Part 3 — Guarantee every charge is eventually resolved

Some charge attempts will end in an unknown state: the server crashed mid-flight, the processor call timed out with no response, or the webhook never arrived. Redesign the flow so that no charge attempt can get permanently stuck, and explain how each unknown outcome is eventually resolved.

Your answer should address:

  • The full set of states a payment record can be in, and which transitions between them are valid
  • Every path by which a non-final payment gets resolved, who is responsible for each path, and the time bound on resolution
  • How the system behaves when the same result arrives more than once, or when results arrive out of order

Part 4 — Place the lock correctly

At any given moment, a client retry, an inbound webhook, and a background recovery job might all try to act on the same payment record. Describe where you would put a lock, at what granularity, and whether it should be held while the outbound processor call is in flight.

Your answer should address:

  • What actually requires mutual exclusion and what does not
  • The concrete cost of holding a lock or an open database transaction across a network call
  • Techniques that achieve the same safety guarantee without a long-held lock

Hints

Hint 1

Start by asking what the possible outcomes of `processor.charge()` are — not just success and failure, but also the case where you genuinely do not know what happened. That third outcome is the root of most of the hard problems here.

Hint 2

An idempotency key only works if it is generated before the outbound call and stored durably before anything else. Think about what needs to exist in your database before the processor is ever contacted.

Hint 3

Separate the question of mutual exclusion from the question of durability. You can keep critical sections very short by using optimistic concurrency or conditional database updates instead of holding a lock across the network call.