Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 30 of 44

Case study: design a payment system

A senior-level walkthrough of a payment system: how card payments really flow, tokens and PCI scope, idempotency and the unknown outcome, order-independent webhooks, reconciliation, provider routing and failure modes, with tested C#.

Case studyApplied33 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 3 data models
  • 2 API designs
  • 5 code samples
  • 10 interviewer follow-ups
  • 4 self-checks

Read first: A framework for system design interviews, API design, Queues and asynchronous work

By the end you will be able to
  • A payment crosses several parties and settles days later, so the design is a state machine, a ledger and a reconciliation loop, and not a single charge call.
  • A timeout is not a failure, it is an unknown. Send an idempotency key, record the payment as unknown and resolve it by asking the provider. Naive retries double-charged 607 of 20,000 payments and the careful design none.
  • Treat webhooks as facts that arrive late, twice and out of order. Keep them in a set and derive the state, so every delivery order ends in the same place.
  • Reconciliation is the safety net. Compare your records with the provider's settlement file and classify every break, such as a double charge or money taken that you recorded as failed.
  • Keep card numbers off your servers with tokens, route across providers only after unknown outcomes are resolved, and prepare the senior answers on refunds, outages and audits.

5 code samples (195 lines), collapsed so the explanation stays in focus.

A payment looks like one call: charge this card. In reality it is an agreement between half a dozen parties that settles days later, over networks that time out, under a rule that nobody forgives a lost payment or a double one. Most of the engineering is not in the happy path. It is in the answer that never comes back, the notification that arrives twice, and the report from the bank that disagrees with your database.

This lesson builds the design around those problems and tests each one in C#: a provider that times out in nasty ways, a service that must not charge twice, webhooks delivered in every order, and a reconciliation job that finds what the design missed. It builds on API design for idempotency and on queues and async work for retries. The books that record where the money went are the subject of the next lesson, designing a ledger and a wallet.

HLD

Clarify the problem

Spend the first minutes on questions. Each answer changes the design.

AskWhy it matters
Are we the merchant, the payment provider itself, or a platform that pays out to sellers?A merchant integrates with providers. A provider builds the connections to banks and card networks. A platform also moves money between parties
Which methods: cards, bank transfers, wallets, buy now pay later?They differ in speed, reversibility and who can dispute. Cards can be disputed for months
One step (charge now) or two (authorize now, capture later)?Hotels, marketplaces and shipped goods authorize first and capture when they fulfil
Which currencies and countries?Decimals differ by currency, and local methods and regulation differ by country
Are refunds, disputes, subscriptions and payouts in scope?Each adds states, ledger entries and timelines
Do our servers ever see card numbers?This decides the compliance burden. The answer should be no
What must never happen?A lost payment, a double charge, a payment recorded with no money, or money with no record

A good scope for 45 minutes: a service that takes card payments through external providers, records every step, supports capture and refunds, receives asynchronous notifications and reconciles against the provider's reports. Mention fraud, subscriptions and payouts as extensions.

HLD

How a card payment really flows

Five parties stand behind a card payment: the cardholder, the merchant (your system), the provider or gateway that you call, the acquirer (the merchant's bank, often run by the provider), the card network and the issuer (the cardholder's bank). You talk only to the provider, and the rest happens behind it.

StepWhat happensWhen money moves
AuthorizationThe provider asks the issuer, through the network, whether the card can pay this amount. The issuer approves and places a hold on the cardholder's fundsNone yet. The hold expires after some days if nothing follows
CaptureThe merchant tells the provider to take the held amount, now or later. A one-step payment does both at onceStill none. Captured payments are queued for settlement
Clearing and settlementCaptured payments are batched and exchanged between banksThe merchant's bank account is credited in one to three days, minus fees
RefundA new transaction that sends money backDays later. Fees are often not returned
Dispute (chargeback)The cardholder tells the issuer something is wrong, and the issuer takes the money back pending evidenceWeeks or months after the sale

The point to carry from the table: the money moves later and in batches, so your system holds claims ("we captured 50.00 for order 881") and matches them against reality when the settlement arrives. Reconciliation is part of the domain, not an extra.

HLD

Estimate: modest rates, no room for error

State assumptions out loud. They are illustrative and the interviewer may change them.

Example · estimate
payments:    10M a day (assumed) = ~115 a second, ~600 at peak (x5)
provider:    each charge waits ~0.3 to 2 s on the provider
in flight:   600 x 2 s = ~1,200 charges waiting at the peak
rows:        ~3 KB a payment with attempts and events = ~30 GB a day
ledger:      ~4 entries a payment = ~40M entries a day
webhooks:    ~3 events a payment = ~350 a second on average
unknown:     ~5% time out = ~500,000 payments a day to resolve

Five conclusions:

  1. Throughput is modest and correctness is the problem. Six hundred a second is small. A mistake costs money and trust, so every decision favours exactness over speed.
  2. Latency belongs to the provider. Little's law says about 1,200 calls are waiting at the peak, so the service must not hold a database transaction or a thread while it waits.
  3. The recovery path is a main path. If about 5% of calls end in an unknown outcome (the simulation below uses 2% plus 3%), half a million payments a day need resolving. Design it as a first-class flow.
  4. Everything is history. Payments, attempts, events and ledger entries are append-only, because an auditor will ask what happened, in order.
  5. Money arrives later, so reconcile daily. The provider's report is the second set of books.

LLD

The contract and the data model

CallWho calls itMeaning
POST /v1/paymentsMerchant backend or checkoutCreate and (usually) capture a payment. The idempotency key is required
POST /v1/payments/{id}/captureMerchant backendCapture an authorized payment, fully or in part
POST /v1/payments/{id}/refundsMerchant backendRefund all or part of a captured payment
GET /v1/payments/{id}Merchant backendThe current state, as a fallback to webhooks
POST /v1/webhooks/{provider}ProvidersAsynchronous events, verified before anything else
POST/v1/payments
auth
merchant API key
idempotency
Idempotency-Key header, required and kept for at least 24 hours, a repeat returns the first result
body
{ "amount": 5000, "currency": "USD", "payment_method": "pm_card_9f2", "capture": true, "order_id": "ord_881" }
note
the amount is an integer in the currency's smallest unit (5000 is 50.00 in dollars), never a float
  • 201created, returns { "id": "pay_77c", "status": "succeeded" }, or "requires_action" when the bank asks the customer to confirm
  • 202accepted but the outcome is not known yet, returns "processing" and the result arrives as a webhook
  • 402declined, returns a reason code the caller can act on
  • 409the same key was reused with different parameters
POST/v1/payments/{id}/refunds
auth
merchant API key
idempotency
Idempotency-Key header, required
body
{ "amount": 2000, "reason": "requested_by_customer" }
  • 201created, returns { "id": "re_31a", "status": "pending" }
  • 409the refund would exceed what was captured and not yet refunded
paymentsSQL, sharded by merchant
  • idtext

    PK
  • merchant_idtext

    INDEXSHARD KEY
  • idempotency_keytext

    unique per merchant, stored with a hash of the request body to detect reuse

    UNIQUE
  • amountbigint

    in the currency's smallest unit

  • currencytext

    an ISO 4217 code such as USD or JPY

  • statetext

    created, requires_action, processing, succeeded, failed or canceled

  • capturedbigint

    amount captured so far

  • refundedbigint

    amount refunded so far

  • providertext

    NULL
  • provider_reftext

    the provider's charge id, once known

    NULLINDEX
  • versionint

    every change is a conditional update on (id, version)

  • created_attimestamptz

The row exists before the first call to a provider. It is the anchor everything else hangs from.

payment_attemptsSQL
  • idtext

    PK
  • payment_idtext

    one payment can have several attempts

    FK→ payments
  • providertext

  • sent_attimestamptz

  • outcometext

    approved, declined, timeout or error

  • provider_reftext

    NULL
  • latency_msint

Append-only: an attempt is never edited, a later attempt or event supersedes it.

webhook_eventsSQL
  • event_idtext

    the provider's own id, so a repeat is a no-op

    PK
  • providertext

  • typetext

  • payment_reftext

    INDEX
  • payloadtext

    stored verbatim, for audit and replay

  • received_attimestamptz

  • processed_attimestamptz

    NULL

The receiver verifies the signature, inserts the row and answers 2xx at once. A worker does the rest.

HLD

The high-level design

Fig. Payments: write first, call out, record facts, reconcile
Fig. Payments: write first, call out, record facts, reconcile
Fig. One card payment
Fig. One card payment

Read it as a loop with three rules. Write first: the payment row, unique on the idempotency key, is committed before any provider is called, so a crash can never leave a charge with no record. Call with a key: the same key goes to the provider, so a repeat cannot charge twice. Record facts, then derive: answers and webhooks are stored as facts, and the state follows from them. The reconciliation job at the bottom of the diagram is the second set of eyes that catches what the first three rules miss.

HLD

Card numbers never touch your servers

The safest card number is one you never see. With hosted fields or a provider SDK, the browser or app sends the card details straight to the provider's vault, which returns a token (a payment method id) that stands for the card. Your servers store and send only the token. This keeps you in the lightest category of PCI DSS, the card industry's security standard, because the systems that would hold card data are the provider's. Rules that follow from it: never log a card number, never store the security code (the standard forbids keeping it after authorization), redact request bodies in logs and traces, and treat the token as sensitive anyway, because anyone who can use it can charge the card through your account. See encryption, secrets and abuse for the key handling around it.

A token is usually specific to the provider that issued it, which matters for failover: a card saved with provider A cannot simply be charged through provider B. The options are a vault you run yourself (heavy compliance), network tokens that work across providers, or accepting that saved cards fail over only to the same provider.

LLD

Deep dive: the answer that never came

A call to a provider can end four ways. The provider approves, the provider declines, the request is lost before the provider did anything, or the provider charged the card and the reply was lost on the way back. The caller sees the last two identically: nothing. The tempting code treats a timeout as a failure and tries again, and in the fourth case it charges the customer twice. The right model has three outcomes, not two: succeeded, failed and unknown.

Four rules follow:

  1. Write the payment before calling anyone, with the idempotency key unique, so that the record exists whatever happens next.
  2. Send the key to the provider. A provider that supports idempotency returns the first answer for a repeated key and charges nothing new. The payment's own id is a good key.
  3. On a timeout, mark the payment unknown. Do not retry blindly and do not tell the customer it failed ("processing" is the honest word). Resolve it by a status inquiry by your own reference: if the provider has a charge, adopt its result, and if it has nothing, retrying with the same key is safe, because even if the first request does turn up late, the key makes it one charge.
  4. Run a sweep that resolves unknown payments, and let webhooks resolve them sooner when they arrive.

The code below is a stand-in provider with those four behaviours (and a settlement file that lists what it really charged), the naive service, the careful service with its recovery sweep, and a reconciliation function that compares what the service recorded with what the provider charged.

C# · Fault, Charge, Response, …46 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum Fault { None, TimeoutBefore, TimeoutAfter, Decline }
public sealed record Charge(string ChargeId, string Ref, long Amount, string Status);
public sealed record Response(bool Received, string Status, string ChargeId);

// A stand-in for a payment provider. It supports idempotency keys (a repeated key returns the first answer and charges nothing
// new), a status inquiry by the merchant's own reference, and a settlement file listing every charge it really made.
public sealed class Provider
{
    private readonly Random _random;
    private readonly Dictionary<string, Charge> _byKey = new();
    private readonly List<Charge> _charges = new();
    public double TimeoutBeforeRate = 0.02, TimeoutAfterRate = 0.03, DeclineRate = 0.05;

    public Provider(int seed) { _random = new Random(seed); }

    private Fault Roll()
    {
        double r = _random.NextDouble();
        if (r < TimeoutBeforeRate) return Fault.TimeoutBefore;
        if (r < TimeoutBeforeRate + TimeoutAfterRate) return Fault.TimeoutAfter;
        if (r < TimeoutBeforeRate + TimeoutAfterRate + DeclineRate) return Fault.Decline;
        return Fault.None;
    }

    // `key` may be null for a client that sends no idempotency key.
    public Response Charge(string key, string reference, long amount)
    {
        if (key != null && _byKey.TryGetValue(key, out var earlier)) return new Response(true, earlier.Status, earlier.ChargeId);
        var fault = Roll();
        if (fault == Fault.TimeoutBefore) return new Response(false, null, null);               // never processed, no answer
        string status = fault == Fault.Decline ? "declined" : "succeeded";
        var charge = new Charge("ch_" + (_charges.Count + 1), reference, amount, status);
        _charges.Add(charge);
        if (key != null) _byKey[key] = charge;
        return fault == Fault.TimeoutAfter ? new Response(false, null, null) : new Response(true, status, charge.ChargeId);   // processed, but the answer is lost
    }

    // Status inquiry by the merchant's reference: what the provider actually did, regardless of what any reply said.
    public Charge Lookup(string reference) => _charges.LastOrDefault(c => c.Ref == reference && c.Status == "succeeded") ?? _charges.LastOrDefault(c => c.Ref == reference);

    public List<Charge> Settlement() => _charges.ToList();
}
C# · Payment, Break, Psp59 lines
using System;
using System.Collections.Generic;
using System.Linq;

public sealed record Payment(string Id, long Amount) { public string State = "pending"; public int Attempts; }

public enum Break { DoubleCharge, ChargedButRecordedFailed, ChargedButUnknown, RecordedButNotCharged, AmountMismatch }

public static class Psp
{
    // The naive service: on a timeout, send the charge again as a brand-new request, up to three times, then give up.
    public static void Naive(Provider provider, Payment p)
    {
        for (int attempt = 0; attempt < 3; attempt++)
        {
            p.Attempts++;
            var r = provider.Charge(null, p.Id, p.Amount);
            if (r.Received) { p.State = r.Status == "succeeded" ? "succeeded" : "failed"; return; }
        }
        p.State = "failed";                                                  // "it timed out, so it did not happen"
    }

    // The careful service: the payment id is the idempotency key, and a timeout leaves the payment unknown.
    public static void Careful(Provider provider, Payment p)
    {
        p.Attempts++;
        var r = provider.Charge(p.Id, p.Id, p.Amount);
        p.State = r.Received ? (r.Status == "succeeded" ? "succeeded" : "failed") : "unknown";
    }

    // A sweep that resolves unknown payments by asking the provider what happened, and only retries when nothing happened.
    public static void Recover(Provider provider, Payment p)
    {
        if (p.State != "unknown") return;
        var seen = provider.Lookup(p.Id);
        if (seen != null) { p.State = seen.Status == "succeeded" ? "succeeded" : "failed"; return; }
        p.Attempts++;
        var r = provider.Charge(p.Id, p.Id, p.Amount);                       // same key: safe even if the first attempt did arrive
        p.State = r.Received ? (r.Status == "succeeded" ? "succeeded" : "failed") : "unknown";
    }

    // Reconciliation: compare what we recorded with what the provider says it charged, one payment at a time.
    public static Dictionary<Break, int> Reconcile(IEnumerable<Payment> payments, List<Charge> settlement)
    {
        var breaks = Enum.GetValues<Break>().ToDictionary(b => b, _ => 0);
        var charged = settlement.Where(c => c.Status == "succeeded").GroupBy(c => c.Ref).ToDictionary(g => g.Key, g => g.ToList());
        foreach (var p in payments)
        {
            charged.TryGetValue(p.Id, out var list);
            int count = list?.Count ?? 0;
            if (count > 1) breaks[Break.DoubleCharge]++;
            else if (count == 1 && p.State == "failed") breaks[Break.ChargedButRecordedFailed]++;
            else if (count == 1 && p.State != "succeeded") breaks[Break.ChargedButUnknown]++;
            else if (count == 0 && p.State == "succeeded") breaks[Break.RecordedButNotCharged]++;
            else if (count == 1 && list[0].Amount != p.Amount) breaks[Break.AmountMismatch]++;
        }
        return breaks;
    }
}

The experiment runs 20,000 payments through a provider that loses the request 2% of the time, charges and then loses the reply 3% of the time, and declines 5%. The same seed gives both services the same provider luck. After each run, the reconciliation function compares the service's records with the provider's settlement file.

C# · 20,000 payments through a provider that times out before processing 2% of the time…31 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// 20,000 payments through a provider that times out before processing 2% of the time, after processing 3% of the time, and declines 5%.
Payment[] Make() => Enumerable.Range(0, 20_000).Select(i => new Payment("pay_" + i, 1_000 + i % 500)).ToArray();

var naiveProvider = new Provider(31);
var naive = Make();
foreach (var p in naive) Psp.Naive(naiveProvider, p);
var naiveBreaks = Psp.Reconcile(naive, naiveProvider.Settlement());

var carefulProvider = new Provider(31);
var careful = Make();
foreach (var p in careful) Psp.Careful(carefulProvider, p);
int unknownBefore = careful.Count(p => p.State == "unknown");
var carefulBeforeSweep = Psp.Reconcile(careful, carefulProvider.Settlement());
for (int sweep = 0; sweep < 5 && careful.Any(p => p.State == "unknown"); sweep++)
    foreach (var p in careful.Where(p => p.State == "unknown")) Psp.Recover(carefulProvider, p);
var carefulBreaks = Psp.Reconcile(careful, carefulProvider.Settlement());

string Show(Dictionary<Break, int> b) => string.Join(", ", b.Where(x => x.Value > 0).Select(x => $"{x.Key} {x.Value}").DefaultIfEmpty("none"));
Console.WriteLine($"naive retries:         {Show(naiveBreaks)}");
Console.WriteLine($"careful, before sweep: {unknownBefore} unknown; {Show(carefulBeforeSweep)}");
Console.WriteLine($"careful, after sweep:  {careful.Count(p => p.State == "unknown")} unknown; {Show(carefulBreaks)}");
Console.WriteLine($"succeeded {careful.Count(p => p.State == "succeeded")}, declined {careful.Count(p => p.State == "failed")}, charges at the provider {carefulProvider.Settlement().Count(c => c.Status == "succeeded")}");
Debug.Assert(naiveBreaks[Break.DoubleCharge] > 500 && naiveBreaks[Break.ChargedButRecordedFailed] > 0);
Debug.Assert(unknownBefore > 0 && carefulBeforeSweep[Break.DoubleCharge] == 0);
Debug.Assert(carefulBreaks.Values.All(v => v == 0) && careful.All(p => p.State != "unknown"));
Debug.Assert(careful.Count(p => p.State == "succeeded") == carefulProvider.Settlement().Count(c => c.Status == "succeeded"));
Naive retriesCareful: key, unknown, sweep
Customers charged twice6070
Charged, but we recorded a failure320
Unknown before the sweepnot modelled1,020, of which 640 had really been charged
After the sweep639 breaks0 unknown, 0 breaks, 18,989 succeeded and 18,989 charges at the provider

The naive service double-charged 607 of 20,000 customers, which is the 3% of first attempts that charged and lost the reply, retried as a new request. It also recorded 32 failures for payments that had in fact been charged: the first attempt charged and timed out, the retry was declined, and the last word the service heard was "declined". The careful service never sent a second charge. Its 1,020 unknown payments, 5% of the total, included 640 that had really been charged, and the sweep resolved all of them with one status inquiry each and a safe retry for the rest. At the end the number of payments recorded as succeeded equals the number of charges at the provider, to the unit.

LLD

Deep dive: webhooks arrive late, twice and out of order

Providers tell you about outcomes asynchronously: the capture settled, the refund completed, the customer opened a dispute. Delivery is at least once, so duplicates are normal, and no provider promises order, so a "captured" event can arrive before "authorized". A state machine that rejects an unexpected transition will lose information whenever the network reorders events, and one that applies each event blindly will refund twice when an event is delivered twice.

The robust design stores events as facts and computes the state from the set of facts. Adding a fact to a set is commutative (order does not matter) and idempotent (repeats do not matter), so every delivery order produces the same answer.

C# · WebhookEvent, PaymentFacts28 lines
using System;
using System.Collections.Generic;
using System.Linq;

public sealed record WebhookEvent(string Id, string Type, long Amount);

// What is known about one payment, kept as a set of facts. An event can arrive twice, late or before the one that logically
// precedes it, and the answer must not depend on that. Applying an event is a set insert, so it is commutative and idempotent.
public sealed class PaymentFacts
{
    private readonly Dictionary<string, WebhookEvent> _seen = new();

    public void Apply(WebhookEvent e) => _seen[e.Id] = e;                    // the same event id twice is one fact

    private long Max(string type) => _seen.Values.Where(e => e.Type == type).Select(e => e.Amount).DefaultIfEmpty(0).Max();
    public long Captured => Max("captured");
    public long Refunded => _seen.Values.Where(e => e.Type == "refund").Sum(e => e.Amount);

    // The state is a function of the facts, not of the order in which they were learned.
    public string State =>
        _seen.Values.Any(e => e.Type == "failed") && Captured == 0 ? "failed"
        : _seen.Values.Any(e => e.Type == "dispute_opened") ? "disputed"
        : Captured > 0 && Refunded >= Captured ? "refunded"
        : Refunded > 0 ? "partially_refunded"
        : Captured > 0 ? "captured"
        : Max("authorized") > 0 ? "authorized"
        : "created";
}
C# · The events of one payment: authorised for 50.00, captured, then refunded in two parts. A…31 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// The events of one payment: authorised for 50.00, captured, then refunded in two parts. A provider may deliver them in any order, and twice.
var events = new[]
{
    new WebhookEvent("evt_1", "authorized", 5_000), new WebhookEvent("evt_2", "captured", 5_000),
    new WebhookEvent("evt_3", "refund", 2_000), new WebhookEvent("evt_4", "refund", 3_000),
};
IEnumerable<IEnumerable<T>> Permutations<T>(IList<T> items) => items.Count <= 1 ? new[] { items } : items.SelectMany((item, i) => Permutations(items.Where((_, j) => j != i).ToList()).Select(rest => rest.Prepend(item)));

int orders = 0;
foreach (var order in Permutations(events))
{
    var facts = new PaymentFacts();
    foreach (var e in order) { facts.Apply(e); facts.Apply(e); }                 // every event delivered twice
    Debug.Assert(facts.State == "refunded" && facts.Refunded == 5_000);
    orders++;
}
Console.WriteLine($"{orders} delivery orders, each event twice: every one ends in the same state");

var early = new PaymentFacts();                                                  // the capture arrives and the authorisation never does
early.Apply(events[1]);
Debug.Assert(early.State == "captured");
early.Apply(events[2]);
Debug.Assert(early.State == "partially_refunded");
var lost = new PaymentFacts();
lost.Apply(new WebhookEvent("evt_9", "failed", 0));
Debug.Assert(lost.State == "failed");

All 24 delivery orders of the four events, each delivered twice, ended as refunded with 5,000 refunded. A capture that arrives with no authorization still yields captured, and a refund added afterwards moves it to partially_refunded, because the state is derived from what is known and does not wait for what should have come first. A strict step-by-step machine would have rejected that capture.

Operating rules for the receiver:

  • Verify first. Check the signature, the timestamp window and the event id before anything else (the verifier is in encryption, secrets and abuse), because the endpoint is public.
  • Acknowledge fast, process later. Insert the event row (the provider's event id is the primary key, so a repeat is a no-op), answer 2xx, and let a worker apply it. A slow handler makes the provider retry, which multiplies the load.
  • Store the payload verbatim, for audit and replay.
  • Do not trust the order, and do not trust webhooks alone. A poller that asks about payments stuck in processing is the fallback when an event is lost.
  • Check the amounts. An event whose amount or currency disagrees with your row is an alert, not an update.

LLD

Deep dive: reconciliation, the safety net

Reconciliation compares two independent records of the same money: yours, and the provider's settlement report (a file or an API, usually daily). It exists because every other mechanism can fail: a bug, a lost event, a manual fix in a database, a provider error. The matching function above does the core of it, joining on your reference and the provider's, and classifying each payment.

BreakWhat it meansUsual action
Charged twiceThe provider charged one payment more than onceRefund the extra charge, then find the code path that allowed it
Charged, recorded as failedThe provider has money that you believe was never takenMark it succeeded and fulfil, or refund it. Do not leave a customer charged for nothing
Charged, still unknownResolution has not run or has failedResolve by inquiry, and alert when it is old
Recorded as succeeded, not chargedYou believe you were paid and the provider says otherwiseStop fulfilment, investigate, chase
Amount mismatchAmounts differ (a partial capture, a currency conversion, a fee)Investigate, and add the missing rule if it is legitimate

In the experiment, reconciling the naive service found 639 breaks (607 charged twice and 32 recorded as failed but charged) in 20,000 payments, and the careful service none. That is the point of the safety net: it measures what the design actually does, whatever the design intended.

How to run it in practice:

  • Match on references you control (your payment id sent as the provider's metadata) and on the provider's charge id, and expect timing differences: settlement lags by one to three days, and a payment made at 23:59 UTC may appear in the next day's file.
  • Treat fees, refunds, adjustments and disputes as lines of their own, each with an expected amount, so that the daily net deposit in the bank can be explained to the cent.
  • Automate the clear cases (charged, recorded as unknown: resolve it) and queue the rest for people, with the amount at stake and the age of the break.
  • Measure it. Track the unmatched count and value and the age of the oldest break. An SLO of "no unexplained break older than three days" turns reconciliation from a chore into a control (see SLOs and error budgets).

HLD

Several providers: routing and failover

A second provider buys three things: lower cost (route each payment where the fee is lowest), a higher approval rate (providers approve different shares of cards in different countries) and resilience when one is down. A router chooses by rules and live success rates, and a circuit breaker per provider stops sending to one that is failing (see designing a notification service for breakers and failing over before the call, not after each timeout).

The danger is failing over after an unknown outcome. If provider A timed out, it may have charged the card, and sending the payment to provider B charges it twice, because B has never heard of A's idempotency key. The rules:

  • Fail over on definite failures only: the provider was down before processing, or refused the request for its own reasons. A decline from the card's issuer is an answer, not a failure, and must not be retried elsewhere.
  • Never route a payment to a second provider while its first attempt is unknown. Resolve A first by inquiry. If you must be faster, accept the rare duplicate and rely on reconciliation to find it and a refund to fix it, and say so aloud.
  • Keep one idempotency key per payment and provider, and record every attempt, so that the full story is in the data.
  • Tokens are the real constraint. A card saved with provider A cannot be charged through B without a portable token, so failover of saved cards needs a vault you control or network tokens.

HLD

Risk, 3-D Secure and disputes

Three more pieces sit around the flow, and each adds states.

  • Risk checks score a payment before it is sent (device, velocity, amount, history), by rules and a learned model. The outcome is allow, block or challenge. Card testing (a burst of tiny authorizations to find live numbers) is caught by velocity limits per card, device and address (see rate limiting).
  • 3-D Secure lets the issuer ask the customer to confirm in their bank's app. It adds a requires_action state to the payment, where the flow waits for the customer and resumes through a callback, and it can shift liability for fraud to the issuer.
  • Disputes reverse a captured payment weeks later. The issuer takes the money back at once, the merchant has a limited window to send evidence, and a disputed state with its own ledger entries (the amount and the fee) must exist. Networks watch the share of payments that are disputed, and a high share has consequences, so the metric belongs on a dashboard.

HLD

Failure modes and edge cases

CaseWhat goes wrongHandle it
A timeout after the provider chargedA retry charges again, or the payment is marked failedThe unknown state, the same key to the provider, a status inquiry, a sweep
A double click or a client retryTwo payments for one orderA unique idempotency key. The same key with different parameters is a 409
The database write fails after the provider answeredThe money moved and there is no recordThe row is written before the call. If it is still missing, reconciliation finds a charge with no record
A provider outagePayments fail, or retry storms buildA breaker per provider, routing new payments elsewhere, unknown ones resolved later
A lost, repeated or reordered webhookA wrong state, or a double refundFacts stored by event id, state derived from the set, a poller for stuck payments
A forged webhookOrders marked paid that were notSignature, timestamp and event id, and a check of the amount against your row
A tampered amountThe customer pays less than the priceThe server computes the amount from the order and checks the provider's amount against it
Concurrent refundsRefunding more than was capturedA conditional update: refunded plus the new amount must not exceed captured
Currency decimalsA yen price multiplied by 100Integer minor units and each currency's exponent (see the ledger lesson)
A payment stuck in processingA customer waits and nobody is lookingTimers on every non-final state, an alert on the age of the oldest unknown
A card number in a logA compliance breachTokens, redaction at the logging layer, scans for number patterns

Senior depth

What senior interviews ask about a payment system

Interviewer follow-upL5How do you make sure a customer is never charged twice?How to answer

Three layers. A unique idempotency key on the payment row, so a client retry returns the first result. The same key sent to the provider, so a repeated request is not charged again. And a state model with an unknown state, so that a timeout is never retried blindly but resolved by a status inquiry. In the simulation naive retries charged 607 of 20,000 payments twice, and the careful design none. Reconciliation is the backstop that proves it.

Interviewer follow-upL5What happens when the provider times out?How to answer

The payment becomes unknown, not failed, and the customer sees "processing". A sweep asks the provider for the status by your reference: if there is a charge, adopt its result, and if not, retry with the same idempotency key, which is safe even if the first request was merely slow. A webhook can resolve it earlier. In the simulation 1,020 of 20,000 payments were unknown and 640 of those had been charged.

Interviewer follow-upL5Why separate authorization from capture?How to answer

Because you often do not know the final amount or cannot yet deliver. A hotel or a marketplace authorizes (a hold on the funds), and captures when the service is rendered or the goods ship, in full or in part. Holds expire after some days, so the flow must capture or release in time, and a capture that is smaller than the authorization releases the rest.

Interviewer follow-upL6How do you handle webhooks that arrive late, twice or out of order?How to answer

Verify the signature, store each event under the provider's event id (a repeat is a no-op), answer 2xx at once and process asynchronously. Keep the events as a set of facts and derive the payment's state from them, so order stops mattering: all 24 orders of four events, each delivered twice, ended in the same state. Add a poller for payments stuck in processing, because an event can be lost.

Interviewer follow-upL6What is reconciliation, and what does it find?How to answer

A comparison of your records with the provider's settlement report, joined on your reference and the provider's id. It finds charges you do not know about, payments you recorded as paid that never settled, double charges, and amount differences, and it accounts for fees, refunds and timing. In the experiment it found 639 breaks in the naive design and none in the careful one. Track unmatched count and age as a control, and automate the clear cases.

Interviewer follow-upL6How would you add a second payment provider?How to answer

Behind an adapter interface with the same state model, a router that chooses by cost and live success rate, and a breaker per provider. Fail over only on definite failures, never after an unknown outcome until the first provider has been asked what it did, because the second knows nothing of the first one's idempotency key. Saved cards need portable tokens or a vault you control, or they can only fail over to the same provider.

Interviewer follow-upL6How do you store card data safely?How to answer

You do not. Hosted fields or an SDK send the number straight to the provider's vault, and your servers hold only a token, which keeps you in the lightest PCI category. Never log card numbers, never keep the security code, redact bodies in logs and traces, and protect tokens as credentials, because whoever holds one can charge through your account.

Interviewer follow-upL6Design refunds: partial, repeated and concurrent.How to answer

A refund is a payment in reverse with its own idempotency key and its own unknown outcomes. Enforce the limit with a conditional update, refunded plus the new amount must not exceed captured, so that two concurrent refunds cannot overdraw it. Post the ledger entries with the same ids, keep the provider's refund id, and reconcile refunds like charges, because fees and settlement timing differ.

Interviewer follow-upL7The provider has an outage at peak. What happens to payments in flight?How to answer

New payments fail fast, since the breaker opens, and route to another provider where the card allows it. The payments in flight become unknown, never failed, and the sweep resolves them by inquiry once the provider returns, the customers see "processing" meanwhile, and webhooks that arrive late are absorbed by the fact model. Alert on the count and age of unknown payments and size the sweep for the backlog.

Interviewer follow-upL7How would you prove to an auditor that no money was lost?How to answer

With records that cannot lie: append-only payments, attempts, events and ledger entries, where every correction is a new entry. A double-entry ledger whose debits equal credits and whose balances can be recomputed from the journal, daily reconciliation that explains the settlement to the cent, and an unmatched-break age that is zero. Show the invariants as checks that run continuously, and keep the evidence of each break and how it was closed.

HLD

How to present this design in an interview

  1. Clarify: merchant or provider, methods, authorize and capture, currencies, refunds and disputes, card data, what must never happen.
  2. Explain the flow: parties, authorization, capture, settlement days later, refunds and disputes. Say that money moves later and in batches.
  3. Estimate: modest rates (hundreds a second), about 1,200 calls in flight, about 5% unknown outcomes. Correctness is the problem.
  4. Contract and model: an idempotency key on every write, integer minor units, a payments table whose row exists before any call, append-only attempts and events.
  5. Draw it: API, payment service with a state machine, router and adapters, webhook receiver, ledger, outbox, reconciliation.
  6. Go deep on the unknown: write first, send the key, mark unknown on timeout, resolve by inquiry. Quote the double-charge numbers.
  7. Go deep on webhooks: verify, store by event id, derive state from facts.
  8. Reconcile: the settlement file, the break categories, the age of the oldest break.
  9. Close with providers, risk and audits: failover rules, tokens, 3-D Secure, disputes, and how you would prove nothing was lost.

Summary

A payment is a conversation among a cardholder, a merchant, a provider, an acquirer, a card network and an issuer, and the money moves days later in batches, so a payment system is a state machine, a ledger and a reconciliation loop. The payment row is written before any call, with a unique idempotency key that is also sent to the provider. A timeout means unknown, not failed: the payment is resolved by a status inquiry or a safe retry with the same key (naive retries double-charged 607 of 20,000 payments and recorded 32 failures for charged payments, the careful design none). Webhooks are stored as facts under the provider's event id and the state is derived from the set, so all 24 delivery orders of four events, each delivered twice, agree. Reconciliation against the settlement file classifies every break and is the proof that the design works. Card numbers never reach your servers, a second provider is used only after unknown outcomes are resolved, and the senior answers cover refunds, outages and audits.

Check yourself

Try answering out loud before you reveal each answer.

QuestionThe provider times out on a charge. What do you do, and what do you not do?Reveal answer

Mark the payment unknown and show "processing", then ask the provider what happened by your own reference, or retry with the same idempotency key, which is safe whether or not the first request arrived. Do not retry as a new request and do not mark the payment failed: in the experiment those two mistakes caused 607 double charges and 32 charges recorded as failures in 20,000 payments.

QuestionWhy store webhook events as a set of facts instead of applying them in order as they arrive?Reveal answer

Delivery is at least once and unordered, so a late "captured" or a repeated "refund" would be misapplied by a step-by-step machine. A set insert is idempotent and commutative, and the state is computed from the facts, so every order and every repeat gives the same answer: all 24 orders of four events, each delivered twice, ended as refunded with 5,000 refunded. A capture without an authorization is still understood.

QuestionWhat does reconciliation compare, and what categories of break can it find?Reveal answer

Your payment records against the provider's settlement report, joined on your reference and the provider's id. Breaks are a double charge, a charge you recorded as failed, a charge still unknown, a payment recorded as succeeded that the provider never charged, and an amount mismatch. It is the second set of books that catches what the first mechanisms missed. Timing (settlement lags a day or more) and fees must be modelled so that real breaks are not buried in noise.

QuestionWhy is failing over to a second provider after a timeout dangerous?Reveal answer

The first provider may have charged the card, and the second knows nothing of its idempotency key, so the customer is charged twice. Fail over only on definite failures, resolve the first provider's unknown outcome before sending the payment elsewhere, and rely on reconciliation and refunds if you must accept a rare duplicate. Saved cards also need portable tokens to be charged through another provider at all.

Sources and further reading

Lesson 30 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 31Case study: design a ledger and a walletA senior-level walkthrough of a ledger and a digital wallet: double-entry bookkeeping, immutable entries and audits, exact money arithmetic, overdraft races, hot accounts and cross-shard sagas with crash recovery, with tested C#.

Send a message

It goes straight to my inbox. I usually reply within a few days.