Sub topic 18
Monitoring and observability
This chapter assumes you have read the earlier chapters on idempotency, the payment state machine, the ledger, retries, webhooks, and reconciliation. It also assumes you know what a metric, a log line, and a distributed trace are in general terms. Here we apply those tools to a payment platform, where the worst failures are silent. A service can return HTTP 200 on every request and still lose money.
What is different about monitoring payments
Ordinary service monitoring watches latency, error rate, and saturation. A payment system needs those, and it also needs to watch business correctness:
- A payment stuck in
authorizedfor days is not an error response, but it is a problem. - A spike in issuer declines may come from a bad release, a PSP outage, or a fraud attack. Each has a different fix.
- A ledger that no longer balances is a critical incident even if every API call succeeded.
Observability means you can ask new questions about the system from the data it already emits, without shipping new code. For payments, the most common question is "what happened to payment X?" You answer it by emitting the same identifiers everywhere.
The three signals
| Signal | Best used for | Payment example |
|---|---|---|
| Metrics | Alerting and trends | Authorization success rate per PSP, p99 latency |
| Logs | Detail about one event | Why a specific PSP call failed |
| Traces | Following one request across services | API, risk check, PSP call, ledger write |
Correlation identifiers
Every log line and span should carry these fields:
payment_id, the internal identifier.merchant_id, to isolate one merchant's problem.idempotency_key, so you can see all retries of one logical request.trace_id, to link spans across services.psp_reference, the identifier the PSP returned, which support teams and the PSP both need.
Pass trace_id to the PSP adapter and to the message queue headers. Without this, the outbox relay and webhook handler appear as separate, unrelated traces.
Never log sensitive data
Logs are copied to many systems and kept for a long time. Card numbers (PANs), CVVs, and full tokens must never appear in them. If logs contain card data, your log pipeline falls into PCI DSS scope, which is costly. Log the token's last four digits or an internal token ID, and filter request bodies by allow-list rather than deny-list. An allow-list logs only the fields you named, so a new sensitive field is excluded by default.
Metrics that matter
Group metrics by what they tell you.
Health of the request path
- Request rate, error rate, and latency (p50, p95, p99) per endpoint.
- Latency of each PSP call, tagged by PSP and operation (authorize, capture, refund).
- Timeout rate per PSP. Timeouts are the dangerous case because the outcome is unknown.
Business outcomes
- Authorization success rate, split by PSP, card network, issuer country, and merchant.
- Decline reasons. Separate technical failures (timeouts, 5xx) from issuer declines (insufficient funds). A technical failure is your problem. An issuer decline is usually not.
- Payments per state, and the age of the oldest payment in each non-terminal state.
Correctness
- Ledger imbalance: the sum of debits minus credits per currency. It must be exactly zero.
- Idempotency conflicts: how often a key is reused with a different request hash. A rise often points to a client bug.
- Outbox lag: the age of the oldest unpublished outbox row.
- Webhook delivery failures and retry backlog.
- Reconciliation mismatches: count and total amount of items that do not match PSP or bank reports.
Example: instrumenting success rate
The following program writes structured logs and checks the technical success rate of each PSP over a sliding window. It only alerts when it has enough samples to avoid noise at low traffic.
import json
import logging
from collections import defaultdict, deque
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("payments")
def log_event(event, payment_id, trace_id, **fields):
record = {"event": event, "payment_id": payment_id, "trace_id": trace_id, **fields}
logger.info(json.dumps(record, sort_keys=True))
class SuccessRateMonitor:
"""Tracks technical success (no timeout or 5xx) per PSP over a time window."""
def __init__(self, window_seconds=300, min_samples=20, threshold=0.9):
self.window = window_seconds
self.min_samples = min_samples
self.threshold = threshold
self.samples = defaultdict(deque) # psp -> deque of (timestamp, ok)
def record(self, psp, ok, now):
self.samples[psp].append((now, ok))
def check(self, psp, now):
q = self.samples[psp]
while q and q[0][0] < now - self.window:
q.popleft()
if len(q) < self.min_samples:
return None # too little data to judge
rate = sum(1 for _, ok in q if ok) / len(q)
return rate if rate < self.threshold else None
monitor = SuccessRateMonitor()
for i in range(100):
ok = i % 5 != 0 # every fifth call fails
monitor.record("psp_a", ok, now=1000 + i)
rate = monitor.check("psp_a", now=1100)
if rate is not None:
log_event("psp_success_rate_low", payment_id=None, trace_id="t-1",
psp="psp_a", rate=rate)Running it prints one JSON line reporting a rate of 0.8 for psp_a. In production you would export this as a gauge to your metrics system and let the alerting system evaluate it. The same pattern, with the same minimum-sample guard, applies to every ratio metric.
Alerting without alert fatigue
Alert on symptoms that need a human, and send everything else to a dashboard or ticket.
- Page for customer-visible impact: the success rate drops below its baseline, the ledger is unbalanced, or the outbox lag exceeds a few minutes.
- Ticket for slow problems: reconciliation mismatches that grow over days, or rising idempotency conflicts.
- Compare to a baseline. Authorization rates vary by hour and by region. A fixed threshold either misses real drops or pages every night. Compare with the same hour last week.
- Segment before you alert. A global rate of 95% can hide a PSP at 40% if it carries little traffic. Alert per PSP, per merchant tier, and per payment method.
Define service level objectives (SLOs), for example "99.9% of authorization requests complete without a technical failure within 2 seconds, measured monthly." An SLO gives you an error budget, which is the amount of failure you can afford. You can alert when the budget is burning too fast.
Synthetic checks and canaries
Real traffic may be too sparse to reveal a problem quickly. A synthetic payment is a scheduled test transaction against a PSP's test mode or a low-value live card. It exercises the whole path every minute. After a release, send a small share of traffic to the new version (a canary) and compare its success rate with the old version before continuing.
Investigating an incident
When a merchant reports a missing payment, work in this order:
- Search logs by
idempotency_keyorpayment_idand read the state transitions. - Open the trace to see which step was slow or failed.
- Check the outbox and webhook queues for this payment.
- Compare with the PSP dashboard using
psp_reference. - Check whether reconciliation has flagged it.
Each step relies on identifiers that were logged earlier. If one is missing, you cannot link the evidence.
Exercise
Your global authorization success rate is steady at 96%, but a merchant complains that many payments fail. Name two reasons the global metric may hide the problem, and one change to your monitoring that would reveal it.
Show answer
The affected traffic may be a small share of the total, so it barely moves the global average, or the failures may be limited to one PSP, card network, or merchant. Segment the success rate by PSP, merchant, and payment method, and alert on each segment (with a minimum sample count). Separating technical failures from issuer declines also helps, because declines do not point to a fault in your system.
Exercise
Why should a payment dashboard show the age of the oldest payment in the authorized state and not only the number of payments in that state?
Show answer
A count can stay low while one payment is stuck for days, for example after a lost capture call or a missed webhook. The oldest age exposes that stuck item, and it can drive an alert such as "any payment in authorized older than the capture deadline."