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:
| Field | What it identifies | Set by |
|---|---|---|
transaction_id | Our payment, withdrawal or transfer (pay_81) | Whoever creates it |
external_transaction_id | The client's own ID for it, if they sent one | API ingestion |
provider_reference | The provider's ID (pc_9KD) | Provider responses and webhooks |
event_id | The event being processed (Part IV envelope) | Outbox insert |
idempotency_key | The client's key for the operation | API ingestion |
correlation_id | Everything caused by one original request | First service to see the request |
trace_id | The distributed trace (W3C Trace Context) | Tracing library |
consumer | Which handler is processing (wallet-credit) | Consumer |
attempt | Which delivery or retry this is | Consumer (SQS receive count) |
transaction_status | Status before and after a change | State 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.
// 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):
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 ReplaceAttrThis is the real output of that code (I removed the time field to keep the lines short):
{"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.
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.
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.
// 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:
| Layer | Metric | Why it matters |
|---|---|---|
| Business | Payments succeeded / failed per minute; success ratio | The most direct customer symptom |
| Business | Payments stuck in PENDING/PROCESSING over N minutes | Customers who paid and are waiting |
| Business | Payout completion time; payouts stuck in INITIATED | Money owed to customers that hasn't arrived |
| Business | Reversals per hour; ledger posting failures; open reconciliation discrepancies | Money that needed correcting, or might |
| Queue | Age of oldest message; visible and in-flight messages; DLQ depth; receive count | How far behind processing is (Part IV) |
| Application | Events processed, failed and duplicated per consumer; processing duration; retries by error class; worker utilisation | Where the work is going wrong |
| Database | Active, idle and waiting connections; pool saturation; transaction duration; lock waits; deadlocks; slow queries; CPU and I/O | Whether the database is the bottleneck (Part V) |
Instrumenting a consumer
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
- 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:
-- 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
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:
| Alert | Illustrative condition | Severity |
|---|---|---|
| Payment success ratio burning error budget fast | See burn-rate alerts below | Page |
| Payments stuck in PROCESSING | More than a handful older than 30 minutes | Page |
| Payments DLQ not empty | Any message for 5 minutes | Page in hours, ticket out of hours |
| Oldest message age, credit queue | Above 10 minutes | Page |
| Outbox lag | Oldest pending row above 5 minutes | Page |
| Late success anomalies | Any new payment_anomalies row | Ticket, same day |
| Reconciliation discrepancies | Any new open discrepancy | Ticket, same day |
| Database pool saturation | Above 80% for 15 minutes | Ticket |
| CPU high on one node | n/a | Dashboard 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):
| Severity | Long window | Short window | Burn rate | Error budget consumed |
|---|---|---|---|---|
| Page | 1 hour | 5 minutes | 14.4 | 2% |
| Page | 6 hours | 30 minutes | 6 | 5% |
| Ticket | 3 days | 6 hours | 1 | 10% |
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:
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
- Establish a baseline. Record throughput, p95, p99, CPU and memory under a known workload.
- Reproduce the workload. A benchmark, a load test, or production traffic itself.
- Capture a profile while the workload runs.
- Identify the bottleneck. Find where the time or memory goes in your code.
- Change one thing.
- Run the same workload again.
- 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.”
// 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)
}
}()
}# 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.outA 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:
// 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:
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.compileOnePassAll 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.
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).SimplifyThe fix is one change: compile the pattern once, when the package starts.
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
}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/opAbout 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
| Symptom | Look at first | Usual causes |
|---|---|---|
| High CPU | CPU profile (-cum) | Work repeated in a loop (like the regex), JSON encoding of large payloads, logging too much |
| Memory keeps growing | Heap profile (inuse_space), then compare two profiles taken minutes apart | Unbounded caches or maps, buffers kept alive, goroutine leaks |
| Goroutine count keeps growing | /debug/pprof/goroutine?debug=1 | Goroutines blocked forever on a channel or a call with no timeout |
| High p99, normal average | Traces of slow requests; block and mutex profiles; database lock waits | Lock contention, hot rows (Part V), GC pauses, retries |
| Slow queries | pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS) (Part V) | Missing or wrong indexes, OFFSET pagination |
| Pool exhaustion | pool.Stat() waits; pg_stat_activity idle-in-transaction | Long transactions, network calls inside transactions |
| Queue backlog | Processing time p99, worker utilisation, dependency latency | A 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
-benchmemand several counts. - Dashboards show p95, p99 and saturation, not only averages.
GOMEMLIMITis 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
| Operational reconciliation | Accounting reconciliation | |
|---|---|---|
| Question | Does every transaction match, one by one? | Do the balances and totals tie out? |
| Granularity | Per payment, per payout | Per account, per settlement batch, per period |
| Frequency | Daily, or more often | Daily totals, plus a monthly close |
| Typical findings | A missing webhook, an amount mismatch, a duplicate payout | A clearing account that doesn't return to zero, a bank balance that doesn't match the ledger |
| Who acts | Engineering and operations | Finance, 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
UPDATE that makes our row match theirs.- Fetch external records: the provider's daily report, the bank statement.
- Normalise them into one record shape, so matching doesn't care which provider or bank they came from. Keep the raw line too.
- 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.
- Compare amounts, currencies and statuses for each match.
- Classify each difference by kind.
- Resolve: automatically where the fix is our normal processing catching up, by escalation to a person otherwise. Record every resolution.
The schema
-- 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
Matching is a full outer join between our records and theirs, followed by a classification:
-- 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:
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
| Kind | Common causes | Safe 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 misread | Escalate. If money didn't move, reverse with an approved journal |
| MISSING_INTERNAL | A payment we have no record of: a lost request, a test charge, a bug | Escalate. Find the cause; usually refund or record with approval |
| MISSING_EXTERNAL | We think it succeeded; the provider has no record | Escalate urgently: we may have credited money we never received |
| AMOUNT_MISMATCH | Fees taken from the amount, currency conversion, partial capture, a bug | Escalate. Correct with an approved adjustment, never by editing |
| DUPLICATE_EXTERNAL | The provider charged or paid out twice for one of ours | Escalate 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:
// 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).
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.
-- 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
- Go: log/slog: structured logging,
ReplaceAttrandLogValuer. - W3C Trace Context and OpenTelemetry for Go.
- OpenTelemetry: messaging span conventions.
- Prometheus: naming and labels, instrumentation and histograms.
- Prometheus Go client: promauto.
- Google SRE: monitoring distributed systems and alerting on SLOs.
- Go: diagnostics, net/http/pprof and the GC guide.
- Stripe: payout reconciliation report.
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.