Available for consulting: payments, backend performance and platform engineering.Book a call
Saravana Thiyagarajan · The Backend Guy
Book a call
Payment System Design · Part 1 of 8

Understanding payment systems

What happens between “Pay” and the money arriving, why the obvious code credits people twice, and how to model a payment as a state machine that refuses illegal moves.

Chapters 1–228 min readPublished 23 Nov 2026

Most first payment integrations look alike: call the provider, get a success response, mark the order as paid. It works in the demo, and it keeps working for the first few hundred customers. Then a provider has a slow afternoon, a few requests time out, a few customers tap “Pay” again, and someone in finance asks why the books are off.

This part explains why. Before ledgers, queues or locks, you need a clear picture of what a payment is, and a way to say where each payment is in its life. The rest of the handbook builds on both.

Chapter 1

Why processing payments is harder than it looks

To the customer, a payment is one action: tap a button and the money is gone. Behind that button, several companies and their computers have to agree on what happened, and they don't all get there at the same time.

A payment is not one HTTP request

When you call POST /charges on a provider, it is tempting to treat the response as the whole story. It isn't. A card payment goes through several stages that happen at different times and are run by different parties:

  1. Initiation. The customer says “I want to pay €40”. Nothing has happened to any money yet; so far it is only a request in our system.
  2. Authorisation. The customer's bank checks the card and puts a hold on €40. The money is still in the customer's account, but it is reserved.
  3. Capture. The merchant (us, through our provider) says “yes, take the money we reserved”. This can happen right away or later, for example when an order ships.
  4. Settlement. Money moves between banks and lands in the merchant's account, usually in a batch, often a day or more later.
  5. Reconciliation. We compare our records with the provider's reports and the bank statement, and make sure every cent is explained.
The lifecycle of a card paymentFive boxes from left to right: initiate, authorise, capture, settle, reconcile. The first two happen in seconds; capture, settlement and reconciliation can take hours or days. Initiatecustomer asksAuthorisebank holds fundsCapturemerchant claimsSettlemoney movesReconcilewe check it allwhat the customer sees: secondswhat finance sees: hours to daystime
One “payment”, five separate events. The customer only sees the first two. The money only moves at settlement, often a day or more later. Timings are illustrative and depend on the payment method and provider.

Not every payment method has all five stages. Some methods, like many bank transfers and real-time payment schemes, collapse authorisation and capture into one step. The general shape still holds: the moment the customer sees “paid” is not the moment the money moves.

Authorisation, capture and settlement

People mix these three words up a lot, and the difference shows as soon as something goes wrong.

The three stages of a card payment
StageWhat it meansWho does itHas money moved?
AuthorisationThe bank approves the payment and reserves the amount.Customer's bank (the issuer)No. It is a hold.
CaptureThe merchant confirms it wants the reserved money.Merchant, via the providerNot yet. It is now owed.
SettlementFunds are transferred between banks.Banks and card networksYes.

An authorisation does not last forever. Stripe, for example, says an authorisation for an online card payment is usually valid for 7 days, with shorter windows for some cases (Stripe: place a hold on a payment method). If you authorise and never capture, the hold expires and you never get paid. Nothing throws an error when that happens, which is why it's easy to miss.

Payment success is not business success

When a provider tells you a payment succeeded, it means their part worked. Your part still has to happen: credit a wallet, mark an order as paid, give the customer the thing they bought. These are two different facts:

  • Payment success: “PayCo charged the customer €40.”
  • Business success: “We credited the customer's wallet with €40, exactly once.”

Either can be true while the other is false. The provider can charge the customer and our server can crash before crediting them, so the customer has paid and got nothing. Or, as the example below shows, we can credit the wallet twice for one charge. A good payment system tracks the two facts separately and has a plan for when they disagree.

Confirmation usually arrives later, and sometimes more than once

Many payments are not decided inside the request that starts them. The customer may need to approve the payment in their banking app, pass a 3-D Secure check, or finish on the provider's hosted page.

In all of these cases the final answer reaches us asynchronously, meaning later and through a different channel. Usually that channel is a webhook: the provider calls a URL on our side to tell us what happened.

Webhooks are convenient, but you can't count on them to behave. Stripe's documentation says plainly that endpoints “might occasionally receive the same event more than once”, and that it “doesn't guarantee the delivery of events in the order that they're generated” (Stripe: webhooks). Expect the same from other providers. From day one, the code that handles a payment result has to cope with:

  • the same event arriving twice (or ten times),
  • events arriving in the wrong order, like “succeeded” before “processing”,
  • an event arriving late, after we have already given up on the payment,
  • an event never arriving at all.

Because of that last case, I never rely on webhooks alone: we also ask the provider for the status ourselves, and we reconcile.

A timeout does not mean the payment failed

If you take one idea from this chapter, take this one. When our call to the provider times out, there are three possibilities, and from our side they look identical:

  1. The request never reached the provider. Nothing happened.
  2. The request reached the provider, and the payment failed.
  3. The request reached the provider, the payment succeeded, and the response got lost on the way back.

“Unknown” is a real state, and the system needs somewhere to keep it; the next chapter calls it PROCESSING. From there we find out what happened by asking the provider for the payment's status, by waiting for the webhook or, as a last resort, through reconciliation.

Three systems, three answers

Taken together, this leads somewhere uncomfortable: at any moment, each system involved in one payment can believe something different, and none of them is wrong.

Three systems, three answers about the same paymentOur database says the payment is processing, PayCo says the charge succeeded, and the bank says the funds are on hold. Arrows from all three lead to reconciliation. Our databasepayment: PROCESSINGPayCocharge: succeededThe bankfunds: on holdreconciliation
At any moment, the systems involved in a payment can disagree, and none of them is lying. Our job is to bring the answers together and to notice when they don’t match, which is what reconciliation does (Chapter 20).

Our database is one of these views, and often the least informed. That is why the third principle of this handbook is never blindly trust any component, our own database included. We design for disagreement and check for it.

Worked example: how a retry credits a customer twice

A common setup makes this concrete. The customer pays on PayCo's hosted page. When they come back to our app, the app calls our API to confirm the payment. Our API asks PayCo for the status, and if it says “succeeded”, we credit the customer's wallet.

The obvious implementation, in Python with FastAPI and psycopg, looks like this. (The payco client is fictional, and so are pool and load_payment, which stand for a connection pool and a small query helper.)

api/payments.py (naive)Python
# Naive version: do not use
@app.post("/payments/{payment_id}/confirm")
def confirm_payment(payment_id: str):
    payment = load_payment(payment_id)
    result = payco.get_payment(payment.provider_payment_id)

    if result.status == "succeeded":
        with pool.connection() as conn:
            conn.execute("UPDATE payments SET status = 'SUCCESS' WHERE id = %s", (payment_id,))
            conn.execute(
                "UPDATE wallets SET balance_minor = balance_minor + %s WHERE id = %s",
                (payment.amount_minor, payment.wallet_id),
            )

    return {"status": result.status}

On a first read it looks fine. On a slow day, this happens:

How a timeout and a retry credit a wallet twiceSequence: the customer pays PayCo. The app asks our API to confirm. Our API checks with PayCo, sees success and credits the wallet, but the app has already timed out. The app retries, our API checks again, sees success again, and credits the wallet a second time. Customer appOur APIPayCo1. pays €40 on PayCo’s pagecharged2. confirm paymentstatus?succeededwallet +€4010 s timeout fires200 OK (too late)3. retry confirmstatus?succeededwallet +€40 againCharged once. Credited twice.
Nothing here is a bug in PayCo or in the network. Every step did what it was told. The bug is that “confirm” credits the wallet every time it sees a success, instead of once per payment.
  1. The customer pays €40 on PayCo's page. PayCo charges them.
  2. The app calls /confirm. Our API asks PayCo, gets “succeeded” and credits the wallet with €40. The database commits.
  3. But all of that took longer than the app's 10-second timeout (because PayCo was slow that afternoon). The app gives up and shows “Something went wrong, try again”.
  4. The customer taps “Try again”. The app calls /confirm a second time. PayCo still says “succeeded”, because it did. Our API credits the wallet again.

The customer paid €40 and now has €80 in their wallet. The retry path isn't the only way in, either: the same thing happens if the webhook handler and the confirm call both credit the wallet, or if PayCo delivers the webhook twice.

What went wrong

Three things went wrong, and all three come back in later chapters. First, the credit is tied to “seeing a success” rather than to the payment: the code credits every time it observes success, when it should credit once per payment however often success is observed.

Second, nothing guards the state change. UPDATE payments SET status = 'SUCCESS' succeeds even if the status is already SUCCESS, so nothing in the database says “this already happened”. And third, several paths apply the same outcome (confirm, webhook, maybe a cron job) without knowing about each other.

The fix: make the state change the guard

Credit the wallet only if this request is the one that moved the payment into SUCCESS. The database can tell us whether it was. A conditional update, UPDATE … WHERE status IN ('PENDING', 'PROCESSING'), changes the row only while the payment is still waiting, so when two requests race, only one can make the change; the other finds the row already in SUCCESS and changes nothing.

PostgreSQL's RETURNING clause gives back values “based on each row actually updated” (PostgreSQL: UPDATE). A row back means we won and should credit. No row means someone else got there first, and we leave the wallet alone.

api/payments.py (fixed)Python
@app.post("/payments/{payment_id}/confirm")
def confirm_payment(payment_id: str):
    payment = load_payment(payment_id)              # plain read, no transaction held open
    if payment.status not in ("PENDING", "PROCESSING"):
        return {"status": payment.status}           # already decided: answer from our records

    result = payco.get_payment(payment.provider_payment_id)   # network call, outside any transaction
    if result.status != "succeeded":
        return {"status": payment.status}
    if (result.amount_minor, result.currency) != (payment.amount_minor, payment.currency):
        raise HTTPException(status_code=409, detail="amount mismatch, flagged for review")

    with pool.connection() as conn, conn.transaction():
        row = conn.execute(
            """
            UPDATE payments
               SET status = 'SUCCESS', updated_at = now()
             WHERE id = %s AND status IN ('PENDING', 'PROCESSING')
            RETURNING wallet_id, amount_minor
            """,
            (payment_id,),
        ).fetchone()
        if row is not None:                         # this request moved it to SUCCESS: credit once
            wallet_id, amount_minor = row
            conn.execute(
                "UPDATE wallets SET balance_minor = balance_minor + %s WHERE id = %s",
                (amount_minor, wallet_id),
            )

    return {"status": load_payment(payment_id).status}

Some details in there are deliberate:

  • The status update and the credit are in one transaction. Either both happen or neither does. psycopg's conn.transaction() block commits when it exits normally and rolls back if an exception escapes it (psycopg: transactions).
  • The call to PayCo happens before the transaction opens, never inside it. A transaction that waits on a slow network call holds database locks and a connection the whole time. Chapter 13 covers this in depth.
  • We check the amount and currency the provider reports against what we expected. If they differ, we don't guess; we stop and flag it. This is “never blindly trust any component” applied to the provider.
  • Amounts are integers in minor units (cents), never floats. Chapter 3 explains why.

The webhook handler needs the same guard. The simplest way to guarantee that is one function that applies a success, called from every path that learns about one. In Go with pgx, it looks like this:

payments/apply.goGo
var ErrAmountMismatch = errors.New("provider amount does not match payment")

// ApplySuccess moves a payment to SUCCESS and credits the wallet, at most once.
// The confirm endpoint, the webhook consumer and reconciliation all call this.
func ApplySuccess(ctx context.Context, pool *pgxpool.Pool, paymentID string, gotAmountMinor int64, gotCurrency string) error {
	return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		var walletID, currency string
		var amountMinor int64
		err := tx.QueryRow(ctx, `
			UPDATE payments
			   SET status = 'SUCCESS', updated_at = now()
			 WHERE id = $1 AND status IN ('PENDING', 'PROCESSING')
			RETURNING wallet_id, amount_minor, currency`, paymentID).
			Scan(&walletID, &amountMinor, &currency)
		if errors.Is(err, pgx.ErrNoRows) {
			// Already SUCCESS, or in a state where success can't be applied
			// automatically. Either way: no second credit. Chapter 2 tells these apart.
			return nil
		}
		if err != nil {
			return err
		}
		if amountMinor != gotAmountMinor || currency != gotCurrency {
			return ErrAmountMismatch // returning an error rolls back the status change too
		}
		_, err = tx.Exec(ctx,
			`UPDATE wallets SET balance_minor = balance_minor + $1 WHERE id = $2`,
			amountMinor, walletID)
		return err
	})
}

pgx.BeginFunc starts a transaction, runs the function, and commits if it returns nil or rolls back if it returns an error (pgx v5 docs). That makes the transaction boundary easy to see: everything inside the function is atomic, and nothing outside it is.

Two more protections complete the picture. Both get their own chapters later.

  • Idempotency keys on the way in. When the app creates a payment, it sends a unique key (for example a UUID it generated). If the create request is retried, we return the existing payment instead of creating a new one. Providers do the same on their side: Stripe compares the parameters of a retried request with the original and returns an error if they differ (Stripe: idempotent requests). Chapter 6 covers how to choose and store these keys.
  • A unique constraint on the provider's payment ID, so the same provider payment can never be attached to two of our payments.

What to monitor

  • Payments stuck in PENDING or PROCESSING, by age. A payment that has been “unknown” for an hour needs a person or a job to look at it.
  • How often the guard fires: confirm calls and webhooks that found the payment already decided. A sudden jump usually means a client retry loop or a provider redelivering events.
  • Amount mismatches. There should be close to none, and each one is worth investigating.
  • Timeouts to the provider, as a rate. They are the main source of “unknown” payments.

What to test

  • Call confirm twice for the same payment, one after the other. Expect exactly one credit.
  • Call confirm twice at the same time (two goroutines or threads). Expect exactly one credit.
  • Deliver the same success webhook ten times. Expect exactly one credit.
  • Make the provider respond after your client's timeout. Expect the payment to end up in SUCCESS with one credit, not two, and not a failure.
  • Return a different amount from the fake provider. Expect no credit and a flagged payment.

Checklist

  • A timeout is treated as “unknown”, never as success or failure.
  • Every path that learns about a success calls the same function.
  • The credit happens in the same database transaction as the status change.
  • The status change is conditional, so only one caller can win.
  • Network calls to providers happen outside database transactions.
  • Provider-reported amounts and currencies are checked against our own records.
  • Webhooks are expected to be duplicated, reordered, late or missing.

Chapter 2

Designing a payment lifecycle

Chapter 1 ended with a status column doing real work: WHERE status IN ('PENDING', 'PROCESSING') was the thing that stopped a double credit. This chapter designs that column on purpose: which states a payment can be in, which moves between them are allowed, and what happens when something tries a move that isn't.

Why a few booleans are not enough

A lot of payment tables start like this: is_paid, is_credited, is_refunded, is_failed. Four booleans give you sixteen combinations, and most of them make no sense. What does is_paid = true, is_failed = true mean? What about refunded but never paid?

Each of these combinations will show up in production eventually, usually because two pieces of code updated different flags at the same time, and then someone has to work out by hand what happened.

A single status column with a fixed set of values, and a fixed set of allowed moves between them, rules those combinations out. That's all a state machine is: a list of states, plus rules for moving between them.

The states

Payment states
StateWhat it meansTerminal?
CREATEDWe recorded the customer's request. Nothing has been sent to a provider yet.No
PENDINGSent to the provider, waiting on the customer or the provider to act (approve in their bank app, finish 3-D Secure).No
PROCESSINGThe provider has it and is working on it, or we lost track (a timeout) and are finding out.No
SUCCESSThe provider confirmed the money was taken, and we applied it (credited the wallet, marked the order).For this flow, yes, but see below
FAILEDThe provider declined or errored, and no money was taken.Yes
CANCELLEDStopped before any money moved: the customer abandoned it, or it expired.Yes
REFUNDEDMoney was sent back to the customer through the provider.Yes
REVERSEDWe undid a successful payment internally, with a compensating ledger entry.Yes

A terminal state is one that nothing can move out of. SUCCESS is a slightly special case: the payment flow is finished, but the payment can still be refunded or reversed later. Those later moves are new operations with their own records (a refund has its own lifecycle with the provider), and they point back to the original payment. They don't rewrite it.

Three words that people often use interchangeably mean different things here:

  • Cancellation happens before money moves. Nothing needs to be undone.
  • Refund happens after money moved, and sends money back to the customer through the provider. It is a new money movement.
  • Reversal undoes a successful payment in our books, for example because we credited the wrong wallet. It writes a new, opposite ledger entry rather than deleting the old one. Chapter 4 covers this in detail.

The allowed moves

The payment state machineStates: CREATED, PENDING, PROCESSING, SUCCESS, FAILED, CANCELLED, REFUNDED, REVERSED. CREATED goes to PENDING or CANCELLED. PENDING goes to PROCESSING, SUCCESS, FAILED or CANCELLED. PROCESSING goes to SUCCESS or FAILED. SUCCESS goes to REFUNDED or REVERSED. FAILED, CANCELLED, REFUNDED and REVERSED are terminal. CREATEDPENDINGPROCESSINGSUCCESSFAILEDCANCELLEDREVERSEDREFUNDEDdouble border = terminal: nothing moves it again
Every arrow is a move we allow; anything without an arrow is rejected. This drawing and the transition table below describe the same rules, and the Go map later in the chapter is the same rules again in code.
Legal transitions
FromAllowed toTypical trigger
CREATEDPENDING, CANCELLEDSent to provider; customer abandons before we send
PENDINGPROCESSING, SUCCESS, FAILED, CANCELLEDProvider events; expiry
PROCESSINGSUCCESS, FAILEDProvider event, status check or reconciliation
SUCCESSREFUNDED, REVERSEDRefund completes; internal reversal
FAILEDnoneTerminal
CANCELLEDnoneTerminal
REFUNDEDnoneTerminal
REVERSEDnoneTerminal

PENDING → SUCCESS is allowed on purpose. Webhooks arrive out of order, so we may hear “succeeded” before we ever hear “processing”, and the state machine has to accept the real world rather than an idealised version of it.

The arrows that aren't there do most of the protecting. Nothing leaves FAILED, and nothing goes backwards from SUCCESS to PROCESSING.

Why every transition must be checked

Imagine a status column with no rules, where every event handler just writes the status it was given. Two ordinary things break it.

Out-of-order events. PayCo sends “processing” and then “succeeded”, but they arrive the other way round. Without rules, the payment ends up in PROCESSING even though it succeeded. It now looks stuck, someone may retry it, and the customer may be charged again.

Late success after failure. We call PayCo, it times out, and after a while we give up and mark the payment FAILED. The customer sees “payment failed” and pays again with another card. An hour later a webhook arrives: the first payment had succeeded after all.

If we write SUCCESS, we credit a payment the customer believes failed, on top of the one they made after it. If we ignore the event, we keep the customer's money with nothing recorded against it.

A late SUCCESS cannot silently overwrite FAILEDA payment is in FAILED. A late webhook says SUCCESS. The transition check rejects the move and sends the event to a review queue instead. FAILEDcustomer was told“payment failed”transition checklate webhook: SUCCESSreview queuea person or a reconciliation job decides
Rejecting the move is only half the job. FAILED to SUCCESS is illegal, but the event may still be telling the truth: money may have moved. So we neither apply it nor drop it. We record it somewhere a person or a reconciliation job will look.

Other illegal moves are harmless. A processing event that arrives after SUCCESS is stale news; ignore it, but log it.

Payouts have their own lifecycle

Money going out, to a customer's bank account for a withdrawal, has its own flow and its own states. The part to watch is in the middle:

The payout lifecyclePayout states: CREATED, then PAYOUT_INITIATED, then PAYOUT_ACKNOWLEDGED, then SETTLED. INITIATED or ACKNOWLEDGED can also end in PAYOUT_FAILED. CREATEDwe decided to payINITIATEDwe sent itACKNOWLEDGEDprovider acceptedSETTLEDmoney arrivedFAILEDreturned or rejected
“Acknowledged” is not “paid”. In code these are PAYOUT_INITIATED, PAYOUT_ACKNOWLEDGED, SETTLED and PAYOUT_FAILED. A payout can be accepted by the provider and still bounce back from the receiving bank later, so SETTLED waits for real confirmation.

PAYOUT_ACKNOWLEDGED means the provider accepted our instruction. It does not mean the money arrived. Bank transfers can be returned days later, for example because the account was closed or the name didn't match. That is why SETTLED is a separate state, set only when we have real confirmation such as a settlement report or a bank statement line. Treating “acknowledged” as “paid” is a common and expensive shortcut.

Reconciliation is not a state in either lifecycle. It is a separate check that runs alongside them and records its own result (“matched on 24 Nov”, “amount differs”). Keeping it out of the status column means a reconciliation problem never has to fight with the payment flow over one field.

Request, execution and posting are three different things

One last modelling decision saves a lot of pain later. Three things often get crammed into one table, and they shouldn't be:

  • The payment request: what the customer asked for. Amount, currency, their idempotency key, and the price or exchange rate we quoted. It exists once.
  • The attempts: each try with a provider. If the first card is declined and the customer tries another, that is one request with two attempts, each with its own provider reference and status.
  • The postings: the ledger entries that record money moving. They exist only for attempts that succeeded.
Request, attempts and postings are different recordsOne payment request has two attempts. Attempt 1 was declined and created no postings. Attempt 2 succeeded and created two ledger postings: plus 40 to the wallet and minus 40 to clearing. payment requestid: pay_81key: 5f1c…e2amount: 40.00 EURstatus: SUCCESSattempt 1ref: pc_7Q2status: FAILED(card declined)attempt 2ref: pc_9KDstatus: SUCCESSdeclined: nothing postedledger postingsfrom: attempt 2wallet +40.00clearing -40.00
One request, many attempts, postings only for money that moved. The request is what the customer asked for, and each attempt is one try with a provider. Part II builds the ledger behind the postings box.

Splitting them means a declined attempt never leaves half-written money records behind, and a retried attempt never overwrites the evidence of the first one. When finance asks “what happened to this payment?”, the answer is a list of facts rather than one row that has been overwritten five times.

Implementing the state machine in PostgreSQL

We enforce the rules in two places: the database makes sure only known states can be stored, and every status change is a conditional update that only succeeds from the state we expected. The schema below is simplified (one attempt per payment, to keep the examples short), but the ideas carry over.

schema.sqlPostgreSQL
CREATE TABLE payments (
    id                  text PRIMARY KEY,          -- e.g. 'pay_81', generated by us
    customer_id         text NOT NULL,
    wallet_id           text NOT NULL,
    idempotency_key     text NOT NULL,
    amount_minor        bigint NOT NULL CHECK (amount_minor > 0),
    currency            text NOT NULL,
    provider            text,
    provider_payment_id text,
    status              text NOT NULL DEFAULT 'CREATED'
        CHECK (status IN ('CREATED', 'PENDING', 'PROCESSING', 'SUCCESS',
                          'FAILED', 'CANCELLED', 'REFUNDED', 'REVERSED')),
    created_at          timestamptz NOT NULL DEFAULT now(),
    updated_at          timestamptz NOT NULL DEFAULT now(),
    UNIQUE (customer_id, idempotency_key),
    UNIQUE (provider, provider_payment_id)
);

-- Every status change is recorded, so we can always explain how a payment got here.
CREATE TABLE payment_status_history (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    payment_id  text NOT NULL REFERENCES payments (id),
    from_status text NOT NULL,
    to_status   text NOT NULL,
    reason      text NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);

-- Events that tried to make an illegal move, kept for a person or a job to resolve.
CREATE TABLE payment_anomalies (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    payment_id  text NOT NULL REFERENCES payments (id),
    kind        text NOT NULL,
    detail      text NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now(),
    resolved_at timestamptz,
    UNIQUE (payment_id, kind)
);

The CHECK constraint means a typo like 'SUCCES' is rejected by the database, not discovered in a report three months later (PostgreSQL: constraints). The two UNIQUE constraints stop the same idempotency key creating two payments, and the same provider payment being attached to two of ours. PostgreSQL treats NULLs as distinct by default, so payments that don't have a provider ID yet don't clash.

A status change is then always a conditional update: change the status only if it is still what we think it is.

conditional updatePostgreSQL
UPDATE payments
   SET status = 'SUCCESS', updated_at = now()
 WHERE id = 'pay_81'
   AND status = 'PROCESSING';
-- PostgreSQL reports "UPDATE 1" if we made the move, "UPDATE 0" if the status had already changed.

PostgreSQL's command tag reports how many rows the UPDATE changed (PostgreSQL: UPDATE). Zero rows means someone else changed the status first, so our view was stale. This pattern is called compare-and-swap: compare the current value with what you expect, and swap in the new value only if they match. Chapter 7 covers it in depth.

If several services write to the same table, you can also put the transition rules themselves in the database, so no writer can skip them:

transition rules as dataPostgreSQL
CREATE TABLE payment_transitions (
    from_status text NOT NULL,
    to_status   text NOT NULL,
    PRIMARY KEY (from_status, to_status)
);

INSERT INTO payment_transitions (from_status, to_status) VALUES
    ('CREATED', 'PENDING'), ('CREATED', 'CANCELLED'),
    ('PENDING', 'PROCESSING'), ('PENDING', 'SUCCESS'), ('PENDING', 'FAILED'), ('PENDING', 'CANCELLED'),
    ('PROCESSING', 'SUCCESS'), ('PROCESSING', 'FAILED'),
    ('SUCCESS', 'REFUNDED'), ('SUCCESS', 'REVERSED');

-- $1 = payment id, $2 = expected current status, $3 = new status
UPDATE payments p
   SET status = $3, updated_at = now()
 WHERE p.id = $1
   AND p.status = $2
   AND EXISTS (SELECT 1 FROM payment_transitions t
                WHERE t.from_status = $2 AND t.to_status = $3);

The same rules in Go

In application code, the rules live in one map, and every status change goes through one function. The function checks the move is legal, makes the conditional update, and writes the history row, all inside the caller's transaction.

payments/status.goGo
type Status string

const (
	Created    Status = "CREATED"
	Pending    Status = "PENDING"
	Processing Status = "PROCESSING"
	Success    Status = "SUCCESS"
	Failed     Status = "FAILED"
	Cancelled  Status = "CANCELLED"
	Refunded   Status = "REFUNDED"
	Reversed   Status = "REVERSED"
)

// transitions is the state machine: the moves we allow, and nothing else.
// Failed, Cancelled, Refunded and Reversed are terminal, so they have no entry.
var transitions = map[Status][]Status{
	Created:    {Pending, Cancelled},
	Pending:    {Processing, Success, Failed, Cancelled},
	Processing: {Success, Failed},
	Success:    {Refunded, Reversed},
}

var (
	ErrIllegalTransition = errors.New("illegal status transition")
	ErrStaleStatus       = errors.New("status changed concurrently")
)

func CanTransition(from, to Status) bool {
	return slices.Contains(transitions[from], to)
}

// Transition moves a payment from one status to another inside tx.
// It fails if the move is illegal, or if the payment is no longer in from.
func Transition(ctx context.Context, tx pgx.Tx, paymentID string, from, to Status, reason string) error {
	if !CanTransition(from, to) {
		return fmt.Errorf("%w: %s -> %s", ErrIllegalTransition, from, to)
	}
	tag, err := tx.Exec(ctx,
		`UPDATE payments SET status = $1, updated_at = now() WHERE id = $2 AND status = $3`,
		to, paymentID, from)
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrStaleStatus
	}
	_, err = tx.Exec(ctx,
		`INSERT INTO payment_status_history (payment_id, from_status, to_status, reason)
		 VALUES ($1, $2, $3, $4)`,
		paymentID, from, to, reason)
	return err
}

Now the handler for a provider event. It locks the payment row, compares what the provider says with what we have, and decides between four outcomes: duplicate, legal move, dangerous late success, or harmless stale event.

payments/events.goGo
// ApplyProviderStatus records what the provider told us, if it is a legal move.
func ApplyProviderStatus(ctx context.Context, pool *pgxpool.Pool, paymentID string, reported Status) error {
	return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
		var current Status
		err := tx.QueryRow(ctx,
			`SELECT status FROM payments WHERE id = $1 FOR UPDATE`, paymentID).Scan(&current)
		if err != nil {
			return err // includes pgx.ErrNoRows: an event for a payment we don't know
		}

		switch {
		case current == reported:
			return nil // duplicate delivery: nothing to do

		case CanTransition(current, reported):
			if err := Transition(ctx, tx, paymentID, current, reported, "provider_event"); err != nil {
				return err
			}
			if reported == Success {
				return creditWallet(ctx, tx, paymentID) // same transaction as the status change
			}
			return nil

		case current == Failed && reported == Success:
			// Money may have moved after we gave up. Don't apply it, don't drop it.
			_, err := tx.Exec(ctx, `
				INSERT INTO payment_anomalies (payment_id, kind, detail)
				VALUES ($1, 'LATE_SUCCESS', 'provider reported SUCCESS after we marked FAILED')
				ON CONFLICT (payment_id, kind) DO NOTHING`, paymentID)
			return err

		default:
			return nil // stale event, e.g. PROCESSING after SUCCESS: log it and move on
		}
	})
}

The SELECT … FOR UPDATE locks the payment row until the transaction ends, so two events for the same payment are handled one after the other instead of interleaving.

Inside that lock, the conditional update in Transition can't lose a race. I keep it anyway, because other code paths (an admin tool, a reconciliation job) might change the status without taking the lock, and the database guard covers those too. creditWallet is the same credit as in ApplySuccess from Chapter 1, written to run inside an existing transaction.

Trade-offs and alternatives

  • Rules in code, rules in the database, or both. Rules in a Go map are easy to read and test. Rules in a table, or a trigger, also protect you from scripts and other services. For a payment table, I'd keep the map as the readable source and add the database check once more than one service writes to it.
  • Locking first vs compare-and-swap only. FOR UPDATE makes concurrent events wait in line, which is simple to reason about. A plain conditional update with no lock is cheaper and fine when there's little contention. Chapter 7 compares them properly.
  • How many states. Real systems often need a few more, like PARTIALLY_REFUNDED or REQUIRES_ACTION. Add them when a real flow needs them, and update the diagram, the table and the map together.
  • Workflow engines. Tools like Temporal or AWS Step Functions can run the steps of a long payment flow for you. They don't replace the payment state in your own database, which is what finance, support and reconciliation read. Chapter 12 covers when they are worth it.

Common mistakes

  • Writing the status straight from the provider's event without checking the current status.
  • Treating “provider acknowledged” as “paid” for payouts.
  • Deleting or overwriting a failed attempt when the customer retries, instead of creating a new attempt.
  • Letting a late SUCCESS overwrite FAILED, or ignoring it without a record.
  • Putting reconciliation results in the same status column as the payment flow.
  • Having no history table, so nobody can explain how a payment reached its current state.

What to monitor and test

Monitor: the number of payments in each non-terminal state and the age of the oldest; the rate of ErrStaleStatus and of illegal-transition attempts, broken down by from/to; and every new row in payment_anomalies, which should page someone during working hours.

Test: deliver every event type in every order; deliver each event twice; deliver SUCCESS to a FAILED payment and expect exactly one anomaly and no credit; run two transitions on one payment concurrently and expect exactly one to win; and check, in a test, that the Go map and the payment_transitions rows contain the same pairs.

Checklist

  • Payment status is one column with a CHECK constraint, not a set of booleans.
  • Allowed transitions are written down once, and the diagram, table and code match.
  • Every status change is conditional on the current status.
  • Every status change writes a history row in the same transaction.
  • Terminal states have no way out.
  • Illegal transitions that might mean money moved are recorded as anomalies and alerted on.
  • Payouts are only SETTLED on real confirmation, not on acknowledgement.
  • Requests, attempts and postings are separate records.

Further reading

What's next

We now know what a payment is and how to say where it is in its life. But we have been crediting a balance_minor column and waving our hands about “ledger postings”. Part II, Financial Data Correctness, fixes that: how to represent money without rounding bugs, how to build an immutable ledger where every balance can be explained, and how to enforce the rules that must never break.

If this was useful

Pass it on to someone who's building or fixing a payment system, or share it with your network. The handbook is free, and people passing it on is how it reaches the engineers it was written for.

I post new writing on LinkedIn and X.

Have a backend or payments problem to solve?

Tell me what you are building and where it hurts. I reply within one working day, usually with a time for a 30-minute call.