CodingNodes Space play · ←→ step · R restart

The problem

Every other system in this course fails by being slow, or by returning a slightly wrong answer. A payment system fails by losing money, and the two failure directions are both real. Charge a card twice for one purchase and you have overcharged a customer; miss a settlement that was due and you have lost the merchant their money. The design that survives is not the one that is fast — it is the one where a wrong state is impossible, or at the very least detectable and correctable. Speed is a property of a payment system; correctness is its definition.

So the design is a state machine and the invariants that keep it honest. A payment moves through a small set of states — created, authorised, captured, settled, and the two exits, refunded and voided — and each transition is a guarded step that the state machine allows or refuses. An idempotency key makes a retried charge not a double charge, because the second request with the same key returns the first result instead of a new payment. A ledger makes the balance a derived quantity, so it cannot drift out of step with the payments that created it. And an async path keeps the merchant's checkout from blocking on the bank's settlement, which takes days. We will build the charge path, the state machine, the idempotency, the ledger, the settlement, and the reconciliation that closes the loop between what we think happened and what the bank says happened — and close the chapter with one charge that is authorised, captured, settled, and reconciled, with no double-charge and no lost money anywhere along the way.

Requirements

Functional — what it must do

  • Charge: a merchant submits a charge for an amount against a payment method, and the system returns a definitive outcome — authorised, or declined with a reason — without ever charging twice for the same logical charge.
  • Settle: an authorised payment is captured and the funds are moved to the merchant, with the settlement completing on the bank's timescale, not the checkout's.
  • Refund: a payment can be refunded, in whole or in part, and the refund is a new, traceable money movement that reverses the original, with the state machine refusing any refund that would exceed what was charged.

Non-functional — how well it must do it

  • Correctness over speed: a wrong state — a double charge, a lost settlement, a refund over the charged amount — is the failure the design exists to prevent, and it is detectable and correctable even if it is not prevented.
  • Idempotency: a request that is retried, timed out, or resent with the same idempotency key returns the original outcome and does not create a second payment.
  • Traceability: every movement of money is a ledger entry with a before and after state, so the balance is a derived quantity and the audit is a query, not a reconstruction.
  • Durability: a payment that is acknowledged is durable; a crash between the authorisation and the state record loses nothing, because the state and the ledger entry are written together.

Scale — how much it must take

  • On the order of millions of payments per day, with a peak-hour burst and a settlement cycle that runs on a daily or sub-daily bank timescale, and a reconciliation that must close the gap between our records and the bank's on every cycle.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Payments/day
millions
The throughput. The design goal is correctness at that rate, not just correctness.
Authorise
sub-second
The authorisation must return in time for a checkout, which is why it is synchronous and the settlement is not.
Settle
daily / sub-daily
The bank's timescale. A settlement is not an event the merchant waits for; it is a batch that closes on the bank's schedule.
Idempotency
one key → one payment
The idempotency key is the anchor: a retried request with the same key returns the first result, never a second charge.
Refund
≤ the charged amount
A refund is bounded by the original charge, and the state machine refuses a refund that would exceed it.
Ledger
the balance is derived
The balance is the sum of the ledger entries, not a stored counter, so it cannot drift out of step with the payments.

Takeaways

Part 1

A state machine, not a pipeline

A payment is not a sequence of steps that runs once; it is a state with guarded transitions. The system is the state machine and the invariants that keep it honest, and 'fast' is a property of it, not a substitute for 'correct'.

  1. 1
    The failure is a wrong state

    The defining property of a payment system is that its failure mode is not latency or a wrong answer — it is a wrong state, and a wrong state is a real loss of money. Charge twice and you have overcharged a customer; miss a settlement and you have lost the merchant their money; refund more than was charged and you have created a loss out of thin air. Every one of these is a state the system should never reach, and the design is the set of invariants that make those states unreachable, or at the very least detectable and correctable. Correctness is the definition of a payment system; speed is a property of one.

  2. 2
    A state machine, not a pipeline

    A pipeline runs its steps once and ends. A payment does not: it can be authorised and then captured days later, or authorised and then voided, or captured and then refunded in part, several times, over months. That is a state machine — a small set of states and a guarded set of transitions — and the design is the state machine plus the invariants that keep it honest. A pipeline has no notion of 'this step is not allowed from here'; a state machine does, and that refusal is what stops a settlement from running on an already-settled payment, or a refund from running after the funds are gone.

Part 2

The charge path

The charge is synchronous: the merchant's checkout waits for an answer. Tokenisation keeps the raw card out of the system, the acquirer authorises against the bank, and the payment state records the outcome. The settlement is not on this path — it is the next part, on the bank's timescale.

  1. 1
    Synchronous, because the checkout waits

    The charge is the one operation that is synchronous, because the merchant's checkout is blocked on it. The customer is at the 'pay' button and the page is waiting, so the system must return a definitive outcome — authorised or declined, with a reason — within a second or two. That is why the authorisation is on the critical path and the settlement is not: the authorisation answers the question the checkout is asking ('is this charge good?'), and the settlement answers a question the checkout does not care about ('has the money moved to the merchant?'). Splitting them is what lets the checkout be fast and the settlement be correct.

  2. 2
    Tokenisation keeps the raw card out

    The system does not store the card number. When a card is presented, a tokenisation service exchanges it for a token — a surrogate that references the card but is useless without the service that issued it — and the rest of the system works with the token. That is both a security property (a breach of the payment database leaks tokens, not cards) and a design one (the charge, the capture, and the refund all refer to the same token, so the payment method is a stable reference across the state machine). The raw card touches exactly one component and is gone.

  3. 3
    The authorisation is a hold, not a movement

    An authorisation is not a transfer of money; it is a hold on it. The bank confirms that the card can cover the amount and sets that amount aside, but the money has not moved. That distinction is what lets the later steps be safe: a capture moves the held amount, a void releases it, and a refund — after a capture — moves it back. The authorisation is the 'yes, this is payable' answer the checkout was waiting for, and it is the precondition for every later transition. It is a state, and like every state, it is recorded durably the moment it is reached.

Part 3

The idempotency key: one logical charge

A checkout that times out retries. A network that drops a response retries. The same logical charge reaches the system more than once, and the second request must not be a second charge. The idempotency key is what makes 'retry' and 'new charge' distinguishable.

  1. 1
    The retry is indistinguishable from a new charge

    From the system's point of view, a retried charge and a brand-new charge look identical: same amount, same card, same merchant. The only thing that separates them is the idempotency key — a value the merchant generates once, at the moment they decide to charge, and sends with every attempt of that logical charge. A retry carries the same key; a genuinely new charge carries a new one. Without that key, the system cannot tell the two apart, and the safe behavior — treating every request as a new charge — is exactly the one that double-charges.

  2. 2
    The key maps to the one real payment

    The system keeps a map from idempotency key to the payment it created. The first request with a key creates the payment and records the key → payment mapping. A later request with the same key does not create a payment; it looks up the mapping and returns the outcome of the payment that already exists. So a retry — whether it arrives before the first has finished or long after — returns the first result, and the customer is charged once. The key is the anchor of exactly-once charging: it is what turns 'at-least-once delivery of a charge request' into 'exactly-once movement of money'.

  3. 3
    The key is a contract, and it is the merchant's

    The idempotency key is generated by the merchant, not the payment system, and that is deliberate. The merchant is the one who knows what a logical charge is — who knows that these two HTTP requests are the same purchase and those three are three different ones. The payment system cannot know that; it can only honor the key it is given. So the contract is: the merchant sends a stable key per logical charge, and the system guarantees one charge per key. The system's job is to make the guarantee hold; the merchant's job is to make the key stable. Get the key wrong and the guarantee is only as good as the key.

Part 4

The ledger: the balance is derived

The balance is not a stored counter that is incremented; it is the sum of a ledger of money movements. A payment is a debit on one side and a credit on the other, and the balance falls out of the ledger, so it cannot drift out of step with the payments that created it.

  1. 1
    A counter drifts; a ledger does not

    The naive balance is a counter that goes up on a charge and down on a refund. It is simple, and it is wrong in exactly the way that matters: every arithmetic slip, every missed refund, every double charge is a permanent error in the counter, and the counter has no memory of why it is what it is. A ledger is the opposite: it is an append-only record of every money movement, each with a debit side and a credit side, and the balance is the sum of that record. A slip is still a slip, but it is a slip in a record you can read, and the balance is always recomputable from the movements that produced it. The ledger turns the balance from a thing you trust into a thing you can verify.

  2. 2
    Every payment is two entries

    A completed payment is not one ledger entry; it is two. The customer's side is debited — the amount leaves their account — and the merchant's side is credited — the amount is added to what they are owed. Both entries are written together, as one logical record with two sides, and the double-entry is what keeps the books balanced: the total of all debits always equals the total of all credits, by construction. A balance is the position of one side of that record, and because the two sides are written together, a balance that is wrong is a record that is unbalanced — and an unbalanced record is visible, not hidden.

  3. 3
    The balance is a query, not a stored value

    Because the balance is the sum of the ledger, computing a balance is a query over the record, not a read of a stored number. That has a consequence that is easy to underestimate: you can recompute any balance, for any account, for any point in time, by summing the ledger up to that point. A stored counter can only tell you the balance now; a ledger can tell you the balance at any moment, and the difference between the two is the difference between a number you trust and a number you can prove. The ledger is the audit, and the audit is not a separate system bolted on — it is the data model.

Part 5

Capture and settlement: the bank's timescale

An authorisation is a hold; a capture moves the held amount; a settlement moves it to the merchant. The capture can be immediate or batched, and the settlement runs on the bank's schedule, not the checkout's — which is why it is async and why it must be idempotent and replayable.

  1. 1
    Capture is the money moving

    A capture is the transition that moves the held amount. It takes the authorisation — the bank's 'yes, this is payable' — and turns it into a settlement in progress: the amount that was held is now committed to the merchant. A capture can happen immediately, in which case the authorisation and the capture are nearly the same moment, or it can be batched, in which case many authorisations accumulate and are captured together on a schedule. Either way, the capture is the point at which the money's movement begins, and it is the transition the state machine guards most carefully, because capturing an already-captured payment, or a voided one, is a loss.

  2. 2
    Settlement is the bank's timescale

    A settlement is the movement of the captured amount into the merchant's bank account, and it happens on the bank's schedule — a daily or sub-daily cycle — not on the checkout's. That is why settlement is async: the merchant does not wait for it, and the customer's purchase is complete long before the money lands. A settlement is also why the system is a batch as much as a transaction: a settlement cycle is a batch over the day's captures, and it must be idempotent (running it twice moves the money once) and replayable (a cycle that fails partway can be redone without double-moving). The bank's timescale is a constraint the design absorbs, not a problem it solves.

  3. 3
    The window between authorised and settled

    There is a real window between the moment a payment is authorised and the moment it is settled, and that window is where a lot of the correctness lives. A payment in that window is 'authorised, not yet settled', and the system must be able to answer, at any moment, exactly which payments are in that window and what their state is. A refund can only be processed on a settled payment, a void can only be processed on an authorised-but-not-settled one, and a capture can only be processed on an authorised-but-not-captured one. The window is not a gap in the design; it is a state, and the state machine treats it as one.

Part 6

Reconciliation: closing the loop

The bank keeps its own record of what it did, and it is not the same record as ours. Reconciliation is the periodic comparison of the two — what we think we moved, and what the bank says it moved — and the handling of any gap. It is not a bolt-on; it is the mechanism that makes 'correct' mean anything across two parties.

  1. 1
    Two records, two parties

    The payment system has a record of the payments it processed, and the bank has a record of the movements it made. These are two records kept by two parties, and they can disagree: a payment we recorded as settled may have been declined at the bank, a settlement we batched may have been partially rejected, a refund we issued may not have reached the customer's bank yet. Reconciliation is the periodic comparison of the two records — what we think happened, and what the bank says happened — and the handling of any difference. It is the only mechanism that can tell us whether our 'correct' and the bank's 'correct' are the same 'correct'.

  2. 2
    The gap is the product

    Reconciliation does not produce a number; it produces a gap — the set of payments where the two records disagree. That gap is the product, because a gap is a thing to investigate and resolve, and the absence of a gap is what 'reconciled' means. A reconciliation that finds no gap is a reconciliation that proves the two records agree; a reconciliation that finds a gap is a reconciliation that has found a real problem — a double charge, a lost settlement, a refund that did not land — and named it. The quality of the reconciliation is measured by how small and how explainable its gap is, and a gap that cannot be explained is the most expensive kind of error, because it is one you did not know you had.

  3. 3
    A cycle that is idempotent and replayable

    A reconciliation runs on a schedule — daily, or per settlement cycle — and it must have the same properties as the settlement it is checking: idempotent, so running it twice does not double-count a movement, and replayable, so a cycle that failed partway can be redone cleanly. The reconciliation is a batch over the window of payments, comparing our ledger to the bank's statement, and it is the async path's audit. It is the mechanism that turns 'the money moved' from a claim into a fact, and it is what separates a payment system that is correct from one that is merely self-consistent.

★ Finale

End to end

One charge's life: submitted with an idempotency key, authorised against the bank, captured, settled on the bank's cycle, and reconciled against the bank's record — with a retry of the charge returning the first outcome, and no double-charge and no lost money anywhere along the way.

  1. 1
    The whole system

    Every piece in one frame. A merchant submits a charge with an idempotency key; the payment API validates it and checks the key map; the card is tokenised; the acquirer authorises; the payment state records the outcome and the ledger gets its debit and credit. A capture moves the held amount, a settlement moves it to the merchant on the bank's cycle, and a reconciliation compares our record to the bank's and closes the gap. One charge, one movement of money, and a loop that proves it.

  2. 2
    Authorised, and the retry is a no-op

    A merchant submits a charge with idempotency key K. The system creates the payment, records the K → payment mapping, tokenises the card, and the acquirer authorises the amount. The checkout returns 'authorised' to the customer. Now the merchant's client times out and retries with the same key K. The system looks up K, finds the payment it already created, and returns that payment's outcome — no new payment, no second charge. The idempotency key did its job: the retry is a no-op, and the customer is charged exactly once.

  3. 3
    Captured, and settled on the bank's cycle

    The authorised payment is captured: the held amount is committed to the merchant. The capture is recorded in the state and the ledger. Then, on the bank's settlement cycle, the captured amount is moved into the merchant's bank account. The settlement is a batch over the day's captures, and it is idempotent — running the cycle twice moves the money once. The money has moved, and the ledger reflects it: the customer's side is debited, the merchant's side is credited, and the balance is the sum of that record.

  4. 4
    Reconciled: our record, the bank's record, no gap

    At the end of the settlement cycle, a reconciliation runs: it compares our ledger to the bank's statement over the window of payments, and it finds the gap — the set of payments where the two records disagree. For this charge, there is none: our record says it was authorised, captured, and settled, and the bank's record says the same. The reconciliation closes the loop, and 'the money moved' is no longer a claim but a fact, verified against the party that actually moved it. No double-charge, no lost settlement, and a balance that is a sum you can recompute.

🌐 In the wild

In the wild

Payment systems are the backbone of every commerce platform. The boxes below are anchored to the classes of well-known systems that run each piece — an illustrative mapping, not a claim about any one product's internals.

  1. 1
    The pattern, piece by piece

    Each box is a standard building block of a payment system. Anchoring them to the classes of production systems that run that piece turns the abstract design into the shape behind the checkout that charges once, settles correctly, and reconciles cleanly.

  2. 2
    Why the same pieces keep winning

    Independent payment systems converge on the same pieces because each one removes a real failure: the idempotency key removes the double-charge failure, the tokenisation removes the raw-card-leak failure, the ledger removes the balance-drift failure, the settlement batch removes the lost-money failure, and the reconciliation removes the unexplained-gap failure. That convergence across independent systems is the evidence the design is load-bearing.