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
| Component | Responsibility | Must never | Part |
|---|---|---|---|
| API service | Validate, check idempotency keys, record intent, start provider calls with derived keys | Hold a transaction across a provider call | III, V |
| Webhook ingest | Verify signatures, store raw events, announce them, reply 200 | Reply 200 before the event is committed | IV |
| PostgreSQL | Payments, workflows, ledger, balances, keys, inboxes, outbox, discrepancies | Be bypassed by any path that moves money | I, II |
| Outbox publisher | Publish committed events, retry with backoff, recover leases | Generate a new event ID on republication | IV |
| SNS and SQS | Fan events out to one queue per consumer; absorb bursts | Be the only place a payment exists | IV |
| wallet-credit consumer | Apply payment results: state, journal, next event | Apply the same payment twice | all |
| Payout worker | Run withdrawals as a resumable workflow | Compensate an unknown outcome | V, VI |
| Sweeper | Find stuck payments and workflows, resolve forward | Guess an outcome it hasn't confirmed | V, VI |
| Reconciliation | Match against provider reports and bank statements | Edit records to make numbers agree | VII |
| Redis | Leases for coordination, caches | Hold anything that guards money | III |
| Observability | Logs, traces, metrics, SLO alerts, runbooks | Log card numbers or secrets | VII |
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
- Initiation. The app sends
POST /paymentswith anIdempotency-Key. The API claims the key and inserts the payment inCREATED, in one transaction (Part III). - Provider. PayCo is called outside any transaction, with our payment ID as its idempotency key. The payment moves to
PENDINGwhile the customer approves (Part I). - 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). - Queue. The outbox publisher sends a normalised
payment.succeededenvelope to SNS, which delivers it to the credit queue. - Idempotency. The consumer records the event in its inbox. A repeat of this event stops here.
- Database transaction. Lock the payment row, check the amount against our record, check the transition is legal, move to
SUCCESSwith a history row. - Ledger. Post a balanced journal (wallet up, clearing down) and update balances (Part II).
- Outbox. Write
payment.credited. Commit everything at once. - Notification. A separate consumer of
payment.creditedpushes “€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.
// 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, ¤cy)
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
- Request. The app asks to withdraw €80. The API validates limits and the destination account and records the withdrawal as
REQUESTED. - 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). - Intent. It records
PAYOUT_INITIATEDbefore calling the provider, so a crash from here on is known to have a payout possibly in flight. - 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). - Acknowledgement.
PAYOUT_ACKNOWLEDGED: the provider has taken responsibility, but the money hasn't arrived. - Settlement. Days later, a settlement report confirms it. The withdrawal becomes
SETTLED, with a journal from “in transit” to “settled”. - Reconciliation. The bank statement line is matched to the payout (Part VII).
Flow C: duplicate and delayed events
There are three kinds of “again” here, and each is stopped at a different layer:
- The same delivery again (PayCo resends
evt_31): the rawprovider_eventsinsert conflicts, the webhook replies200, 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
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.
// 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")
}
}$ 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:
$ 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)
PASSThe three principles, revisited
The handbook opened with three rules. This is where each one ended up:
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_minorcolumn 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
FAILEDpayments; Part VI extended that toCANCELLED, 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:
| Question | How 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:
- The state machine and integer money (I, II). Cheap to do now, expensive to retrofit.
- The ledger, double-entry and append-only, from the first payment (II).
- Idempotency everywhere: API keys, an inbox per consumer, derived provider keys (III).
- The outbox, as soon as a second service needs to hear about payments (IV).
- Daily reconciliation against the provider, even as a script at first (VII).
- Tests for duplicates, races and crashes, against a real database, not only the happy path.
- 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
- The eight parts of this handbook, each with its own sources: Part I, Part II, Part III, Part IV, Part V, Part VI, Part VII.
- PostgreSQL documentation: transactions, isolation, constraints, triggers.
- Amazon SQS developer guide and the transactional outbox pattern.
- Google's SRE books: overload, cascading failures, monitoring and SLO alerting.
- Martin Kleppmann: How to do distributed locking.
- Stripe: idempotent requests: a large provider's view of the same problems.
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.