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

Observability and production engineering

Following one payment through every service, alerting on what customers feel rather than what CPUs do, finding the real bottleneck before you buy bigger machines, and reconciliation, which catches the mistakes every other layer missed.

Chapters 17–18–19–2045 min readPublished 23 Nov 2026

Part VI kept starting with the same word: detect. A stuck payment, a duplicate payout, a provider that has started failing one request in fifty. None of the recovery techniques help if nobody notices the problem, or if noticing takes three engineers an afternoon of searching logs.

This part is about seeing what the system is doing. Chapter 17 gets logs and traces to follow a single payment across every service, and Chapter 18 builds metrics and alerts on top of them that fire when customers are affected. Chapter 19 finds a performance bottleneck with a profiler, using real output. Chapter 20 is the longest; it covers reconciliation, the independent check that catches whatever the other layers missed.

Chapter 17

Structured logging and distributed tracing

The problem: one payment, five services, no story

A customer writes in: “I paid €40 an hour ago and my wallet still shows nothing.” To answer, you need the story of that one payment: the API request, PayCo's webhook, the outbox row, the SNS publication, the SQS message, the consumer's attempts, the database transaction. Those events happened in five processes on different machines, minutes apart.

If each service logs free-form text ("processing payment...", "done"), there is no story to find. If every log line carries the same identifiers, it's one search away.

A correlation model

Decide once which identifiers every log line and span about a payment should carry, and use the same names everywhere:

Identifiers on every payment log line and span
FieldWhat it identifiesSet by
transaction_idOur payment, withdrawal or transfer (pay_81)Whoever creates it
external_transaction_idThe client's own ID for it, if they sent oneAPI ingestion
provider_referenceThe provider's ID (pc_9KD)Provider responses and webhooks
event_idThe event being processed (Part IV envelope)Outbox insert
idempotency_keyThe client's key for the operationAPI ingestion
correlation_idEverything caused by one original requestFirst service to see the request
trace_idThe distributed trace (W3C Trace Context)Tracing library
consumerWhich handler is processing (wallet-credit)Consumer
attemptWhich delivery or retry this isConsumer (SQS receive count)
transaction_statusStatus before and after a changeState transitions

Structured JSON logs in Go

Go's standard log/slog package writes structured logs: each line is a JSON object with named fields instead of a sentence. Logger.With “returns a Logger that includes the given attributes in each output operation” (log/slog), so you attach a payment's identifiers once and every later line carries them. Storing that logger in the context means deep code doesn't need to know which payment it's working on to log correctly.

obs/log.goGo
// Masked hides all but the last four characters of a value when it is logged.
type Masked string

func (m Masked) LogValue() slog.Value {
	s := string(m)
	if len(s) <= 4 {
		return slog.StringValue("****")
	}
	return slog.StringValue(strings.Repeat("*", len(s)-4) + s[len(s)-4:])
}

// sensitiveKeys are dropped from every log record, whatever code tries to log them.
var sensitiveKeys = map[string]bool{"card_number": true, "cvv": true, "password": true, "authorization": true}

func NewLogger(service string) *slog.Logger {
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if sensitiveKeys[a.Key] {
				return slog.Attr{} // an empty Attr is dropped
			}
			return a
		},
	})
	return slog.New(h).With("service", service)
}

type loggerKey struct{}

// WithLogger stores a logger, already carrying a payment's identifiers, in ctx.
func WithLogger(ctx context.Context, l *slog.Logger) context.Context {
	return context.WithValue(ctx, loggerKey{}, l)
}

// Log returns the logger from ctx, or the default logger.
func Log(ctx context.Context) *slog.Logger {
	if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok {
		return l
	}
	return slog.Default()
}

A consumer sets up the payment's logger once, when it parses the message, and everything downstream uses Log(ctx):

consumer/handle.go (sketch)Go
ctx = WithLogger(ctx, base.With(
	"transaction_id", "pay_81",
	"provider_reference", "pc_9KD",
	"event_id", ev.EventID,
	"correlation_id", ev.CorrelationID,
	"trace_id", trace.SpanContextFromContext(ctx).TraceID().String(),
	"consumer", "wallet-credit",
	"attempt", receiveCount,
))
Log(ctx).Info("payment event received", "event_type", ev.Type,
	"destination_iban", Masked(iban), "card_number", pan) // card_number is dropped by ReplaceAttr

This is the real output of that code (I removed the time field to keep the lines short):

real slog outputJSON
{"level":"INFO","msg":"payment event received","service":"wallet-credit","transaction_id":"pay_81","provider_reference":"pc_9KD","event_id":"4a9c2f6e-8d1b-4c39-9f0e-3b7d2a51c8e4","correlation_id":"req_8KQ2","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","consumer":"wallet-credit","attempt":2,"event_type":"payment.succeeded","destination_iban":"******************3000"}
{"level":"INFO","msg":"payment credited","service":"wallet-credit","transaction_id":"pay_81","provider_reference":"pc_9KD","event_id":"4a9c2f6e-8d1b-4c39-9f0e-3b7d2a51c8e4","correlation_id":"req_8KQ2","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","consumer":"wallet-credit","attempt":2,"status_from":"PROCESSING","status_to":"SUCCESS","journal_id":"j_pay_81","duration_ms":14}
{"level":"WARN","msg":"duplicate event ignored","service":"wallet-credit","transaction_id":"pay_81","provider_reference":"pc_9KD","event_id":"4a9c2f6e-8d1b-4c39-9f0e-3b7d2a51c8e4","correlation_id":"req_8KQ2","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","consumer":"wallet-credit","attempt":2,"reason":"inbox_hit"}
{"level":"ERROR","msg":"ledger posting failed","service":"wallet-credit","transaction_id":"pay_81","provider_reference":"pc_9KD","event_id":"4a9c2f6e-8d1b-4c39-9f0e-3b7d2a51c8e4","correlation_id":"req_8KQ2","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","consumer":"wallet-credit","attempt":2,"error_class":"insufficient_funds","err":"insufficient funds: cust:c_42:wallet:EUR"}

The card number is gone completely, because ReplaceAttr drops that key from every record no matter who logs it. The IBAN is masked by its LogValue method, a use the slog documentation mentions by name: you can “redact secret information like passwords” (log/slog).

Levels and error classes

  • ERROR: something needs a person, or money may be affected. If an error-level line doesn't need action, it's a warning.
  • WARN: unexpected but handled. Duplicates, retries, stale events.
  • INFO: state changes. One line per transition is the backbone of a payment's story.
  • DEBUG: off in production unless switched on for a specific investigation.

Add an error_class field with a small, fixed vocabulary (insufficient_funds, provider_timeout, illegal_transition, db_unavailable). Error messages vary from one call to the next, but a class can be counted, graphed and alerted on.

Distributed tracing

Logs tell you what happened. A trace tells you where the time went: it's a tree of timed spans, one per operation, across every service that worked on a request.

One payment as a distributed traceA trace for one payment: the webhook request with its verify and outbox insert spans, then the outbox publish to SNS, the SQS receive by the wallet-credit consumer, the inbox check, a database transaction containing the row lock and the journal posting, and finally the SQS delete. The journal posting is the longest span. trace 4bf92f35…timewebhook POST /paycoverify + store eventoutbox insertoutbox publish → SNSSQS receive (wallet-credit)inbox checkDB tx: SUCCESS + journallock payment rowpost journal + balancesSQS deletethe slow part is obvious: the ledger write
A trace turns “the payment was slow” into “this step was slow”. Each bar is a span; nesting shows which step ran inside which. The gaps between bars are time spent waiting in the outbox and the queue.

Tracing works by passing a small piece of context along with every call. The standard format is W3C Trace Context, whose traceparent header looks like 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01: version, trace ID, parent span ID and flags (W3C Trace Context). HTTP clients and servers instrumented with OpenTelemetry pass it automatically. It gets lost at queues, and most often at the outbox.

Identifiers flowing from webhook to consumerThe webhook records the event ID and provider reference. The outbox row stores the trace context with the event. SNS and SQS carry the traceparent in message attributes. The consumer adds all identifiers to its logger and span attributes. webhookevent_idprovider_referenceoutbox row+ trace contextstored with the eventSNS / SQStraceparent inmessage attributesconsumerlogger.With(ids…)span attributesthe same transaction_id, event_id and trace_id in every log line and span
The outbox is where traces usually break. The publisher runs later, in a different process, with no memory of the request. Storing the trace context in the outbox row lets the consumer’s spans join the original trace.

The fix has three parts, using OpenTelemetry's Go API (OpenTelemetry Go, propagation): capture the trace context when the event is written to the outbox, attach it to the SNS message, and extract it in the consumer.

obs/trace.goGo
// 1. When writing an event, capture the current trace context with it.
//    (Add a trace_context jsonb column to the outbox table from Part IV.)
func traceContext(ctx context.Context) map[string]string {
	carrier := propagation.MapCarrier{}
	otel.GetTextMapPropagator().Inject(ctx, carrier)
	return carrier // e.g. {"traceparent": "00-4bf9…-00f0…-01"}
}

// 2. When publishing, send it as SNS message attributes. With raw message delivery,
//    SNS passes them on to the SQS subscription as SQS message attributes.
func traceAttributes(tc map[string]string) map[string]snstypes.MessageAttributeValue {
	attrs := map[string]snstypes.MessageAttributeValue{}
	for k, v := range tc {
		attrs[k] = snstypes.MessageAttributeValue{DataType: aws.String("String"), StringValue: aws.String(v)}
	}
	return attrs
}

// 3. In the consumer, continue the trace from the message and start a span for the work.
//    (Ask ReceiveMessage for MessageAttributeNames: []string{"All"} to receive them.)
func startConsumerSpan(ctx context.Context, consumer string, msg sqstypes.Message) (context.Context, trace.Span) {
	carrier := propagation.MapCarrier{}
	for k, v := range msg.MessageAttributes {
		if v.StringValue != nil {
			carrier[k] = *v.StringValue
		}
	}
	ctx = otel.GetTextMapPropagator().Extract(ctx, carrier)
	ctx, span := otel.Tracer("payments").Start(ctx, "process "+consumer,
		trace.WithSpanKind(trace.SpanKindConsumer))
	span.SetAttributes(
		attribute.String("messaging.system.name", "aws.sqs"),
		attribute.String("messaging.message.id", aws.ToString(msg.MessageId)),
		attribute.String("payments.consumer", consumer),
	)
	return ctx, span
}

// finishSpan records the outcome. RecordError needs a separate SetStatus call.
func finishSpan(span trace.Span, err error) {
	if err != nil {
		span.RecordError(err)
		span.SetStatus(codes.Error, err.Error())
	}
	span.End()
}

The messaging.* attribute names follow OpenTelemetry's messaging semantic conventions, which name SQS aws.sqs (OpenTelemetry: messaging spans). Those conventions are still marked as in development, so check them when you upgrade. SQS allows at most 10 message attributes per message (AWS: SQS message metadata); trace context uses one or two, and you need to leave room for the event_type attribute your filter policies depend on.

Put payment identifiers on spans as attributes (payments.transaction_id) so you can find a trace from a support ticket. Unlike metric labels (next chapter), span attributes are fine with high-cardinality values.

Sampling

Tracing every request at high volume is expensive, so traces are usually sampled. Head sampling decides at the start of a trace (keep 10%, say), which is cheap but can drop the one trace you needed. Tail sampling, typically done in an OpenTelemetry Collector, decides after the trace is complete, so you can keep every trace with an error or high latency and only a fraction of the healthy ones.

For payments I'd keep all errors and all slow traces, and sample the rest. Logs aren't sampled: every state transition is logged, always.

Checklist

  • Every service logs JSON with the same field names for the same identifiers.
  • A payment's logger is set up once and carried in the context.
  • Sensitive fields are dropped or masked by the log handler, not by convention.
  • Every state transition produces exactly one INFO line with from and to statuses.
  • Errors carry a small, fixed set of error classes.
  • Trace context is stored in the outbox and carried through SNS and SQS.
  • Errors and slow traces are always kept by sampling.

Chapter 18

Metrics, monitoring and alerting

Logs and traces answer questions about one payment. Metrics answer questions about all of them: how many succeeded this minute, how long the oldest message has waited, how close the database pool is to full. They're cheap to store and fast to query, which is why alerts are built on them.

Start from symptoms

Google's SRE book describes four golden signals: latency, traffic, errors and saturation. It also makes a point that changes how you design alerts: “it's better to spend much more effort on catching symptoms than causes” (Google SRE: monitoring distributed systems).

A symptom is what a customer feels: payments failing, confirmations late. A cause is why: CPU high, a disk filling up. Causes are useful for debugging; symptoms are what you page on, because “every page should be actionable”.

For a payment system I group metrics into four layers:

Metrics for a payment system
LayerMetricWhy it matters
BusinessPayments succeeded / failed per minute; success ratioThe most direct customer symptom
BusinessPayments stuck in PENDING/PROCESSING over N minutesCustomers who paid and are waiting
BusinessPayout completion time; payouts stuck in INITIATEDMoney owed to customers that hasn't arrived
BusinessReversals per hour; ledger posting failures; open reconciliation discrepanciesMoney that needed correcting, or might
QueueAge of oldest message; visible and in-flight messages; DLQ depth; receive countHow far behind processing is (Part IV)
ApplicationEvents processed, failed and duplicated per consumer; processing duration; retries by error class; worker utilisationWhere the work is going wrong
DatabaseActive, idle and waiting connections; pool saturation; transaction duration; lock waits; deadlocks; slow queries; CPU and I/OWhether the database is the bottleneck (Part V)

Instrumenting a consumer

obs/metrics.goGo
var (
	eventsProcessed = promauto.NewCounterVec(prometheus.CounterOpts{
		Name: "payments_events_processed_total",
		Help: "Events handled by a consumer, by outcome.",
	}, []string{"consumer", "event_type", "outcome"}) // outcome: ok | duplicate | retry | failed

	processingSeconds = promauto.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "payments_event_processing_seconds",
		Help:    "Time to process one event, including database work.",
		Buckets: prometheus.ExponentialBuckets(0.005, 2, 12), // 5 ms … ~10 s
	}, []string{"consumer", "event_type"})

	retriesTotal = promauto.NewCounterVec(prometheus.CounterOpts{
		Name: "payments_retries_total",
		Help: "Retries, by dependency and error class.",
	}, []string{"dependency", "error_class"})
)

// observe records one processed event.
func observe(consumer, eventType, outcome string, started time.Time) {
	eventsProcessed.WithLabelValues(consumer, eventType, outcome).Inc()
	processingSeconds.WithLabelValues(consumer, eventType).Observe(time.Since(started).Seconds())
}

Two rules keep metrics useful and affordable. First, never use unbounded values as labels. Every distinct combination of label values is a separate time series, and Prometheus's guidance is explicit: “do not use labels to store dimensions with high cardinality”, “such as user IDs, email addresses, or other unbounded sets of values” (Prometheus: naming).

Payment IDs, customer IDs and amounts belong in logs and span attributes. Labels are for small, fixed sets: consumer, event type, outcome, error class.

Second, record latency in histograms rather than averages. A histogram stores counts per bucket, and its distribution “can be aggregated” across instances, while a summary's precomputed quantiles cannot (Prometheus: histograms and summaries). That is how you get one p99 across twenty worker pods.

Average, p95, p99 and saturation

Average, p95 and p99 latencyA latency distribution with most requests clustered at low latency and a long tail to the right. The average is 40 ms, p95 is 180 ms and p99 is 900 ms. A small bump in the tail is labelled lock waits and retries. request latencyhow many requestsaverage 40 msp95 180 msp99 900 msthe slow tail:lock waits, retries
The average hides the customers who are having a bad time. One payment in a hundred taking almost a second is invisible in a 40 ms average and obvious in the p99. Numbers are illustrative.
  • Throughput: how much work per second. Payments per minute, events per second.
  • Average latency: easy to compute and almost useless on its own, because it hides the slow tail.
  • p95, p99: 95% (or 99%) of requests were faster than this. The p99 is where lock waits, retries and garbage-collection pauses show up first.
  • Saturation: how full the most constrained resource is. Pool connections in use out of the maximum, in-flight messages out of the worker limit. Saturation near 100% predicts latency problems before they happen.

Business metrics come from the database

Some of the most important numbers, like payments stuck in an unknown state, aren't events at all; they're the current state of the data. A small job queries them every minute and exports them as gauges:

business_gauges.sqlPostgreSQL
-- Payments customers are waiting on, by state and age bucket
SELECT status,
       count(*) FILTER (WHERE updated_at < now() - interval '15 minutes') AS older_than_15m,
       count(*) FILTER (WHERE updated_at < now() - interval '1 hour')     AS older_than_1h
  FROM payments
 WHERE status IN ('PENDING', 'PROCESSING')
 GROUP BY status;

-- Withdrawals whose payout may be in flight with no confirmation
SELECT count(*) AS payouts_unconfirmed_30m
  FROM withdrawals
 WHERE status = 'PAYOUT_INITIATED' AND updated_at < now() - interval '30 minutes';

A dashboard that answers questions in order

A payments dashboardSix panels: payments succeeded per minute, success ratio against a 99.5% SLO line, payments stuck in PROCESSING over 15 minutes, oldest message age per queue, database pool acquired versus maximum, and open reconciliation discrepancies. Payments succeeded / minSuccess ratio (SLO 99.5%)Stuck in PROCESSING > 15 minOldest message age, per queueDB pool: acquired / maxRecon discrepancies open99.5%37
The top row answers “are customers OK?”; the bottom row answers “why not?”. Business symptoms go first because they’re what you page on, with infrastructure panels underneath for the next question. Values are illustrative.

Arrange panels in the order you'd ask questions during an incident: are customers affected (top row), then which part of the pipeline is behind (queues), then why (database, dependencies). Put the outbox lag from Part IV next to queue age; between them they show whether events are stuck before or after publication.

Alerting on what matters

Pages wake people up, so each one must mean customers are affected now, and a person can do something about it. Everything else is a ticket or a dashboard. The thresholds below are illustrative starting points, and you should tune each one to your own traffic:

Illustrative alerts for a payment system
AlertIllustrative conditionSeverity
Payment success ratio burning error budget fastSee burn-rate alerts belowPage
Payments stuck in PROCESSINGMore than a handful older than 30 minutesPage
Payments DLQ not emptyAny message for 5 minutesPage in hours, ticket out of hours
Oldest message age, credit queueAbove 10 minutesPage
Outbox lagOldest pending row above 5 minutesPage
Late success anomaliesAny new payment_anomalies rowTicket, same day
Reconciliation discrepanciesAny new open discrepancyTicket, same day
Database pool saturationAbove 80% for 15 minutesTicket
CPU high on one noden/aDashboard only: a cause, not a symptom

For the success ratio, I use the approach from Google's SRE workbook: define a service level objective (say, 99.9% of payments processed successfully), and alert on how fast you're using up the 0.1% error budget. Its recommended multiwindow, multi-burn-rate alerts for a 99.9% objective are (Google SRE workbook: alerting on SLOs):

Burn-rate alerts for a 99.9% objective
SeverityLong windowShort windowBurn rateError budget consumed
Page1 hour5 minutes14.42%
Page6 hours30 minutes65%
Ticket3 days6 hours110%

A burn rate of 14.4 means you're failing 14.4 times faster than the objective allows. Requiring both the long and the short window to be over the threshold means the alert fires quickly when things break and stops quickly once they're fixed. In Prometheus, the first row looks like this:

alerts.ymlYAML
groups:
  - name: payments-slo
    rules:
      - alert: PaymentSuccessBudgetBurnFast
        expr: |
          (
            sum(rate(payments_events_processed_total{consumer="wallet-credit",outcome="failed"}[1h]))
              / sum(rate(payments_events_processed_total{consumer="wallet-credit"}[1h]))
          ) > (14.4 * 0.001)
          and
          (
            sum(rate(payments_events_processed_total{consumer="wallet-credit",outcome="failed"}[5m]))
              / sum(rate(payments_events_processed_total{consumer="wallet-credit"}[5m]))
          ) > (14.4 * 0.001)
        labels:
          severity: page
        annotations:
          summary: "Payment processing is failing fast enough to exhaust the monthly error budget"
          runbook: "https://runbooks.example.internal/payments/success-ratio"

Every alert links to a runbook: what the alert means, the first three things to check, and how to escalate. An alert without a runbook is a riddle delivered at 3 a.m.

Checklist

  • Business, queue, application and database metrics exist for every payment flow.
  • No metric label holds IDs, amounts or other unbounded values.
  • Latency is recorded in histograms, and dashboards show p99.
  • Stuck states are exported as gauges from the database.
  • Pages fire on customer symptoms (success ratio, stuck payments, queue age, outbox lag), not on causes.
  • The success ratio has an SLO with burn-rate alerts.
  • Every alert has a runbook.

Chapter 19

Profiling and performance engineering

Measure before you scale

When a service gets slow, the quickest fix to reach for is more: more pods, a bigger instance, more connections. Sometimes that's right. Often it multiplies a waste instead of removing it, and Part V showed how adding workers can make a database problem worse. A profiler can usually tell you where the time goes in a few minutes.

The profiling loop

The profiling loopSeven steps in a loop: establish a baseline, reproduce the workload, capture a profile, find the bottleneck, change one thing, run the same workload again, and compare, keeping or reverting the change. 1. baseline2. reproduce3. capture profile4. find the bottleneck5. change one thing6. same workload again7. comparekeep it or revert
One change per loop, measured against the same workload. If you change three things at once, you can’t tell which one helped and which one made it worse.
  1. Establish a baseline. Record throughput, p95, p99, CPU and memory under a known workload.
  2. Reproduce the workload. A benchmark, a load test, or production traffic itself.
  3. Capture a profile while the workload runs.
  4. Identify the bottleneck. Find where the time or memory goes in your code.
  5. Change one thing.
  6. Run the same workload again.
  7. Compare. Keep the change if it helped; revert it if it didn't.

Go's profiles

Go has profiling built in. The runtime can produce CPU, heap, goroutine, thread-creation, block and mutex profiles (Go: diagnostics). Importing net/http/pprof serves them under /debug/pprof/, and a CPU profile lasts “for 30 seconds if not specified” (net/http/pprof).

Block and mutex profiles are off by default and must be switched on with runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction. The Go team notes that it's “safe to profile programs in production, but enabling some profiles (e.g. the CPU profile) adds cost.”

obs/debug.goGo
// startDebugServer serves pprof on a separate, private port, never on the public API port.
func startDebugServer() {
	runtime.SetBlockProfileRate(10_000)   // sample blocking events of 10 µs or more
	runtime.SetMutexProfileFraction(100)  // sample 1 in 100 mutex contention events
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index)
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
	go func() {
		if err := http.ListenAndServe("127.0.0.1:6060", mux); err != nil {
			slog.Error("debug server stopped", "err", err)
		}
	}()
}
pprof commandsOutput
# 30-second CPU profile from a running worker (through a port-forward), opened in a browser UI
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile?seconds=30

# Where is memory being allocated? Where are goroutines stuck?
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/heap
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -50

# Profile a benchmark instead of a live process
go test -run '^$' -bench 'ValidateSlow' -benchmem -cpuprofile cpu.out -memprofile mem.out
go tool pprof -top -cum cpu.out

A real example: a hot loop in journal validation

This is a real profile of a small, realistic mistake. Before posting a journal, a service validates each entry's account ID with a regular expression, and it compiles the pattern inside the loop:

validate.go (before)Go
// validateSlow checks each entry before posting. It compiles the pattern on every call.
func validateSlow(entries []Entry) error {
	for _, e := range entries {
		re := regexp.MustCompile(`^(cust:[a-z0-9_]+|plat):[a-z_]+:[A-Z]{3,5}$`)
		if !re.MatchString(e.AccountID) {
			return fmt.Errorf("bad account id %q", e.AccountID)
		}
	}
	return nil
}

I benchmarked it on the six-entry purchase journal from Part II and captured a CPU profile. Sorted by cumulative time (-cum), the profile is unambiguous:

go tool pprof -top -cum cpu.out (excerpt)Output
      flat  flat%   sum%        cum   cum%
         0     0% 72.99%      0.13s  9.49%  example.com/prof.BenchmarkValidateSlow
         0     0% 72.99%      0.13s  9.49%  example.com/prof.validateSlow
         0     0% 72.99%      0.13s  9.49%  regexp.Compile (inline)
         0     0% 72.99%      0.13s  9.49%  regexp.MustCompile
         0     0% 72.99%      0.13s  9.49%  regexp.compile
     0.01s  0.73% 80.29%      0.06s  4.38%  runtime.mallocgc
         0     0% 80.29%      0.05s  3.65%  regexp.compileOnePass

All of validateSlow's time is inside regexp.MustCompile. (The low percentages are because most of the profile's samples were the Go runtime idling in the scheduler; with -cum you read your own functions relative to each other.) The memory profile tells the same story: almost all of the 3.5 GB allocated over the benchmark run came from regular-expression compilation.

go tool pprof -top -sample_index=alloc_space mem.out (excerpt)Output
Showing nodes accounting for 2932.52MB, 83.92% of 3494.55MB total
      flat  flat%   sum%        cum   cum%
  958.88MB 27.44% 27.44%   958.88MB 27.44%  regexp/syntax.(*compiler).inst
  717.87MB 20.54% 47.98%   717.87MB 20.54%  regexp.onePassCopy
  648.57MB 18.56% 66.54%   648.57MB 18.56%  regexp/syntax.(*parser).newRegexp
  240.15MB  6.87% 73.41%   647.18MB 18.52%  regexp.makeOnePass
  186.52MB  5.34% 78.75%   259.02MB  7.41%  regexp/syntax.(*Regexp).Simplify

The fix is one change: compile the pattern once, when the package starts.

validate.go (after)Go
var accountID = regexp.MustCompile(`^(cust:[a-z0-9_]+|plat):[a-z_]+:[A-Z]{3,5}$`)

// validateFast compiles the pattern once, at package start-up.
func validateFast(entries []Entry) error {
	for _, e := range entries {
		if !accountID.MatchString(e.AccountID) {
			return fmt.Errorf("bad account id %q", e.AccountID)
		}
	}
	return nil
}
go test -bench Validate -benchmem -count 3 (Go 1.26, Apple M-series)Output
BenchmarkValidateSlow-10      55192     19873 ns/op     61034 B/op     744 allocs/op
BenchmarkValidateSlow-10      60303     19933 ns/op     61034 B/op     744 allocs/op
BenchmarkValidateSlow-10      61134     19741 ns/op     61034 B/op     744 allocs/op
BenchmarkValidateFast-10    1000000      1016 ns/op         0 B/op       0 allocs/op
BenchmarkValidateFast-10    1000000      1005 ns/op         0 B/op       0 allocs/op
BenchmarkValidateFast-10    1000000      1005 ns/op         0 B/op       0 allocs/op

About twenty times faster, with zero allocations instead of 744 per journal. Nobody would have found that by adding pods; they'd have paid for it. Run benchmarks several times (-count) and compare the spread, not just one number; the benchstat tool does this properly.

Investigating common symptoms

Where to look for common symptoms
SymptomLook at firstUsual causes
High CPUCPU profile (-cum)Work repeated in a loop (like the regex), JSON encoding of large payloads, logging too much
Memory keeps growingHeap profile (inuse_space), then compare two profiles taken minutes apartUnbounded caches or maps, buffers kept alive, goroutine leaks
Goroutine count keeps growing/debug/pprof/goroutine?debug=1Goroutines blocked forever on a channel or a call with no timeout
High p99, normal averageTraces of slow requests; block and mutex profiles; database lock waitsLock contention, hot rows (Part V), GC pauses, retries
Slow queriespg_stat_statements, EXPLAIN (ANALYZE, BUFFERS) (Part V)Missing or wrong indexes, OFFSET pagination
Pool exhaustionpool.Stat() waits; pg_stat_activity idle-in-transactionLong transactions, network calls inside transactions
Queue backlogProcessing time p99, worker utilisation, dependency latencyA slow dependency, too few workers, or a database at its knee

Garbage collection settings

Go's garbage collector is tuned by two settings. GOGC controls how much the heap may grow between collections; it is 100 by default (runtime/debug). GOMEMLIMIT, added in Go 1.19, sets a soft memory limit the runtime tries to stay under (Go: GC guide).

In containers, setting GOMEMLIMIT a little below the container's memory limit helps the runtime collect harder before the container is killed for using too much memory. Even so, I'd reduce allocations first, as in the regex example; it beats tuning the collector every time.

Load testing

A load test is the “reproduce the workload” step at system scale. Make it realistic: production-like data volumes (a balance query on an empty ledger proves nothing), the real mix of operations, realistic payload sizes, and the same database configuration.

Increase load in steps, as in Part V's knee measurement, and record throughput, p95, p99 and saturation at each step. Use a fake provider that can be told to be slow or to fail, so you can load-test the retry and recovery behaviour from Part VI, not only the happy path.

Checklist

  • Every performance change starts with a baseline and ends with a comparison under the same workload.
  • pprof is enabled on a private port, with block and mutex profiling switched on.
  • Hot paths have benchmarks, run with -benchmem and several counts.
  • Dashboards show p95, p99 and saturation, not only averages.
  • GOMEMLIMIT is set in containers, slightly below the memory limit.
  • Load tests use realistic data and include provider slowness and failures.

Chapter 20

Reconciliation: the final safety net

Every earlier part of this handbook is about getting things right the first time. This chapter is about admitting that sometimes we won't, and finding out before a customer or an auditor does.

Why our own database isn't enough

Part I showed that one payment has several witnesses: our database, the provider, the bank. Each has its own view, and each can be wrong or incomplete. Our database misses webhooks that never arrived, applies a bug's mistakes faithfully, and has no idea that a payout bounced last Tuesday. Checking our database against itself (Part II's ledger checks) catches internal inconsistency, but not a record that's consistently wrong.

Reconciliation compares our records against independent sources and investigates every difference. The sources usually include:

  • Our transaction records: payments, withdrawals, refunds and their statuses.
  • Our ledger: journals and balances (Part II).
  • Provider reports: transaction and settlement reports, available as files or through an API.
  • Bank statements: what arrived in and left our accounts.
  • Custodians or other external holders, if you hold assets with a third party.

Operational and accounting reconciliation

Two kinds of reconciliation
Operational reconciliationAccounting reconciliation
QuestionDoes every transaction match, one by one?Do the balances and totals tie out?
GranularityPer payment, per payoutPer account, per settlement batch, per period
FrequencyDaily, or more oftenDaily totals, plus a monthly close
Typical findingsA missing webhook, an amount mismatch, a duplicate payoutA clearing account that doesn't return to zero, a bank balance that doesn't match the ledger
Who actsEngineering and operationsFinance, with engineering support

You need both. Operational reconciliation catches individual broken payments fast, while the customer is still waiting. Accounting reconciliation catches what operational matching can't see, like fees being deducted at a different rate than you expected, spread across thousands of correct-looking transactions.

The workflow

The reconciliation workflowSix steps: fetch external reports and statements, normalise them into one record shape, match by reference, compare amounts and statuses, classify discrepancies, and resolve them forward or escalate. Every resolution is recorded. fetchreports, statementsnormaliseone record shapematchby referencecompareamount, statusclassifydiscrepancy kindresolveforward or escalaterecord the resolutionnever edit our records to make the numbers agree
Reconciliation finds differences; it never hides them. A resolution is either our normal processing catching up, or a new, approved correction. It is never an UPDATE that makes our row match theirs.
  1. Fetch external records: the provider's daily report, the bank statement.
  2. Normalise them into one record shape, so matching doesn't care which provider or bank they came from. Keep the raw line too.
  3. Match them to our records by stable references. This is why every earlier part insisted on sending our payment ID to the provider and storing their reference: matching on amount and date alone is guesswork.
  4. Compare amounts, currencies and statuses for each match.
  5. Classify each difference by kind.
  6. Resolve: automatically where the fix is our normal processing catching up, by escalation to a person otherwise. Record every resolution.

The schema

reconciliation.sqlPostgreSQL
-- Every external line we've imported, normalised, with the raw line kept.
CREATE TABLE external_records (
    source        text NOT NULL,             -- 'payco_transactions', 'bank_statement'
    external_id   text NOT NULL,             -- their ID for the line
    our_reference text,                      -- the ID we sent them, if they echo it back
    amount_minor  bigint NOT NULL,
    fee_minor     bigint NOT NULL DEFAULT 0,
    currency      text NOT NULL,
    status        text NOT NULL,             -- normalised: 'SUCCEEDED', 'FAILED', 'REFUNDED'
    occurred_at   timestamptz NOT NULL,
    payout_id     text,                      -- the settlement batch this line was paid out in
    raw           jsonb NOT NULL,
    imported_at   timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (source, external_id)        -- re-importing a file adds nothing
);

-- Every difference found, and what was done about it.
CREATE TABLE recon_discrepancies (
    id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    source        text NOT NULL,
    business_date date NOT NULL,
    kind          text NOT NULL CHECK (kind IN ('MISSING_INTERNAL', 'MISSING_EXTERNAL',
                      'AMOUNT_MISMATCH', 'STATUS_MISMATCH', 'DUPLICATE_EXTERNAL')),
    payment_id    text,
    external_id   text,
    detail        jsonb NOT NULL,            -- both sides, as they were when found
    status        text NOT NULL DEFAULT 'OPEN'
        CHECK (status IN ('OPEN', 'AUTO_RESOLVED', 'RESOLVED', 'ACCEPTED')),
    resolution    text,
    resolved_by   text,
    resolved_at   timestamptz,
    first_seen_at timestamptz NOT NULL DEFAULT now(),
    UNIQUE NULLS NOT DISTINCT (source, kind, payment_id, external_id)  -- re-running finds nothing new
);

Reconciliation gets re-run all the time, after fixes and when files arrive late, so both tables are built to make it idempotent. The primary key means importing the same file twice adds no rows. The unique key means running the match twice for the same day adds no discrepancies, and NULLS NOT DISTINCT (PostgreSQL 15 and later) keeps that working even when one side's ID is missing.

Matching

What matching our records against a provider report can findTwo overlapping circles: our records and the provider report. Only in ours: missing externally. Only in theirs: missing internally. In both: matched, or an amount mismatch, status mismatch, or duplicate external records. our recordsprovider reportMISSING_EXTERNALMISSING_INTERNALmatched ✓AMOUNT_MISMATCHSTATUS_MISMATCHDUPLICATE_EXTERNALeverything except “matched” becomes a discrepancy row
A full outer join is the shape of reconciliation. Records only we have, records only they have, and records we both have but disagree about are all different problems with different owners.

Matching is a full outer join between our records and theirs, followed by a classification:

match.sqlPostgreSQL
-- Match our PayCo payments for one business day against PayCo's report for that day.
-- $1 = source, $2 = business date. Run once the provider's report for the day is final.
WITH ours AS (
    SELECT id, provider_payment_id, amount_minor, currency, status
      FROM payments
     WHERE provider = 'payco'
       AND created_at >= $2::date AND created_at < $2::date + 1
),
theirs AS (
    SELECT external_id, our_reference, amount_minor, currency, status,
           count(*) OVER (PARTITION BY our_reference) AS copies
      FROM external_records
     WHERE source = $1
       AND occurred_at >= $2::date AND occurred_at < $2::date + 1
)
INSERT INTO recon_discrepancies (source, business_date, kind, payment_id, external_id, detail)
SELECT $1, $2::date, kind, payment_id, external_id, detail
  FROM (
    SELECT CASE
             WHEN o.id IS NULL THEN 'MISSING_INTERNAL'
             WHEN t.external_id IS NULL
                  AND o.status IN ('SUCCESS', 'REFUNDED', 'REVERSED') THEN 'MISSING_EXTERNAL'
             WHEN t.external_id IS NULL THEN NULL          -- failed here, unknown there: fine
             WHEN t.copies > 1 THEN 'DUPLICATE_EXTERNAL'
             WHEN o.amount_minor <> t.amount_minor OR o.currency <> t.currency THEN 'AMOUNT_MISMATCH'
             WHEN (o.status IN ('SUCCESS', 'REFUNDED', 'REVERSED')) <> (t.status = 'SUCCEEDED')
                  THEN 'STATUS_MISMATCH'
           END AS kind,
           coalesce(o.id, t.our_reference) AS payment_id,
           t.external_id,
           jsonb_build_object('ours', to_jsonb(o), 'theirs', to_jsonb(t)) AS detail
      FROM ours o
      FULL OUTER JOIN theirs t ON t.our_reference = o.id
  ) m
 WHERE kind IS NOT NULL
ON CONFLICT (source, kind, payment_id, external_id) DO NOTHING;

I ran this against a small test day with one example of each problem deliberately planted. This is the real result:

recon_discrepancies after one runOutput
        kind        | payment_id | external_id | ours_amount | theirs_amount | ours_status | theirs_status
--------------------+------------+-------------+-------------+---------------+-------------+---------------
 AMOUNT_MISMATCH    | pay_2      | pc_2        | 2500        | 2400          | SUCCESS     | SUCCEEDED
 DUPLICATE_EXTERNAL | pay_5      | pc_5a       | 1200        | 1200          | SUCCESS     | SUCCEEDED
 DUPLICATE_EXTERNAL | pay_5      | pc_5b       | 1200        | 1200          | SUCCESS     | SUCCEEDED
 MISSING_EXTERNAL   | pay_4      |             | 3000        |               | SUCCESS     |
 MISSING_INTERNAL   | pay_9      | pc_9        |             | 999           |             | SUCCEEDED
 STATUS_MISMATCH    | pay_3      | pc_3        | 1800        | 1800          | PROCESSING  | SUCCEEDED
(6 rows)

The matched payment and the payment that failed on both sides produced nothing, as they should. Running the match a second time inserted zero rows.

Handling each kind

Discrepancy kinds and how to resolve them
KindCommon causesSafe resolution
STATUS_MISMATCH (ours pending, theirs succeeded)Webhook never arrived (Part VI, scenario 3)Automatic: apply the provider's status through the normal guarded path
STATUS_MISMATCH (ours succeeded, theirs failed)Bug, or a webhook we misreadEscalate. If money didn't move, reverse with an approved journal
MISSING_INTERNALA payment we have no record of: a lost request, a test charge, a bugEscalate. Find the cause; usually refund or record with approval
MISSING_EXTERNALWe think it succeeded; the provider has no recordEscalate urgently: we may have credited money we never received
AMOUNT_MISMATCHFees taken from the amount, currency conversion, partial capture, a bugEscalate. Correct with an approved adjustment, never by editing
DUPLICATE_EXTERNALThe provider charged or paid out twice for one of oursEscalate urgently: refund or recover the duplicate

Only the first row is safe to resolve automatically, and only because the fix is to do what the missing webhook would have done, through the same code it would have gone through:

recon/auto.goGo
// AutoResolve applies provider successes we missed. Everything else stays OPEN for a person.
// It never edits amounts or statuses directly: it goes through ApplyProviderStatus (Part I),
// which enforces the state machine and posts the ledger journal in one transaction.
func AutoResolve(ctx context.Context, pool *pgxpool.Pool, source string, day time.Time) (int, error) {
	rows, err := pool.Query(ctx, `
		SELECT id, payment_id
		  FROM recon_discrepancies
		 WHERE source = $1 AND business_date = $2 AND status = 'OPEN'
		   AND kind = 'STATUS_MISMATCH'
		   AND detail #>> '{ours,status}' IN ('PENDING', 'PROCESSING')
		   AND detail #>> '{theirs,status}' = 'SUCCEEDED'`, source, day)
	if err != nil {
		return 0, err
	}
	type item struct {
		ID        int64
		PaymentID string
	}
	items, err := pgx.CollectRows(rows, pgx.RowToStructByPos[item])
	if err != nil {
		return 0, err
	}
	resolved := 0
	for _, it := range items {
		if err := ApplyProviderStatus(ctx, pool, it.PaymentID, Success); err != nil {
			slog.Warn("auto-resolve failed; leaving open", "payment_id", it.PaymentID, "err", err)
			continue
		}
		_, err := pool.Exec(ctx, `
			UPDATE recon_discrepancies
			   SET status = 'AUTO_RESOLVED', resolution = 'applied missed provider success',
			       resolved_by = 'recon-auto', resolved_at = now()
			 WHERE id = $1 AND status = 'OPEN'`, it.ID)
		if err != nil {
			return resolved, err
		}
		resolved++
	}
	return resolved, nil
}

One-to-many settlement

Providers rarely pay you one bank transfer per payment. They batch a day's payments into a payout, deduct fees, and send one transfer. Stripe's payout reconciliation report exists for this reason: it “helps you match the payouts you receive in your bank account with the batches of payments and other transactions that they relate to” (Stripe: payout reconciliation report).

One bank credit settling many paymentsFour payments of 40.00, 650.00, 12.50 and 560.00 euros are grouped into payout po_77. Fees of 31.00 are deducted, and the bank statement shows a single credit of 1,231.50 referencing po_77. bank statement+ €1,231.50 · ref po_77pay_81 €40.00pay_82 €650.00pay_83 €12.50pay_84 €560.00payout po_77minus fees €31.001,262.50 − 31.00 = 1,231.50 ✓
The bank sees one number; you have to explain it with many. Providers settle in batches, net of fees, so a bank line matches a payout, and the payout matches a set of payments. Amounts are illustrative.

So accounting reconciliation works at the batch level: each bank line should equal the payout it references, and each payout should equal the sum of its transactions minus their fees.

settlement_check.sqlPostgreSQL
-- Each bank credit must equal the provider lines in the payout it references, net of fees.
SELECT b.external_id   AS bank_line,
       b.our_reference AS payout_id,
       b.amount_minor  AS bank_amount,
       sum(p.amount_minor - p.fee_minor) AS expected_amount
  FROM external_records b
  JOIN external_records p
    ON p.source = 'payco_transactions' AND p.payout_id = b.our_reference
 WHERE b.source = 'bank_statement'
 GROUP BY b.external_id, b.our_reference, b.amount_minor
HAVING b.amount_minor <> sum(p.amount_minor - p.fee_minor);

On the same test data, with one correct payout (po_77, the €1,231.50 from the diagram) and one bank credit planted €5.00 short, this returned exactly one row: the short one.

The ledger side is the same check: after a payout settles, the provider clearing account for those payments should return to zero. A clearing account that drifts away from zero over weeks is a classic sign of fees or refunds being booked differently than they're settled.

Timing, tolerance and late data

A payment made at 23:58 may appear in tomorrow's report, so match each day only once its report is final, and re-check unmatched items for a few days before calling them missing. Providers also reissue reports sometimes. Because importing and matching are idempotent, re-running after a correction is safe and only adds what's new.

Resist the urge to “ignore differences under one cent”. Small systematic differences are usually a rounding rule that disagrees with the provider's (Part II), and they add up. Accept a difference only as a recorded decision (ACCEPTED, with a reason), never by default.

Exception management

Every open discrepancy is work for a person, so treat it like any other queue of work. Each one needs an owner, an age, and a target time to resolve, which is shorter for duplicates and missing external records because those may mean money has left.

Track the count and age of open discrepancies on the dashboard (Chapter 18), and review the resolved ones periodically: recurring kinds point to bugs worth fixing upstream.

Checklist

  • Every transaction is matched against at least one independent source, daily.
  • Matching uses stable references we sent to the provider, not amount and date.
  • Importing and matching are idempotent and safe to re-run.
  • Each discrepancy is stored with both sides' data as they were when found.
  • Only “we missed a success” is auto-resolved, through the normal guarded path.
  • Corrections are new approved records; nothing is edited to make numbers agree.
  • Payouts are reconciled against bank statements, net of fees.
  • Open discrepancies have owners, ages and alerts.

Further reading

What's next

We can now see what the system is doing, and catch what it got wrong. Part VIII, Putting It All Together, is the last part: every mechanism from the handbook in one architecture, four complete flows through it, and one end-to-end test that runs them all against a real database.

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.