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

Putting it all together

Every part of the handbook assembled into one architecture, with four complete flows through it and one end-to-end test that runs them all against a real database.

Chapters 2126 min readPublished 23 Nov 2026

Seven parts, twenty chapters, and a lot of separate mechanisms: state machines, ledgers, idempotency keys, inboxes, outboxes, leases, sweepers, breakers, reconciliation. Each one was shown on its own. This last part puts them in one picture and shows they still hold when they run together.

Chapter 21 assembles the architecture and walks four complete flows through it: a successful payment, a withdrawal, a duplicate and delayed event, and an administrative cancellation. Then comes the bit I trust more than any diagram, a single end-to-end test that runs all four flows through the real code from every earlier part, against PostgreSQL, and checks the ledger afterwards.

Chapter 21

End-to-end payment architecture

The architecture

The complete payment architectureThe customer app calls the API service, which charges PayCo with the payment ID as its key. PayCo calls webhook ingest. Both write to PostgreSQL, which holds payments, withdrawals, the ledger, balances, idempotency keys, inboxes, the outbox and reconciliation discrepancies. An outbox publisher sends events to an SNS topic, which fans out to credit, notify and payout queues, each with its consumer writing back to PostgreSQL. The payout worker calls the payout provider. A sweeper and a reconciliation service also work against PostgreSQL, reconciliation using reports and bank statements. Redis holds leases and caches only. Logs, traces, metrics, alerts and runbooks cover everything. customer appPayCocard paymentsAPI serviceidempotency keyswebhook ingestverify, store, 200charge, key = pay_81PostgreSQL: the truthpayments · withdrawalsstatus history · anomaliesledger journals + entriesaccount balancesidempotency keysprovider_events (inbox)processed_events (inbox)outboxrecon discrepanciesoutbox publisherSNS topiccredit queuewallet-creditnotify queuenotificationspayout queuepayout workerpayout providersweeperstuck workflowsreconciliationreports, bankstatementsRedisleases, caches: never moneylogs · traces · metrics · SLO alerts · runbooks
One source of truth, everything else around it. Every arrow into PostgreSQL is a transaction that either fully happens or doesn’t. Arrows out of it all go through the outbox. Queues, Redis and providers can fail, repeat or lie, and the boxes in the middle still hold the right answer.
Components and their responsibilities
ComponentResponsibilityMust neverPart
API serviceValidate, check idempotency keys, record intent, start provider calls with derived keysHold a transaction across a provider callIII, V
Webhook ingestVerify signatures, store raw events, announce them, reply 200Reply 200 before the event is committedIV
PostgreSQLPayments, workflows, ledger, balances, keys, inboxes, outbox, discrepanciesBe bypassed by any path that moves moneyI, II
Outbox publisherPublish committed events, retry with backoff, recover leasesGenerate a new event ID on republicationIV
SNS and SQSFan events out to one queue per consumer; absorb burstsBe the only place a payment existsIV
wallet-credit consumerApply payment results: state, journal, next eventApply the same payment twiceall
Payout workerRun withdrawals as a resumable workflowCompensate an unknown outcomeV, VI
SweeperFind stuck payments and workflows, resolve forwardGuess an outcome it hasn't confirmedV, VI
ReconciliationMatch against provider reports and bank statementsEdit records to make numbers agreeVII
RedisLeases for coordination, cachesHold anything that guards moneyIII
ObservabilityLogs, traces, metrics, SLO alerts, runbooksLog card numbers or secretsVII

I kept the shape simple on purpose. PostgreSQL is the one source of truth, and any change to it that involves money is a single transaction that either fully happens or doesn't. Announcements of those changes leave through the outbox and nowhere else. Queues, caches, providers and workers are all allowed to be slow, to repeat themselves or to fail, since the guards at the centre make those outcomes harmless.

Flow A: a successful customer payment

Flow A: a successful customer paymentThe app posts a payment with an idempotency key. The API records it as CREATED and charges PayCo with key pay_81. The customer approves. PayCo sends a succeeded webhook, evt_31. Webhook ingest stores the event and an outbox row in one transaction and replies 200. The outbox publishes through SNS and SQS to the wallet-credit consumer, which in one transaction checks its inbox, locks the payment, moves it to SUCCESS, posts the journal and writes an outbox event. It deletes the message, and a payment.credited notification reaches the app. appAPIPayCowebhookPostgreSQLwallet-creditPOST /payments + keypayment CREATED (+ key)charge, key pay_81customer approvessucceeded evt_31event + outbox (1 tx)200outbox → SNS → SQSinbox · lock · SUCCESS · journal · outboxdelete messagepayment.credited → push “€40 added”one charge · one journal · one credit · one notification
Every step that touches money is one transaction, and every hop between them is retryable. When something fails between two arrows, the step runs again and the guards make the repeat harmless.
  1. Initiation. The app sends POST /payments with an Idempotency-Key. The API claims the key and inserts the payment in CREATED, in one transaction (Part III).
  2. Provider. PayCo is called outside any transaction, with our payment ID as its idempotency key. The payment moves to PENDING while the customer approves (Part I).
  3. Webhook. PayCo sends “succeeded”. Ingest verifies the signature, stores the raw event (deduplicated on PayCo's event ID) and an outbox row in one transaction, then replies 200 (Part IV).
  4. Queue. The outbox publisher sends a normalised payment.succeeded envelope to SNS, which delivers it to the credit queue.
  5. Idempotency. The consumer records the event in its inbox. A repeat of this event stops here.
  6. Database transaction. Lock the payment row, check the amount against our record, check the transition is legal, move to SUCCESS with a history row.
  7. Ledger. Post a balanced journal (wallet up, clearing down) and update balances (Part II).
  8. Outbox. Write payment.credited. Commit everything at once.
  9. Notification. A separate consumer of payment.credited pushes “€40 added” to the app.

Steps 5 to 8 are the heart of the system, and they fit in one function. It's assembled from the pieces built in Parts I to IV, and the comments name the part each line comes from.

consumer/credit.goGo
// paymentSucceeded is the payload of a normalised payment.succeeded event (Part IV).
type paymentSucceeded struct {
	PaymentID   string `json:"payment_id"`
	AmountMinor int64  `json:"amount_minor"`
	Currency    string `json:"currency"`
}

// ApplyPaymentSucceeded is the whole job of the wallet-credit consumer, assembled from
// the earlier parts. Everything inside HandleOnce commits in one transaction, or not at all.
func ApplyPaymentSucceeded(ctx context.Context, pool *pgxpool.Pool, ev Envelope) error {
	var p paymentSucceeded
	if err := json.Unmarshal(ev.Payload, &p); err != nil {
		return fmt.Errorf("bad payload: %w", err)
	}
	_, err := HandleOnce(ctx, pool, "wallet-credit", ev.EventID, func(tx pgx.Tx) error { // Part III: inbox
		var status Status
		var walletAccount, currency string
		var amountMinor int64
		err := tx.QueryRow(ctx, `
			SELECT status, wallet_id, amount_minor, currency
			  FROM payments WHERE id = $1 FOR UPDATE`, p.PaymentID). // Part III: row lock
			Scan(&status, &walletAccount, &amountMinor, &currency)
		if err != nil {
			return err
		}
		switch {
		case status == Success:
			return nil // already applied by another path: a poll, reconciliation, another event
		case amountMinor != p.AmountMinor || currency != p.Currency:
			return ErrAmountMismatch // Part I: never trust the event's amount blindly
		case status == Failed || status == Cancelled:
			_, err := tx.Exec(ctx, `
				INSERT INTO payment_anomalies (payment_id, kind, detail)
				VALUES ($1, 'LATE_SUCCESS', $2)
				ON CONFLICT (payment_id, kind) DO NOTHING`,
				p.PaymentID, "provider reported SUCCESS after we marked "+string(status)) // Part VI
			return err
		case !CanTransition(status, Success):
			return nil // stale, e.g. after REVERSED: log it and move on
		}
		if err := Transition(ctx, tx, p.PaymentID, status, Success, "provider_event"); err != nil { // Part I
			return err
		}
		amount := decimal.New(amountMinor, -minorUnits[currency]) // Part II: exact money
		err = Post(ctx, tx, Journal{                               // Part II: balanced journal + balances
			ID: "j_" + p.PaymentID, Kind: "PAYMENT", SourceType: "transaction", SourceID: p.PaymentID,
			CreatedBy: "wallet-credit", EffectiveAt: time.Now(),
			Entries: []Entry{
				{AccountID: walletAccount, Asset: currency, Amount: amount},
				{AccountID: "plat:clearing:" + currency, Asset: currency, Amount: amount.Neg()},
			},
		})
		if err != nil {
			return err
		}
		return enqueueEvent(ctx, tx, "payment", p.PaymentID, "payment.credited", // Part IV: outbox
			map[string]string{"payment_id": p.PaymentID})
	})
	return err
}

The function is short because the hard parts were built earlier and each does one job. That switch holds the complete decision table from Part I and Part VI in a few lines: already applied, amount wrong, late success on a dead payment, stale event, or apply.

Flow B: a withdrawal

Flow B: a withdrawal from request to settlementThe app requests a withdrawal of 80 euros, recorded as REQUESTED. The payout worker reserves the funds by moving them from the wallet to an in-transit account, marks the payout initiated, and sends it to the payout provider with key payout:wd_88. The reply is lost, so it sends again with the same key and gets the original payout back, then records PAYOUT_ACKNOWLEDGED. Days later a settlement report moves the withdrawal to SETTLED, and reconciliation matches the bank line. appPostgreSQLpayout workerpayout providerbank + reconwithdraw €80 → REQUESTEDreserve: wallet → in transitFUNDS_RESERVEDPAYOUT_INITIATED (intent)payout, key payout:wd_88reply lostsame key againpo_payout:wd_88PAYOUT_ACKNOWLEDGEDdays later…settlement report → SETTLEDin transit → settledbank line matched
Reservation, acknowledgement and settlement are three different moments. Money stops being spendable at reservation and the provider takes responsibility at acknowledgement, but it hasn’t arrived until settlement. Each gets its own state and its own journal.
  1. Request. The app asks to withdraw €80. The API validates limits and the destination account and records the withdrawal as REQUESTED.
  2. Reservation. The payout worker moves €80 from the wallet to “payouts in transit” with a balanced journal, guarded against overdraft, and marks FUNDS_RESERVED: one transaction (Part V).
  3. Intent. It records PAYOUT_INITIATED before calling the provider, so a crash from here on is known to have a payout possibly in flight.
  4. Provider. It sends the payout with the derived key payout:wd_88. In the diagram, the reply is lost; the retry sends the same key and gets the same payout back (Part VI, scenario 6).
  5. Acknowledgement. PAYOUT_ACKNOWLEDGED: the provider has taken responsibility, but the money hasn't arrived.
  6. Settlement. Days later, a settlement report confirms it. The withdrawal becomes SETTLED, with a journal from “in transit” to “settled”.
  7. Reconciliation. The bank statement line is matched to the payout (Part VII).

Flow C: duplicate and delayed events

Flow C: duplicate and delayed payment eventsPayCo resends evt_31; the webhook finds it already in provider_events and replies 200 without doing anything. PayCo then sends evt_35, a new event for the same payment; it is stored and delivered, the consumer’s inbox sees a new event but the payment is already SUCCESS, so nothing happens. A success for a payment that was cancelled is recorded as an anomaly with no credit. PayCowebhookPostgreSQLwallet-creditevt_31 againprovider_events: conflict200, nothing elseevt_35: same payment, new IDnew event + outboxdeliveredinbox new · status already SUCCESSno-opsuccess for a CANCELLED paymentanomaly recorded, no creditthree layers of “seen it”: raw event, inbox, payment status
Each kind of duplicate is stopped at its own layer. The raw event table catches a repeated delivery and the inbox a repeated event. A known payment arriving under a new event ID is caught by the payment’s status.

There are three kinds of “again” here, and each is stopped at a different layer:

  • The same delivery again (PayCo resends evt_31): the raw provider_events insert conflicts, the webhook replies 200, and nothing is published (Part IV).
  • The same event again (the outbox republishes, or SQS redelivers): the consumer's inbox already has the event ID, so nothing runs (Part III).
  • The same payment as a different event (PayCo sends a new event ID for a payment we've already applied, or the status poller found it first): the payment is already SUCCESS, so the consumer does nothing.

Then there's the dangerous kind of late: a success for a payment that is already FAILED or CANCELLED, which probably means money moved after we gave up. The consumer doesn't apply it and doesn't drop it. It records an anomaly for a person and for reconciliation (Part VI, scenario 10).

An administrative cancellation

Administrative cancellation as one transactionInside one transaction: lock the payment row, check the state transition from SUCCESS to REVERSED is legal, post a compensating journal reversing the original, update balances with the overdraft guard, move the status with a history row, and commit. A second admin waits on the row lock, then sees REVERSED and does nothing. one transactionlock the payment rowFOR UPDATEcheck the stateSUCCESS → REVERSED legal?compensating journalreverses j_pay_81update balancesoverdraft guardmove the statusTransition + historycommitall or nothingsecond adminwaits here……then seesREVERSED anddoes nothing
The database does all the work here. The row lock handles concurrency, the state check and the unique reversal key make it idempotent, and the transaction makes it atomic.

Cancellation of a successful payment is Part III's CancelPayment: lock the row, check that SUCCESS → REVERSED is a legal move, post a compensating journal that references the original (Part II), update balances, move the status with a history row, commit. If a second admin, a retry or a racing webhook turns up, it waits on the same row lock and then finds nothing left to do.

If cancelling should also return money to the customer's card, that is a separate refund operation through the provider, with its own key and lifecycle, started after this commit.

Proving it: one test, four flows

Diagrams can be wrong, so this test runs every flow above through the real code from Parts I to VII, against PostgreSQL with every migration applied. It uses a few small helpers that aren't shown here (testDB gives each test a fresh database, plus a seeded wallet and a fake PayCo that can lose a reply), plays the outbox publisher into a fake SNS, and finishes with the ledger checks from Part II.

endtoend_test.goGo
// publishAll plays the outbox publisher (Part IV) into a fake SNS and returns the envelopes.
func publishAll(t *testing.T, pool *pgxpool.Pool, eventType string) []Envelope {
	t.Helper()
	ctx := context.Background()
	rows, err := pool.Query(ctx, claimSQL)
	if err != nil {
		t.Fatal(err)
	}
	batch, err := pgx.CollectRows(rows, pgx.RowToStructByPos[outboxRow])
	if err != nil {
		t.Fatal(err)
	}
	var out []Envelope
	for _, r := range batch {
		if _, err := pool.Exec(ctx, markPublishedSQL, r.ID); err != nil {
			t.Fatal(err)
		}
		if r.EventType == eventType {
			out = append(out, Envelope{EventID: r.EventID, Type: r.EventType, Version: 1, Payload: r.Payload})
		}
	}
	return out
}

func TestEndToEnd(t *testing.T) {
	pool := testDB(t)
	seedWallet(t, pool, "0")
	ctx := context.Background()
	exec := func(sql string, args ...any) {
		t.Helper()
		if _, err := pool.Exec(ctx, sql, args...); err != nil {
			t.Fatal(err)
		}
	}
	status := func(table, id string) (s string) {
		pool.QueryRow(ctx, `SELECT status FROM `+table+` WHERE id = $1`, id).Scan(&s)
		return s
	}

	// Flow A: a successful customer payment.
	exec(`INSERT INTO payments (id, customer_id, wallet_id, idempotency_key, amount_minor, currency, provider, provider_payment_id, status)
	      VALUES ('pay_81', 'c_42', 'cust:c_42:wallet:EUR', 'k_81', 4000, 'EUR', 'payco', 'pc_9KD', 'PROCESSING')`)
	err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { // what webhook normalisation writes
		return enqueueEvent(ctx, tx, "payment", "pay_81", "payment.succeeded",
			map[string]any{"payment_id": "pay_81", "amount_minor": 4000, "currency": "EUR"})
	})
	if err != nil {
		t.Fatal(err)
	}
	events := publishAll(t, pool, "payment.succeeded")
	if err := ApplyPaymentSucceeded(ctx, pool, events[0]); err != nil {
		t.Fatal(err)
	}
	credited := publishAll(t, pool, "payment.credited")
	t.Logf("Flow A: payment=%s wallet=%s payment.credited events=%d", status("payments", "pay_81"), walletBalance(t, pool), len(credited))

	// Flow C: the same event redelivered 5 times at once, plus a delayed duplicate with a new event ID.
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); _ = ApplyPaymentSucceeded(ctx, pool, events[0]) }()
	}
	wg.Wait()
	late := events[0]
	late.EventID = "a-different-event-id-for-the-same-payment"
	if err := ApplyPaymentSucceeded(ctx, pool, late); err != nil {
		t.Fatal(err)
	}
	var journals int
	pool.QueryRow(ctx, `SELECT count(*) FROM ledger_journals WHERE source_id = 'pay_81' AND kind = 'PAYMENT'`).Scan(&journals)
	t.Logf("Flow C: after 6 more deliveries: wallet=%s PAYMENT journals=%d", walletBalance(t, pool), journals)

	// Flow C, worse: a success arriving for a payment the customer already cancelled.
	exec(`INSERT INTO payments (id, customer_id, wallet_id, idempotency_key, amount_minor, currency, status)
	      VALUES ('pay_82', 'c_42', 'cust:c_42:wallet:EUR', 'k_82', 1500, 'EUR', 'CANCELLED')`)
	payload, _ := json.Marshal(map[string]any{"payment_id": "pay_82", "amount_minor": 1500, "currency": "EUR"})
	if err := ApplyPaymentSucceeded(ctx, pool, Envelope{EventID: "evt_late_82", Payload: payload}); err != nil {
		t.Fatal(err)
	}
	var anomalies int
	pool.QueryRow(ctx, `SELECT count(*) FROM payment_anomalies WHERE payment_id = 'pay_82'`).Scan(&anomalies)
	t.Logf("Flow C: late success on CANCELLED: payment=%s anomalies=%d wallet=%s", status("payments", "pay_82"), anomalies, walletBalance(t, pool))

	// Admin cancellation, racing a redelivery of the original event.
	wg.Add(2)
	go func() { defer wg.Done(); _ = CancelPayment(ctx, pool, "pay_81", "alice", "customer complaint") }()
	go func() { defer wg.Done(); _ = ApplyPaymentSucceeded(ctx, pool, events[0]) }()
	wg.Wait()
	t.Logf("Cancellation: payment=%s wallet=%s", status("payments", "pay_81"), walletBalance(t, pool))

	// Flow B: fund the wallet, then withdraw 80.00 to the end.
	credit(t, pool, "topup_1", "100.00")
	exec(`INSERT INTO withdrawals (id, customer_id, wallet_account_id, amount_minor, currency, destination_id)
	      VALUES ('wd_88', 'c_42', 'cust:c_42:wallet:EUR', 8000, 'EUR', 'ba_1')`)
	engine := &WithdrawalEngine{Pool: pool, Payouts: &fakePayCo{payouts: map[string]string{}, loseReplies: 1}}
	for i := 0; i < 4; i++ { // reserve, send (reply lost), send again, nothing left to do
		_ = engine.Advance(ctx, "wd_88")
	}
	if err := engine.Settle(ctx, "wd_88"); err != nil {
		t.Fatal(err)
	}
	t.Logf("Flow B: withdrawal=%s wallet=%s", status("withdrawals", "wd_88"), walletBalance(t, pool))

	// The ledger checks from Part II must all return zero rows.
	checks := map[string]string{
		"unbalanced journals": `SELECT journal_id FROM ledger_entries GROUP BY journal_id, asset HAVING sum(amount) <> 0`,
		"ledger not net zero": `SELECT asset FROM ledger_entries GROUP BY asset HAVING sum(amount) <> 0`,
		"projection drift": `SELECT b.account_id FROM account_balances b LEFT JOIN ledger_entries e ON e.account_id = b.account_id
		                     GROUP BY b.account_id, b.balance HAVING b.balance <> coalesce(sum(e.amount), 0)`,
	}
	for name, q := range checks {
		var n int
		pool.QueryRow(ctx, `SELECT count(*) FROM (`+q+`) x`).Scan(&n)
		t.Logf("ledger check %-20s rows=%d", name, n)
		if n != 0 {
			t.Fatalf("%s: %d rows", name, n)
		}
	}

	if status("payments", "pay_81") != "REVERSED" || journals != 1 || anomalies != 1 ||
		status("withdrawals", "wd_88") != "SETTLED" || walletBalance(t, pool) != "20.00" {
		t.Fatal("end-to-end invariants violated")
	}
}
real output, PostgreSQL 17Output
$ go test -run TestEndToEnd -v ./...
    endtoend_test.go:67: Flow A: payment=SUCCESS wallet=40.00 payment.credited events=1
    endtoend_test.go:83: Flow C: after 6 more deliveries: wallet=40.00 PAYMENT journals=1
    endtoend_test.go:94: Flow C: late success on CANCELLED: payment=CANCELLED anomalies=1 wallet=40.00
    endtoend_test.go:101: Cancellation: payment=REVERSED wallet=0.00
    endtoend_test.go:114: Flow B: withdrawal=SETTLED wallet=20.00
    endtoend_test.go:126: ledger check unbalanced journals  rows=0
    endtoend_test.go:126: ledger check ledger not net zero  rows=0
    endtoend_test.go:126: ledger check projection drift     rows=0
--- PASS: TestEndToEnd (0.10s)

Follow the wallet value down the output. It's €40 after the payment, and still €40 after six more deliveries of the same success, five of them at once and one with a different event ID. A success for a cancelled payment leaves it at €40 too; that one was recorded as an anomaly.

The cancellation takes it to €0, even with a redelivery racing it. Then €100 is topped up and €80 withdrawn through a lost reply and a retry, leaving €20. After all that, every journal balances, the ledger nets to zero, and every balance matches its entries.

And the full suite, with Go's race detector on:

real output, the complete suiteOutput
$ go test -race -count=1 -v ./...
--- PASS: TestEndToEnd (0.06s)
--- PASS: TestSameEventDeliveredTenTimes (0.04s)
--- PASS: TestCrashAfterCommitBeforeAck (0.03s)
--- PASS: TestCrashAfterPublishBeforeMark (0.04s)
--- PASS: TestProviderTimesOutAfterAccepting (0.05s)
--- PASS: TestVisibilityExpiresWhileProcessing (0.35s)
--- PASS: TestPoolExhaustionFailsFast (0.26s)
--- PASS: TestTwoAdminsCancelAtOnce (0.05s)
--- PASS: TestShutdownDrainsInFlightWork (0.27s)
--- PASS: FuzzAllocate (0.00s)
PASS

The three principles, revisited

The handbook opened with three rules. This is where each one ended up:

The three principles and the mechanisms that deliver themNever move money twice: idempotency keys, inboxes, compare-and-swap state transitions, unique journal sources, derived provider keys. Never lose track of money: an immutable ledger, an outbox for every event, durable workflow state, reconciliation, status history and anomalies. Never blindly trust a component: timeouts treated as unknown, amount checks on events, constraints and triggers, leases that aren’t locks, and independent sources. Never move money twice• idempotency keys (III)• inbox per consumer (III)• CAS state transitions (I, III)• unique journal sources (II)• derived provider keys (III, V)Never lose track of money• immutable ledger (II)• outbox for every event (IV)• durable workflow state (V)• reconciliation (VII)• status history + anomalies (I)Never blindly trust a component• timeouts are “unknown” (I)• amount checks on events (I)• constraints + triggers (II)• leases aren’t locks (III, IV)• independent sources (VII)
Every mechanism in the handbook serves one of three rules. Roman numerals are the parts that introduce them. When you design something new, work out which rule it protects and check that the other two still hold.

What this handbook is, and isn't

It's a set of patterns with working example code, not a production system you can deploy as-is. I made a few simplifications on purpose, and I'd rather list them than have anyone mistake them for recommendations:

  • Part I credits a balance_minor column directly; Part II replaces that with the ledger, and the assembled consumer above uses the ledger.
  • Part I's event handler recorded late successes only for FAILED payments; Part VI extended that to CANCELLED, and the assembled consumer includes both.
  • The schemas keep one provider attempt per payment for brevity, although Part I explains why requests, attempts and postings should be separate records.
  • Authentication, authorisation, PCI DSS scope, encryption, fraud checks and the full chart of accounts are out of scope, though a real system needs every one of them.
  • Provider names, IDs and amounts are fictional, and numbers are illustrative unless a source or a measurement is shown next to them.

How the handbook was checked

The original brief for this handbook ended with a consistency review. This is how each of its questions was answered:

The consistency review
QuestionHow it was checked
Are all state transitions consistent?One transition map in Go, mirrored in a payment_transitions table; the diagrams were drawn from the same list. The end-to-end test exercises legal, stale and illegal moves
Are idempotency concepts used consistently?The same three layers (raw event, inbox, business guard) appear in every flow; the duplicate tests in Part III and the end-to-end test here exercise all three
Do the ledger examples balance?A deferred trigger rejects unbalanced journals; the ledger checks return zero rows after every test, including the end-to-end run
Are database transactions correctly scoped?No provider call sits inside a transaction anywhere; Part V's three-phase pattern; the pool-exhaustion test
Are retry and visibility timeout examples accurate?Checked against AWS's SQS documentation, which itself says the timeout gives no absolute guarantee; Part IV walks through what happens when the timeout expires mid-message
Are external side effects separated?Record intent, commit, call with a derived key, record the result; the end-to-end test loses a payout reply and still makes exactly one payout
Are the diagrams valid?Hand-drawn SVG generated from code instead of Mermaid; every one rendered and reviewed, with overlaps fixed before publishing
Are the code examples consistent?The Go from all eight parts compiles and passes go vet as one package; SQL ran on PostgreSQL 17; Python examples parse
Are factual claims supported?Each part's claims were checked against primary documentation (PostgreSQL, AWS, Go, Stripe, OpenTelemetry, Prometheus, Google SRE); where a page couldn't be verified, the claim was dropped or reworded
Are patterns distinguished from implementations?This section; and measured numbers (query plans, benchmarks, simulations) are labelled as measured on a local machine

Testing found real problems along the way, and each is told in the part where it happened: a floating-point bug in a retry budget (Part VI) and a regex pattern that didn't match the handbook's own account IDs (Part VII)).

I can't make a better case for the testing approach in this handbook than that: it caught my mistakes before you read them.

If you're starting from scratch

You don't need all of this on day one. With a small team and a new payment system, I'd build it in this order:

  1. The state machine and integer money (I, II). Cheap to do now, expensive to retrofit.
  2. The ledger, double-entry and append-only, from the first payment (II).
  3. Idempotency everywhere: API keys, an inbox per consumer, derived provider keys (III).
  4. The outbox, as soon as a second service needs to hear about payments (IV).
  5. Daily reconciliation against the provider, even as a script at first (VII).
  6. Tests for duplicates, races and crashes, against a real database, not only the happy path.
  7. Then the rest as volume grows: workflow sweepers, connection budgets, retry budgets and breakers, SLO alerts, canaries.

Thank you

If you've read all eight parts, thank you. I wrote this because most of what I know about payment systems I learned from incidents, and I'd rather you learned it from a page. If something here is wrong, unclear or missing, please tell me. And if you're building or fixing a payment system and want a second pair of eyes on it, that's the work I do: see my payments and backend consulting.

Further reading

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.