Parts I to IV made every individual operation correct: idempotent, concurrency-safe, recorded in a ledger and announced through an outbox. This part is about what happens when those operations are chained into long processes, and when thousands of them run at once against one database.
Chapter 12 designs a withdrawal as a workflow that can be killed at any step and resumed safely. Chapter 13 is the performance chapter I'd most like every backend engineer to read: why connections are a budget, how one autoscaler can exhaust it, and how to keep transactions short. Chapter 14 shows how to find and fix slow queries, with real query plans from a local test.
Chapter 12
Designing resumable payment workflows
The problem: a withdrawal is not one step
A customer asks to withdraw €80 to their bank account. That's at least six steps, spread over minutes to days:
- Validate the request: limits, a verified destination account, no open dispute.
- Reserve the funds, so the customer can't spend the same €80 while the payout is in flight.
- Initiate the payout with a payout provider.
- Wait for confirmation: an acknowledgement in seconds, settlement in hours or days.
- Settle if it worked, or compensate (give the money back) if it didn't.
- Reconcile against the provider's report and the bank statement.
Now imagine the process running these steps is killed after step 2: a deploy, an out-of-memory error, a spot instance reclaimed. If the workflow's progress lived only in that process's memory, the €80 stays reserved forever and the customer gets nothing. Kill it during step 3 and it's worse: did the payout go out or not? Retry blindly and you might pay twice.
The mental model: durable state and idempotent steps
A resumable workflow needs two things. First, its state is durable: progress is written to the database at each checkpoint, in the same transaction as the step's effect, so whatever process picks the workflow up next reads the checkpoint and carries on from there. Nothing important lives in memory.
Second, every step is safe to run again. A step can be interrupted at any point, so “run it again” has to be correct every time, which is Part III's idempotency applied step by step.
A state machine (Part I) gives you both. The status column is the checkpoint, and conditional transitions make each step run exactly once even if two workers try it.
The payout states are the ones from Part I, with the funds reservation and release around them. The one to watch is PAYOUT_INITIATED, which means “we have decided to send this payout and may already have sent it”. We record it before calling the provider, so after a crash we always know a payout might be in flight, and we always resend it with the same key.
CREATE TABLE withdrawals (
id text PRIMARY KEY, -- 'wd_88'
customer_id text NOT NULL,
wallet_account_id text NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor > 0),
currency text NOT NULL,
destination_id text NOT NULL, -- a saved, verified bank account
status text NOT NULL DEFAULT 'REQUESTED' CHECK (status IN (
'REQUESTED', 'REJECTED', 'FUNDS_RESERVED', 'PAYOUT_INITIATED',
'PAYOUT_ACKNOWLEDGED', 'SETTLED', 'PAYOUT_FAILED', 'FUNDS_RELEASED')),
provider_payout_id text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- The sweeper only ever looks at withdrawals that are still moving.
CREATE INDEX withdrawals_in_flight ON withdrawals (updated_at)
WHERE status IN ('REQUESTED', 'FUNDS_RESERVED', 'PAYOUT_INITIATED', 'PAYOUT_FAILED');Reservation is not settlement
Reserving funds and settling them are different accounting events. Reservation moves €80 from the customer's wallet into a platform account like “payouts in transit”: the money is no longer spendable, but it hasn't left.
Settlement, when the bank confirms, moves it out of “in transit” for good. Failure moves it back to the wallet with a reversal journal. Using the ledger from Part II, every one of those moves is a balanced journal, so at any moment you can see how much money is in flight.
Which accounts you use depends on your business and your finance team. Some platforms debit the wallet immediately; others place a hold and only debit at settlement. Either is fine as long as the choice is written down and every step is a journal.
The steps in Go
The engine has one entry point, Advance, which looks at the current status and runs the next step. The queue (Part IV), the sweeper below and a support agent's “retry” button can all call it. Each step guards itself with a compare-and-swap on the status.
type WStatus string
const (
WRequested WStatus = "REQUESTED"
WRejected WStatus = "REJECTED"
WReserved WStatus = "FUNDS_RESERVED"
WInitiated WStatus = "PAYOUT_INITIATED"
WAcknowledged WStatus = "PAYOUT_ACKNOWLEDGED"
WSettled WStatus = "SETTLED"
WFailed WStatus = "PAYOUT_FAILED"
WReleased WStatus = "FUNDS_RELEASED"
)
type Withdrawal struct {
ID, CustomerID, WalletAccountID, Currency, DestinationID string
AmountMinor int64
Status WStatus
}
type PayoutResult struct{ ProviderRef string }
// PayoutProvider must be idempotent on key: the same key returns the same payout.
type PayoutProvider interface {
CreatePayout(ctx context.Context, key string, amountMinor int64, currency, destinationID string) (PayoutResult, error)
}
// ErrPayoutRejected means the provider definitely refused: nothing was sent.
var ErrPayoutRejected = errors.New("payout rejected by provider")
type WithdrawalEngine struct {
Pool *pgxpool.Pool
Payouts PayoutProvider
}
// moveWithdrawal is compare-and-swap on the status (Part III).
func moveWithdrawal(ctx context.Context, tx pgx.Tx, id string, from, to WStatus) error {
tag, err := tx.Exec(ctx,
`UPDATE withdrawals SET status = $3, updated_at = now() WHERE id = $1 AND status = $2`,
id, from, to)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrStaleStatus
}
return nil
}
// ignoreStale treats "someone else already moved it" as success: the step is done.
func ignoreStale(err error) error {
if errors.Is(err, ErrStaleStatus) {
return nil
}
return err
}
// Advance runs the next step of a withdrawal. Every step is safe to run again.
func (e *WithdrawalEngine) Advance(ctx context.Context, id string) error {
w, err := e.load(ctx, id)
if err != nil {
return err
}
switch w.Status {
case WRequested:
return e.reserve(ctx, w)
case WReserved, WInitiated:
return e.sendPayout(ctx, w)
case WFailed:
return e.release(ctx, w)
default:
return nil // ACKNOWLEDGED waits for settlement; terminal states have nothing to do
}
}
func (e *WithdrawalEngine) load(ctx context.Context, id string) (Withdrawal, error) {
var w Withdrawal
err := e.Pool.QueryRow(ctx, `
SELECT id, customer_id, wallet_account_id, amount_minor, currency, destination_id, status
FROM withdrawals WHERE id = $1`, id).
Scan(&w.ID, &w.CustomerID, &w.WalletAccountID, &w.AmountMinor, &w.Currency, &w.DestinationID, &w.Status)
return w, err
}Step 2, reserving the funds, is one transaction: the status move, the journal (with Part II's overdraft guard) and the outbox event that triggers the next step all commit together. If the customer doesn't have the money, the whole transaction rolls back and a second, separate transaction rejects the withdrawal.
func (e *WithdrawalEngine) reserve(ctx context.Context, w Withdrawal) error {
amount := decimal.New(w.AmountMinor, -minorUnits[w.Currency])
err := pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
if err := moveWithdrawal(ctx, tx, w.ID, WRequested, WReserved); err != nil {
return err
}
err := Post(ctx, tx, Journal{
ID: "j_res_" + w.ID, Kind: "WITHDRAWAL", SourceType: "withdrawal", SourceID: w.ID,
CreatedBy: "withdrawal-engine", EffectiveAt: time.Now(),
Entries: []Entry{
{AccountID: w.WalletAccountID, Asset: w.Currency, Amount: amount.Neg()},
{AccountID: "plat:payouts_in_transit:" + w.Currency, Asset: w.Currency, Amount: amount},
},
})
if err != nil {
return err
}
return enqueueEvent(ctx, tx, "withdrawal", w.ID, "withdrawal.advance", map[string]string{"id": w.ID})
})
if errors.Is(err, ErrInsufficientFunds) {
return pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
return ignoreStale(moveWithdrawal(ctx, tx, w.ID, WRequested, WRejected))
})
}
return ignoreStale(err)
}Step 3 talks to the outside world, so it follows the pattern from Part III: record the intent, then perform the side effect with a derived key, then record the result. Each piece is short, and no transaction is open while the provider call is in progress.
func (e *WithdrawalEngine) sendPayout(ctx context.Context, w Withdrawal) error {
// 1. Record the intent. From here on, a payout may be in flight.
if w.Status == WReserved {
err := pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
return moveWithdrawal(ctx, tx, w.ID, WReserved, WInitiated)
})
if err != nil {
return ignoreStale(err) // another worker is on this step
}
}
// 2. Call the provider with no transaction open. The key comes from the
// withdrawal, so a resend after any crash is the same payout, not a new one.
res, err := e.Payouts.CreatePayout(ctx, "payout:"+w.ID, w.AmountMinor, w.Currency, w.DestinationID)
if errors.Is(err, ErrPayoutRejected) {
return pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
if err := moveWithdrawal(ctx, tx, w.ID, WInitiated, WFailed); err != nil {
return ignoreStale(err)
}
return enqueueEvent(ctx, tx, "withdrawal", w.ID, "withdrawal.advance", map[string]string{"id": w.ID})
})
}
if err != nil {
return err // timeout or 5xx: outcome unknown. Stay INITIATED; the retry resends the same key.
}
// 3. Record what the provider told us.
return pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
if err := moveWithdrawal(ctx, tx, w.ID, WInitiated, WAcknowledged); err != nil {
return ignoreStale(err)
}
_, err := tx.Exec(ctx, `UPDATE withdrawals SET provider_payout_id = $2 WHERE id = $1`, w.ID, res.ProviderRef)
return err
})
}The provider call can end three ways, and the code treats each one differently. A definite rejection means nothing was sent, so it's safe to give the money back. An unknown outcome (timeout, 5xx) is not a failure (Part I's most important rule), so the withdrawal stays PAYOUT_INITIATED and is retried with the same key. Only a success moves it forward.
Compensation: sagas without the jargon
A database transaction can roll back, but a payout that has already left can't. When a later step fails after earlier steps have already changed the world, you don't roll back; you compensate: run a new step that undoes the effect of the earlier one. A workflow built from steps and compensations is called a saga.
// release gives reserved funds back after a definite payout failure.
func (e *WithdrawalEngine) release(ctx context.Context, w Withdrawal) error {
return pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
if err := moveWithdrawal(ctx, tx, w.ID, WFailed, WReleased); err != nil {
return ignoreStale(err)
}
reversal := "rev_j_res_" + w.ID
if err := ReverseJournal(ctx, tx, "j_res_"+w.ID, reversal, "payout failed", "withdrawal-engine"); err != nil {
return err
}
if err := applyJournalToBalances(ctx, tx, reversal); err != nil {
return err
}
return enqueueEvent(ctx, tx, "withdrawal", w.ID, "withdrawal.failed", map[string]string{"id": w.ID})
})
}
// Settle is called when a settlement report or bank statement confirms the payout.
func (e *WithdrawalEngine) Settle(ctx context.Context, id string) error {
w, err := e.load(ctx, id)
if err != nil {
return err
}
amount := decimal.New(w.AmountMinor, -minorUnits[w.Currency])
return pgx.BeginFunc(ctx, e.Pool, func(tx pgx.Tx) error {
if err := moveWithdrawal(ctx, tx, id, WAcknowledged, WSettled); err != nil {
return ignoreStale(err)
}
return Post(ctx, tx, Journal{
ID: "j_set_" + id, Kind: "WITHDRAWAL", SourceType: "withdrawal_settlement", SourceID: id,
CreatedBy: "withdrawal-engine", EffectiveAt: time.Now(),
Entries: []Entry{
{AccountID: "plat:payouts_in_transit:" + w.Currency, Asset: w.Currency, Amount: amount.Neg()},
{AccountID: "plat:payouts_settled:" + w.Currency, Asset: w.Currency, Amount: amount},
},
})
})
}Compensation is a backward recovery: undo what was done. The retry in sendPayout is a forward recovery: keep trying until the step completes. Use forward recovery when the step can still succeed (an unknown outcome, a provider outage). Use backward recovery only when the outcome is definitely negative. Compensating a payout that might still arrive is how customers end up with their money twice.
Recovering stuck workflows
The queue drives workflows forward in the normal case. But messages can be dead-lettered, workers can be killed mid-step, and a provider can be down for an hour. So a sweeper periodically finds workflows that haven't moved for a while and calls Advance on them again:
-- Withdrawals that should have moved by now. Each sweeper instance takes a different batch.
SELECT id
FROM withdrawals
WHERE status IN ('REQUESTED', 'FUNDS_RESERVED', 'PAYOUT_INITIATED', 'PAYOUT_FAILED')
AND updated_at < now() - interval '2 minutes'
ORDER BY updated_at
LIMIT 100
FOR UPDATE SKIP LOCKED;Because every step is idempotent, the sweeper doesn't need to know what went wrong. It says “advance this” and leaves the rest to the state machine. PAYOUT_ACKNOWLEDGED isn't in the list: those are waiting for settlement, which has its own check in reconciliation (Chapter 20). Alert on withdrawals that stay in any non-terminal state far longer than normal; those need a person.
When is a workflow engine worth it?
Everything above is a hand-rolled workflow: a status column, an outbox and a sweeper. It's simple, and for a few workflows with a handful of steps each it's what I'd build. When workflows get complex, a dedicated engine can take over the bookkeeping:
- Temporal provides “Durable Execution of application code”: you write the workflow as ordinary code, and it survives crashes and outages (Temporal).
- AWS Step Functions Standard workflows can run for up to a year with exactly-once workflow execution; Express workflows run for up to five minutes and are at-least-once or at-most-once (AWS: choosing a workflow type).
Reach for one when you have many long waits and timers, human approval steps, complex branching, or dozens of workflow types. Steps that call providers still need idempotency keys, because engines retry steps too. And your payment and ledger state should still live in your own database: the engine orchestrates the steps, but finance, support and reconciliation read your tables, not the engine's history.
Checklist
- Every long process has a status column that is its checkpoint.
- Each step commits its effect and its checkpoint in the same transaction.
- Intent is recorded before any external call, and the call uses a key derived from it.
- Unknown outcomes are retried forward; only definite failures are compensated.
- Compensation writes new records (reversal journals), never deletes old ones.
- A sweeper re-advances stuck workflows, and long-stuck ones alert a person.
- No workflow progress lives only in memory.
Chapter 13
Database connections, connection pooling and short transactions
Connections are a finite, expensive resource
Every PostgreSQL connection is a separate operating-system process on the database server: PostgreSQL uses a “process per user” model, and spawns a new backend process for each connection (PostgreSQL: how connections are established). Each process needs memory, and they all compete for the same CPUs, disks and locks. The server's limit, max_connections, is “typically 100” by default (PostgreSQL: connection settings).
The intuition many people have is that more connections means more throughput. Past a point, it doesn't. A database with 16 CPU cores can only run about 16 things at once, so with 500 active connections it spends its time switching between them and making them wait on each other's locks. Throughput flattens and latency climbs:
The goal, then, is enough connections to keep the database busy and no more. A connection pool is how each service enforces its share.
How a pool works
A pool keeps a set of open connections and lends them out. A goroutine that needs the database acquires a connection, uses it, and releases it. If all connections are busy, it waits. In Go, pgxpool is the usual choice, and these are its main settings (pgxpool):
| Setting | Meaning | pgxpool default |
|---|---|---|
MaxConns | The most connections this pool will ever open | The greater of 4 or the number of CPUs |
MinConns | Connections kept open even when idle, to avoid connect latency after a quiet spell | 0 |
MaxConnLifetime | Connections older than this are closed and replaced (helps with failovers and load balancing) | 1 hour |
MaxConnIdleTime | Idle connections older than this are closed | 30 minutes |
HealthCheckPeriod | How often idle connections are checked | 1 minute |
The default MaxConns depends on the CPUs of the application machine, which tells you nothing about what the database can handle. Set it explicitly, from a budget.
The connection budget
This one relationship causes more payment-system outages than any clever bug:
Total potential connections = number of application instances × maximum pool size per instance, summed over every service that talks to the database.
Each pool setting looks reasonable on its own. The API has 6 pods with 20 connections each; the credit workers have 4 pods with 10. Add the outbox publisher, a migration job and an admin tool, and the total is 180 against a limit of 200, which looks fine.
Then a busy evening makes the credit queue grow, and the autoscaler does what it was told and adds worker pods. At 16 worker pods, the total potential is 300. The database refuses new connections, the API starts failing health checks, and a queue backlog has turned into a full outage.
What prevents it:
- Write the budget down. A table of every service, its maximum instance count (from the autoscaler's max, not today's count) and its pool size, adding up to less than
max_connectionsminus a reserve for admins and migrations. - Cap autoscalers by the budget. A worker that scales on queue depth must have a maximum replica count that fits its share.
- Size pools from the work. A useful rule of thumb (Little's law): the connections a service needs on average are about its transactions per second times the average transaction duration. At 400 transactions per second and 25 ms each, that's about 10 connections busy on average. Give it some headroom, not ten times as many.
The same rule of thumb shows why transaction length dominates everything else. The same 400 transactions per second, each holding a connection for 2 seconds while it waits on a provider, would need about 800 connections. No pool setting fixes that; only a shorter transaction does.
Configuring pgxpool
// NewPool opens a pool sized from the connection budget, with server-side guards
// so one bad query or forgotten transaction can't hold resources forever.
func NewPool(ctx context.Context, dsn, appName string, maxConns int32) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = maxConns // from the budget table, not a guess
cfg.MinConns = 2
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnLifetimeJitter = 5 * time.Minute // don't recycle every connection at once
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
params := cfg.ConnConfig.RuntimeParams
params["application_name"] = appName // shows up in pg_stat_activity
params["statement_timeout"] = "5s"
params["lock_timeout"] = "2s"
params["idle_in_transaction_session_timeout"] = "10s"
return pgxpool.NewWithConfig(ctx, cfg)
}
// reportPoolStats logs the pool's state; export these as metrics in production.
func reportPoolStats(ctx context.Context, pool *pgxpool.Pool, every time.Duration) {
ticker := time.NewTicker(every)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s := pool.Stat()
slog.Info("db pool",
"max", s.MaxConns(), "total", s.TotalConns(),
"acquired", s.AcquiredConns(), "idle", s.IdleConns(),
"waited_acquires", s.EmptyAcquireCount(), // acquires that had to wait
"acquire_time_total", s.AcquireDuration())
}
}
}The three timeouts are PostgreSQL settings (PostgreSQL: client connection defaults). statement_timeout aborts any statement that runs too long. lock_timeout aborts a statement that waits too long for a lock. idle_in_transaction_session_timeout terminates a session that sits inside an open transaction doing nothing, the classic symptom of code that opened a transaction and then went off to call an API. PostgreSQL 17 also added transaction_timeout, which caps a whole transaction's duration (PostgreSQL 17 release notes).
The pool's statistics give you early warning. If EmptyAcquireCount is growing, goroutines are waiting for connections; if total acquire time grows faster than request count, they're waiting longer each time. Either one usually means transactions got longer, not that the pool is too small.
PgBouncer: many clients, few server connections
When you have many services and many pods, even well-sized pools add up. A connection pooler like PgBouncer sits between your applications and PostgreSQL, accepts thousands of client connections, and multiplexes them onto a small number of real server connections. It has three pool modes (PgBouncer: configuration):
- Session: a client keeps one server connection until it disconnects. Safest, least sharing.
- Transaction: “a server connection is assigned to a client only during a transaction”. The usual choice for web and worker traffic.
- Statement: one statement at a time; multi-statement transactions are disallowed. Rarely what a payment system wants.
[pgbouncer]
pool_mode = transaction
max_client_conn = 2000 ; connections your applications may open to PgBouncer
default_pool_size = 40 ; real server connections per user/database pair
max_prepared_statements = 200 ; protocol-level prepared statements in transaction modeTransaction mode has a cost: anything that relies on session state breaks, because consecutive transactions from one client may run on different server connections. PgBouncer's feature table lists SET/RESET, LISTEN, SQL-level PREPARE, session-level advisory locks and WITH HOLD cursors as never supported in transaction mode (PgBouncer: features).
That includes the RuntimeParams in the Go code above, which are sent once per connection; set them per role instead (ALTER ROLE … SET statement_timeout = '5s').
Prepared statements
Protocol-level prepared statements, which pgx uses by default, do work in transaction mode when max_prepared_statements is above zero; it arrived in PgBouncer 1.21 and has defaulted to 200 since 1.24. On older versions, switch pgx to a mode that doesn't use named prepared statements, such as pgx.QueryExecModeExec. On AWS, RDS Proxy plays a similar role.
Read replicas: more reads, older data
Read replicas take read load off the primary, but PostgreSQL streaming replication is “asynchronous by default”, so there's “a small delay between committing a transaction in the primary and the changes becoming visible in the standby” (PostgreSQL: warm standby). Usually under a second; during heavy load or maintenance, much longer.
For payments, that means never make a money decision from a replica. Balance checks, idempotency checks and state transitions read from the primary, inside the transaction that acts on them. Replicas are fine for statements, dashboards, search and reports, as long as the product accepts slightly stale data. Watch for read-your-own-writes surprises: a customer who just withdrew and immediately sees their old balance on a replica-backed screen will file a support ticket.
Keeping transactions short
Most of this chapter comes back to one habit. A transaction holds a connection and its locks for its entire life, so its duration feeds into every other number: connections needed, lock waits, deadlock chances, vacuum's ability to clean up. A slow transaction usually looks something like this sketch:
// SKETCH of what not to do: everything inside one transaction.
BEGIN
lock the payment row
status := payco.GetPayment(...) // network call: 50 ms to 30 s
price := pricing.Quote(...) // another network call
fees := calculateFees(...) // CPU work
profile := customers.Get(...) // another service
validate(...)
update wallet, insert ledger entries
COMMITEvery network call inside the transaction holds the payment's row lock and a pooled connection while it waits. If PayCo takes two seconds, every other request touching this payment waits two seconds, and every one of those requests holds a connection too. A slow dependency turns into a connection shortage, which turns into an outage of things that have nothing to do with PayCo.
The better shape splits the work into three phases:
| Phase | What happens | Transaction? |
|---|---|---|
| Before | Validate the payload. Normalise the provider response. Fetch reference data. Calculate fees and quantities. Resolve pricing. Build ledger entries and event payloads. Run read-only checks. | No |
| Inside | Lock the rows you'll change. Re-check the things that can change. Check idempotency. Update state. Update balances. Insert ledger entries and outbox events. Commit. | Yes, short |
| After | Publish through the outbox. Send notifications. Trigger follow-up work. | No |
Below is the purchase from Part II, settled in that shape. It assumes the payment row points at the quote it was executed against.
type purchasePlan struct {
PaymentID string
Journal Journal
Event map[string]any
}
// planPurchase does all the slow, read-only work, with no transaction open.
func planPurchase(ctx context.Context, pool *pgxpool.Pool, paymentID string) (purchasePlan, error) {
var customerID, payAsset, receiveAsset, payAmount, receiveAmount string
err := pool.QueryRow(ctx, `
SELECT q.customer_id, q.pay_asset, q.receive_asset, q.pay_amount::text, q.receive_amount::text
FROM payments p JOIN quotes q ON q.id = p.quote_id
WHERE p.id = $1`, paymentID).
Scan(&customerID, &payAsset, &receiveAsset, &payAmount, &receiveAmount)
if err != nil {
return purchasePlan{}, err
}
pay, err := decimal.NewFromString(payAmount)
if err != nil {
return purchasePlan{}, err
}
receive, err := decimal.NewFromString(receiveAmount)
if err != nil {
return purchasePlan{}, err
}
return purchasePlan{
PaymentID: paymentID,
Journal: Journal{
ID: "j_" + paymentID, Kind: "PURCHASE", SourceType: "transaction", SourceID: paymentID,
CreatedBy: "purchase-worker", EffectiveAt: time.Now(),
Entries: []Entry{
{AccountID: "cust:" + customerID + ":wallet:" + payAsset, Asset: payAsset, Amount: pay.Neg()},
{AccountID: "plat:purchase_clearing:" + payAsset, Asset: payAsset, Amount: pay},
{AccountID: "cust:" + customerID + ":holdings:" + receiveAsset, Asset: receiveAsset, Amount: receive},
{AccountID: "plat:inventory:" + receiveAsset, Asset: receiveAsset, Amount: receive.Neg()},
},
},
Event: map[string]any{"payment_id": paymentID, "asset": receiveAsset, "units": receive.String()},
}, nil
}
// ApplyPurchase settles a purchase. Only phase 2 holds a transaction, for milliseconds.
func ApplyPurchase(ctx context.Context, pool *pgxpool.Pool, paymentID string) error {
// Phase 1: prepare. No locks, no connection held between queries.
plan, err := planPurchase(ctx, pool, paymentID)
if err != nil {
return err
}
// Phase 2: lock, re-check what can change, write everything, commit.
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
var status Status
err := tx.QueryRow(ctx, `SELECT status FROM payments WHERE id = $1 FOR UPDATE`, paymentID).Scan(&status)
if err != nil {
return err
}
if status == Success {
return nil // already applied: idempotent
}
if err := Transition(ctx, tx, paymentID, status, Success, "purchase_settled"); err != nil {
return err // includes illegal moves, e.g. the payment was cancelled meanwhile
}
if err := Post(ctx, tx, plan.Journal); err != nil {
return err // includes the overdraft guard: balances are re-checked here
}
return enqueueEvent(ctx, tx, "payment", paymentID, "purchase.completed", plan.Event)
})
// Phase 3: nothing to do here. The outbox publisher announces the event,
// and notifications are consumers of it.
}The mutable things (the payment's status, the wallet balance, the inventory) are all re-checked inside the transaction: the status by the lock and Transition, the balances by Post's conditional updates. The immutable things (the quote's amounts, the entries' shape) were prepared outside it.
Opening transactions lazily
Payment processing is often written as a pipeline of steps: parse, validate, enrich, price, apply, notify. A common mistake is to open a transaction at the start of the pipeline “in case a step needs it”, so the read-only and slow steps all end up running inside it. A small helper fixes this by opening the transaction only when a step first asks for one:
// Session lends steps either the pool (for reads) or a transaction (for writes).
// The transaction is opened the first time a step asks for it, not before.
type Session struct {
Pool *pgxpool.Pool
tx pgx.Tx
}
func (s *Session) Tx(ctx context.Context) (pgx.Tx, error) {
if s.tx == nil {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return nil, err
}
s.tx = tx
}
return s.tx, nil
}
type Step func(ctx context.Context, s *Session) error
// RunPipeline runs steps in order. If any step opened a transaction, it is committed
// when every step succeeds and rolled back otherwise. Put read-only and slow steps
// first: once a transaction is open, everything after it runs inside its lifetime.
func RunPipeline(ctx context.Context, pool *pgxpool.Pool, steps ...Step) (err error) {
s := &Session{Pool: pool}
defer func() {
if s.tx == nil {
return
}
if err != nil {
_ = s.tx.Rollback(context.WithoutCancel(ctx))
return
}
err = s.tx.Commit(ctx)
}()
for _, step := range steps {
if err = step(ctx, s); err != nil {
return err
}
}
return nil
}External calls never happen under a lock
This gets its own heading because it's the most common way payment systems fall over. A database transaction can't include an HTTP call; if the transaction rolls back, the call has still happened.
Holding a lock while you wait for the network makes your database's health depend on the slowest service you call. The patterns in this handbook all avoid it: record intent, commit, call with a derived key, then record the result in a new short transaction (Part III, and the payout step above).
What to monitor
-- Who is connected, and what are they doing?
SELECT application_name, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2
ORDER BY 3 DESC;
-- The longest-running open transactions, and what they're waiting on.
SELECT pid, application_name, state, now() - xact_start AS xact_age,
wait_event_type, wait_event, left(query, 80) AS query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 20;In pg_stat_activity, the state idle in transaction means “the backend is in a transaction, but is not currently executing a query” (PostgreSQL: monitoring statistics). A few of those, briefly, are normal. Lots of them, or any that are old, mean application code is holding transactions open while it does something else. Setting application_name in the pool makes it obvious which service is responsible.
- Database: active, idle and idle-in-transaction connections, against
max_connections; transaction age p99; lock waits. - Each pool: acquired vs max, waited acquires, total acquire time.
- The budget: the sum of every service's maximum pool times its maximum replicas, checked in CI whenever an autoscaler or pool setting changes.
Checklist
- Every service's pool size is set explicitly, from a written connection budget.
- Autoscalers have maximum replica counts that fit the budget.
- Pools set
application_nameand server-side timeouts. - No network call happens inside a database transaction.
- Slow, read-only work happens before the transaction; mutable facts are re-checked inside it.
- Transactions are opened lazily, only when a step needs to write or lock.
- Money decisions never read from replicas.
- Idle-in-transaction sessions and long transactions are monitored.
Chapter 14
Database query optimisation and scaling
Before adding replicas, shards or caches, find out what the database is spending its time on. Most slow payment systems I've looked at had a handful of queries doing most of the damage, and each was fixable with an index, a rewrite or a smaller transaction.
Find the expensive queries first
pg_stat_statements tracks “planning and execution statistics of all SQL statements executed by a server” (PostgreSQL: pg_stat_statements). Sort by total time, not mean time: a 2 ms query that runs a million times an hour costs far more than a 2-second report that runs once a day.
-- Needs shared_preload_libraries = 'pg_stat_statements' and then:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT left(query, 70) AS query,
calls,
round(total_exec_time) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Reading a query plan: a slow balance lookup
To see why a query is slow, ask PostgreSQL to run it and report what it did. EXPLAIN ANALYZE “causes the statement to be actually executed, not only planned” (PostgreSQL: EXPLAIN), so be careful with it on statements that change data. The BUFFERS option shows how many pages it touched; since PostgreSQL 18 it's included by default with ANALYZE.
The plans below are real. I generated a ledger table with 2.3 million entries across 20,000 accounts on a laptop running PostgreSQL 17, and asked for one account's balance. Your timings will differ; the shapes won't.
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT sum(amount) FROM ledger_entries WHERE account_id = 'cust:c_4242:wallet:EUR';Finalize Aggregate (actual time=57.389..59.052 rows=1 loops=1)
Buffers: shared hit=13029 read=11006 written=88
-> Gather (actual time=57.260..59.043 rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (actual time=53.096..53.097 rows=1 loops=3)
-> Parallel Seq Scan on ledger_entries (actual time=1.005..53.041 rows=33 loops=3)
Filter: (account_id = 'cust:c_4242:wallet:EUR'::text)
Rows Removed by Filter: 766633
Execution Time: 59.084 msRead it from the innermost line outwards. Parallel Seq Scan means PostgreSQL read the whole table with three processes. Rows Removed by Filter: 766633 (per process) means it looked at about 2.3 million rows to find 100. Buffers shows about 24,000 pages touched. 59 ms sounds fast, but this query runs on every balance check; under load, those page reads crowd out everything else.
CREATE INDEX ledger_entries_account_time ON ledger_entries (account_id, created_at);Aggregate (actual time=1.574..1.574 rows=1 loops=1)
Buffers: shared hit=47 read=57 written=34
-> Index Scan using ledger_entries_account_time on ledger_entries (actual time=0.625..1.558 rows=100 loops=1)
Index Cond: (account_id = 'cust:c_4242:wallet:EUR'::text)
Execution Time: 1.596 msNow it's an Index Scan: PostgreSQL found the account's entries through the index and visited only their table pages. That's about 100 pages instead of 24,000, and 1.6 ms. It still has to visit the table for each row to read amount, which it can skip if the index itself contains the amount:
CREATE INDEX ledger_entries_account_time ON ledger_entries (account_id, created_at) INCLUDE (amount);
VACUUM ANALYZE ledger_entries;Aggregate (actual time=0.086..0.086 rows=1 loops=1)
Buffers: shared hit=1 read=4
-> Index Only Scan using ledger_entries_account_time on ledger_entries (actual time=0.060..0.067 rows=100 loops=1)
Index Cond: (account_id = 'cust:c_4242:wallet:EUR'::text)
Heap Fetches: 0
Execution Time: 0.165 msAn Index Only Scan with Heap Fetches: 0 answered the query from 5 index pages without touching the table. A covering index does this by carrying extra columns: INCLUDE columns are carried in the index but aren't part of its search key (PostgreSQL: index-only scans). Two caveats: they make the index bigger, and index-only scans depend on the table being vacuumed recently, because PostgreSQL uses the visibility map to skip table visits.
Choosing indexes
Order composite indexes for your filters. A multicolumn index “is most efficient when there are constraints on the leading (leftmost) columns” (PostgreSQL: multicolumn indexes), so put the columns you filter with equality first (account_id), then the one you filter by range or sort by (created_at).
Think about selectivity, too. An index on a column with three possible values (like status on a mostly-SUCCESS table) rarely helps on its own, but a partial index on just the rare values often does, like the outbox's WHERE status = 'PENDING' index in Part IV.
And every index costs every write. Each insert into the ledger updates every index on it, so adding indexes “just in case” slows down the busiest table you have. Index for the queries you've measured, and drop indexes that pg_stat_user_indexes shows are never used.
Hot rows and lock contention
Not every slow transaction is a slow query; sometimes the query is fast and it's waiting. In Part II, every journal updated a balance projection, including platform accounts like a clearing account that appears in nearly every payment. Only one transaction can update a row at a time, so that one row serialises all of them.
To see it in pg_stat_activity, I held one update on the clearing row open for a few seconds and started a second update on the same row:
pid | state | wait_event_type | wait_event | query | xact_age
-------+--------+-----------------+---------------+------------------------------------------------------+-----------------
79300 | active | Timeout | PgSleep | BEGIN; UPDATE account_balances SET balance = balance | 00:00:01.318844
79331 | active | Lock | transactionid | UPDATE account_balances SET balance = balance + 1 WH | 00:00:00.807797wait_event_type = Lock means “the server process is waiting for a heavyweight lock” (PostgreSQL: monitoring statistics). The transactionid wait is the signature of one transaction waiting for another to finish with a row. In production you'll see dozens of these lined up behind one hot row. PostgreSQL also logs any lock wait longer than deadlock_timeout (1 second by default), because log_lock_waits is on by default (PostgreSQL: lock management).
Fixes, roughly in the order I'd try them:
- Shorten the transactions that touch the row (Chapter 13). Lock time, not query time, is the bottleneck.
- Don't keep a projection for platform accounts. Customer balances need the overdraft guard; a clearing account usually doesn't. Mark it
allow_negative, skip its projection update, and compute its balance from the ledger when needed. - Split the row into buckets. Spread updates across N sub-rows and read the total as their sum:
-- Spread a busy platform balance over 16 buckets, picked by journal ID.
UPDATE account_balances
SET balance = balance + $2
WHERE account_id = 'plat:clearing:EUR#' || (abs(hashtext($1)) % 16); -- $1 = journal id
-- The real balance is the sum of the buckets.
SELECT sum(balance) FROM account_balances WHERE account_id LIKE 'plat:clearing:EUR#%';Deadlocks
When transactions lock several rows in different orders, they can deadlock. PostgreSQL checks for deadlocks after a lock wait passes deadlock_timeout, aborts one transaction, and logs the details. Treat a deadlock error as retryable in your code, but the lasting fix is the one from Part II: always lock rows in the same order, for example sorted by account ID before updating balances.
Write amplification, vacuum and bloat
PostgreSQL never updates a row in place. An UPDATE writes a new version of the row and leaves the old one for transactions that might still need it. Those old versions must later be cleaned up by VACUUM, because under MVCC (multi-version concurrency control) “the row version must not be deleted while it is still potentially visible to other transactions” (PostgreSQL: routine vacuuming).
For payments, the first consequence is that frequently updated tables bloat. A balance table updated thousands of times a minute produces thousands of dead row versions a minute. If autovacuum can't keep up, the table and its indexes grow, and every query on them slows down. Long-running transactions make it worse, because vacuum can't remove versions they might still see, which is one more reason to keep transactions short.
The second is that HOT updates help. If an update changes no indexed column and the new version fits on the same page, PostgreSQL can do a heap-only tuple (HOT) update that skips index maintenance. Lowering a table's fillfactor leaves room on each page and makes HOT updates more likely (PostgreSQL: HOT updates). So for a balance table: don't index the balance column, and leave free space.
-- Which tables have the most dead rows, and when were they last vacuumed?
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;
-- A hot, frequently updated table: leave room for HOT updates, vacuum it sooner.
ALTER TABLE account_balances SET (fillfactor = 70, autovacuum_vacuum_scale_factor = 0.01);Pagination: OFFSET versus keyset
Statements and transaction histories are paginated, and the obvious way, LIMIT 50 OFFSET 250000, gets slower with every page, because the database still reads and discards every skipped row. Keyset pagination remembers where the last page ended and asks for rows after that point:
-- Index matching the sort order
CREATE INDEX ledger_entries_statement ON ledger_entries (account_id, created_at DESC, id DESC);
-- OFFSET: reads and throws away 250,000 rows first
SELECT id, amount, created_at
FROM ledger_entries
WHERE account_id = 'plat:clearing:EUR'
ORDER BY created_at DESC, id DESC
OFFSET 250000 LIMIT 50;
-- Keyset: starts right after the last row of the previous page
SELECT id, amount, created_at
FROM ledger_entries
WHERE account_id = 'plat:clearing:EUR'
AND (created_at, id) < ('2025-02-21 20:31:30+00', 2050001)
ORDER BY created_at DESC, id DESC
LIMIT 50;On the same test data, against an account with 300,000 entries, the OFFSET version took about 82 ms and the keyset version about 0.04 ms, for the same page. The keyset plan is a single index scan that starts at the cursor. The id is in the cursor to break ties when two entries share a timestamp, so no row is skipped or repeated between pages.
Partitioning, archival, replicas and sharding
When a single, well-indexed PostgreSQL isn't enough, these are the options, roughly from cheapest to most expensive:
- Archive. Move closed months of workflow rows and published outbox rows to cheaper storage. The ledger stays, but most other tables don't need years of history online.
- Partition large append-mostly tables by time (Part II covers the uniqueness trade-offs). Old partitions can be detached and archived cheaply.
- Read replicas for reporting and statements, never for money decisions (Chapter 13).
- Vertical scaling. A bigger database server is unfashionable and often the cheapest fix available.
- Sharding only when the write volume truly exceeds one primary. Keep every journal inside one shard (shard by customer, keep platform accounts per shard), because a journal spanning shards can no longer commit atomically.
Size the database before scaling the workers
Before raising worker concurrency or replica counts, find the database's knee. Run a realistic load at increasing concurrency (8, 16, 32, 64 connections) and record throughput and p99 latency at each step; the point where throughput stops rising is your useful connection budget.
Then set pools and autoscaler limits so the sum stays near it. Scaling workers past that point only lengthens the queue inside the database instead of the queue in SQS, and the queue in SQS is the cheaper place to wait.
Common mistakes
- Adding read replicas or bigger pools before looking at
pg_stat_statements. - Indexes on every column “just in case”, slowing down every ledger insert.
- Composite indexes in the wrong column order for the actual queries.
- One platform balance row updated by every transaction.
- OFFSET pagination on statements and histories.
- Indexing a frequently updated column like
balance, which prevents HOT updates. - Long transactions that stop vacuum from cleaning up.
Checklist
pg_stat_statementsis enabled, and the top queries by total time are reviewed regularly.- Slow queries are diagnosed with
EXPLAIN (ANALYZE, BUFFERS), not guesses. - Balance and statement queries use composite (and where useful, covering) indexes.
- Hot platform rows are avoided, bucketed or computed from the ledger.
- Rows are always locked in a consistent order; deadlocks are retried.
- Dead tuples and autovacuum are monitored on high-churn tables.
- Histories use keyset pagination.
- The database's knee is measured before worker concurrency is raised.
Further reading
- PostgreSQL: client connection defaults: statement, lock and idle-in-transaction timeouts.
- PostgreSQL: monitoring statistics:
pg_stat_activityandpg_stat_user_tables. - PostgreSQL: EXPLAIN, multicolumn indexes and index-only scans.
- PostgreSQL: HOT updates and routine vacuuming.
- pgxpool: pool configuration and statistics in Go.
- PgBouncer: features and configuration: pool modes and their limits.
- Temporal and AWS Step Functions workflow types: workflow engines.
What's next
We can now run long workflows safely and keep the database healthy under load. So far, though, we've assumed failures are occasional.
Part VI, Resilience and Failure Recovery, is about the day a dependency goes down for an hour: retries with exponential backoff and jitter, why naive retries turn a recovery into a second outage, circuit breakers and bulkheads, and a walk through every major failure scenario in a payment system, with what state it leaves behind and how to recover without moving money twice.
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.