Everything so far has treated failure as an occasional event: a lost reply, a crashed worker, a duplicate webhook. This part is about the bad afternoon, when a dependency is down for twenty minutes, tens of thousands of messages pile up, and the way your system recovers decides whether the incident ends there or starts again.
Chapter 15 is about retries: when to retry, how long to wait, and why retries that look harmless one at a time can take down a healthy system together. Chapter 16 walks through ten concrete failure scenarios, each with what state it leaves behind and how to recover without moving money twice.
Chapter 15
Retry strategies, exponential backoff and recovery storms
The problem: the recovery that causes the second outage
I've seen this incident shape more than once. PayCo has a problem and returns errors for twenty minutes. Our payment workers keep receiving messages, failing, and retrying. The queue grows to 50,000 messages.
Then PayCo recovers, and every worker, all of them retrying on the same short fixed delay, succeeds at the same moment, pulls the next batch and sends it. PayCo, which had just come back with cold caches and a fraction of its capacity warmed up, receives in twenty seconds what it normally handles in twenty minutes. It falls over again. Our workers retry again. Repeat.
This is a retry storm, also called a thundering herd. Nothing in it is a bug in the usual sense, and each retry on its own is reasonable.
The Amazon Builders' Library puts it well: retries are “selfish”: each client spends someone else's capacity to improve its own chance of success (Amazon Builders' Library: timeouts, retries and backoff with jitter). Google's SRE book is blunter: “retries can destabilize a system” (Google SRE: addressing cascading failures).
So the question isn't whether to retry, but how to retry so a struggling dependency gets room to recover instead of being held down.
Only retry what can succeed, and what is safe to repeat
Before “how”, decide “whether”. A retry is only useful if the failure might be temporary, and only safe if the operation is idempotent (Part III).
| Failure | Retry? | Why |
|---|---|---|
| Timeout, connection reset | Yes, with the same idempotency key | Outcome unknown; the key makes a repeat harmless |
| HTTP 5xx | Yes | Usually temporary |
| HTTP 429 Too Many Requests | Yes, slower | You're being rate-limited; respect Retry-After if present |
PostgreSQL 40001 serialization failure, 40P01 deadlock | Yes | The database is asking you to try again |
PostgreSQL 55P03 lock not available, 57014 query cancelled (timeouts) | Yes, with backoff | Contention or overload; waiting helps |
PostgreSQL 53300 too many connections | Yes, with backoff, and fix the budget | See Part V |
| HTTP 400, 401, 403, 404, 409, 422 | No | The request is wrong; it will fail the same way |
| Card declined, insufficient funds | No | A business answer, not a failure |
The PostgreSQL error codes are from the documentation's error code table (PostgreSQL: error codes). For HTTP 429, the status means “the user has sent too many requests in a given amount of time”, and the response may include a Retry-After header (RFC 6585), which can be either a date or a number of seconds (RFC 9110).
Not every provider sends one; Stripe, for example, returns 429 and advises an exponential backoff with randomness added (Stripe: rate limits).
// HTTPError is returned by our provider clients for non-2xx responses.
type HTTPError struct {
Status int
RetryAfter time.Duration // parsed from the Retry-After header, if any
}
func (e *HTTPError) Error() string { return fmt.Sprintf("provider returned HTTP %d", e.Status) }
// Retryable reports whether err is worth retrying. Callers must also make sure
// the operation is idempotent: a retried timeout may repeat work that happened.
func Retryable(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch pgErr.Code {
case "40001", "40P01", "55P03", "57014", "53300":
return true
}
return false
}
var httpErr *HTTPError
if errors.As(err, &httpErr) {
return httpErr.Status == http.StatusTooManyRequests || httpErr.Status >= 500
}
var netErr net.Error
if errors.As(err, &netErr) {
return true // connection refused or reset, DNS failure, timeout
}
return errors.Is(err, context.DeadlineExceeded)
}Four ways to wait
- Immediate retry. Try again straight away. Occasionally fine for a single blip, but under load it doubles traffic just when the dependency can least take it.
- Fixed delay. Wait one second each time. Better, but every client that failed at the same moment retries at the same moment, forever.
- Exponential backoff. Double the wait each time: 200 ms, 400 ms, 800 ms … capped at some maximum. Load falls off quickly. But clients that failed together still retry together, in bigger and bigger waves.
- Exponential backoff with jitter. Pick a random wait up to the exponential limit. The waves break up, and retries spread evenly over time. Google's SRE book says to “always use randomized exponential backoff when scheduling retries” (Google SRE).
There are a few ways to add the randomness. With full jitter, the wait is a random value between zero and the exponential limit. With equal jitter, it's half the limit plus a random value up to the other half, so it never waits very little.
Full jitter spreads load the most evenly, and it's what AWS's SDKs use: their documented formula is a random fraction of min(20 s, base × 2retry) (AWS SDKs: retry behaviour). That's what I use too.
To check that the difference is real, I simulated 1,000 clients that all fail at the same moment against a dependency that's down for 20 seconds, then counted requests in the busiest 100 ms after it recovered.
With a fixed 1-second delay: 1,000. With plain exponential backoff: still 1,000, because every client is on the same schedule. With exponential backoff and full jitter: 13. The clients and the outage were identical in all three runs; only the randomness changed.
| Attempt | Exponential limit (base 200 ms, cap 30 s) | Full-jitter wait |
|---|---|---|
| 1 | 200 ms | random 0–200 ms |
| 2 | 400 ms | random 0–400 ms |
| 3 | 800 ms | random 0–800 ms |
| 4 | 1.6 s | random 0–1.6 s |
| 5 | 3.2 s | random 0–3.2 s |
| 6 | 6.4 s | random 0–6.4 s |
| 8 | 25.6 s | random 0–25.6 s |
| 9+ | 30 s (cap) | random 0–30 s |
// Backoff returns how long to wait before retry number attempt (starting at 1):
// a random duration between 0 and min(max, base × 2^(attempt-1)). This is "full jitter".
func Backoff(attempt int, base, max time.Duration) time.Duration {
limit := max
if attempt < 32 {
if d := base << (attempt - 1); d > 0 && d < max {
limit = d
}
}
return time.Duration(rand.Int64N(int64(limit) + 1))
}rand.Int64N from math/rand/v2 is safe to call from many goroutines at once. The attempt < 32 guard stops the shift from overflowing on a very long retry run.
Limit the total: attempts and retry budgets
Backoff controls when you retry, but you also need a limit on how much, and that takes two limits working together.
The first is per operation. Google's SRE book describes “a per-request retry budget of up to three attempts” (Google SRE: handling overload), and AWS SDKs default to three attempts too: one request plus up to two retries (AWS SDKs: retry behaviour).
The second is per client. Even three attempts per operation can triple your traffic during an outage, so also cap retries as a fraction of normal traffic. Google's approach only retries “as long as this ratio is below 10%” (Google SRE); AWS describes the same idea as a local token bucket (Amazon Builders' Library).
While the dependency is healthy, almost every call succeeds and the budget stays full. Once it's down, the budget drains after a handful of retries and the client stops piling on.
// RetryBudget allows retries only while they stay a small fraction of traffic.
// Every success earns `ratio` of a token (0.1 = retries up to ~10% of successes);
// every retry spends one whole token. Tokens are counted in thousandths: adding a
// float 0.1 ten times gives 0.9999999999999999, which is never "one token".
// A nil budget allows everything.
type RetryBudget struct {
mu sync.Mutex
milli int64 // tokens × 1000
max int64
earn int64
}
func NewRetryBudget(ratio float64, maxTokens int) *RetryBudget {
return &RetryBudget{
milli: int64(maxTokens) * 1000,
max: int64(maxTokens) * 1000,
earn: int64(math.Round(ratio * 1000)),
}
}
func (b *RetryBudget) onSuccess() {
if b == nil {
return
}
b.mu.Lock()
b.milli = min(b.max, b.milli+b.earn)
b.mu.Unlock()
}
func (b *RetryBudget) allowRetry() bool {
if b == nil {
return true
}
b.mu.Lock()
defer b.mu.Unlock()
if b.milli < 1000 {
return false
}
b.milli -= 1000
return true
}
type RetryPolicy struct {
MaxAttempts int
Base, Max time.Duration
Budget *RetryBudget
}
// Do runs op until it succeeds, fails permanently, runs out of attempts or budget,
// or ctx ends. op must be idempotent.
func Do(ctx context.Context, p RetryPolicy, op func(context.Context) error) error {
for attempt := 1; ; attempt++ {
err := op(ctx)
if err == nil {
p.Budget.onSuccess()
return nil
}
if !Retryable(err) || attempt >= p.MaxAttempts || !p.Budget.allowRetry() {
return err
}
wait := Backoff(attempt, p.Base, p.Max)
var httpErr *HTTPError
if errors.As(err, &httpErr) && httpErr.RetryAfter > wait {
wait = httpErr.RetryAfter // the server told us how long; believe it
}
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}Retries in a queue consumer
In a queue-based system, most retries aren't loops in code; they're redeliveries. The consumer doesn't delete a message, and SQS hands it out again after the visibility timeout (Part IV). By default that's a fixed delay, the worst of the options above. Instead, when a handler fails with a retryable error, set the message's visibility timeout to a backoff delay based on how many times it has already been received:
// deferRetry hides a failed message for a jittered, growing delay instead of the
// queue's fixed visibility timeout. After maxReceiveCount, the redrive policy
// still moves it to the dead-letter queue.
func deferRetry(ctx context.Context, client *sqs.Client, queueURL string, msg sqstypes.Message) error {
receives, _ := strconv.Atoi(msg.Attributes["ApproximateReceiveCount"])
delay := Backoff(max(receives, 1), 2*time.Second, 10*time.Minute)
_, err := client.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: msg.ReceiptHandle,
VisibilityTimeout: int32(delay.Seconds()),
})
return err
}Combine this with a dead-letter queue (Part IV) for poison messages: anything that has failed many times stops being retried and becomes a person's job.
Retry in one layer only
A customer taps “Pay” and the app retries three times. Each of those requests hits our API, which retries its call to the payment service three times, and the payment service uses an SDK that retries PayCo three times. One tap can now reach PayCo 27 times.
This is retry amplification, and it grows fast: Google's example has “a single user action” creating “64 attempts (4^3) on the database” (Google SRE), and the Builders' Library example reaches 243× with five layers (Amazon Builders' Library). AWS's advice is to “retry at a single point in the stack”.
In a payment system, the natural single point is the layer that owns the idempotency key and the queue: the worker that processes the payment. Everything above it fails fast and lets the queue redeliver. Everything below it (HTTP clients, SDKs) is configured to make one attempt. Check your SDKs: AWS SDKs retry by default, so configure their attempts explicitly when another layer owns retries.
Circuit breakers: stop calling what's down
When PayCo is fully down, every call waits for a timeout before failing, so workers spend their time waiting while connections and goroutines pile up. A circuit breaker notices the failures and starts failing calls immediately, without making them, for a cool-down period.
Martin Fowler's description: the breaker calls the protected code “if the circuit is closed, but return[s] an error if it's open”, and a half-open state makes “a real call as trial to see if the problem is fixed” (Martin Fowler: CircuitBreaker).
var ErrCircuitOpen = errors.New("circuit open: not calling dependency")
// Breaker opens after `threshold` consecutive failures, fails fast for `coolDown`,
// then lets one trial call through (half-open). One per dependency, shared by workers.
type Breaker struct {
mu sync.Mutex
failures int
threshold int
coolDown time.Duration
openUntil time.Time
trial bool // a half-open trial call is in flight
}
func NewBreaker(threshold int, coolDown time.Duration) *Breaker {
return &Breaker{threshold: threshold, coolDown: coolDown}
}
func (b *Breaker) Call(ctx context.Context, op func(context.Context) error) error {
b.mu.Lock()
if b.failures >= b.threshold {
if time.Now().Before(b.openUntil) || b.trial {
b.mu.Unlock()
return ErrCircuitOpen // open, or a trial is already running
}
b.trial = true // half-open: this caller is the trial
}
b.mu.Unlock()
err := op(ctx)
b.mu.Lock()
defer b.mu.Unlock()
b.trial = false
if err != nil && Retryable(err) {
b.failures++
if b.failures >= b.threshold {
b.openUntil = time.Now().Add(b.coolDown)
}
} else {
b.failures = 0 // success, or a permanent error that says nothing about health
}
return err
}This counts consecutive failures, which is easy to reason about. Production breakers often use a failure rate over a time window instead, so a busy service doesn't trip on a short burst. Whichever you use, keep one breaker per dependency, shared by every worker that calls it, and a worker that gets ErrCircuitOpen defers the message (as above) rather than counting it as a failure of the payment.
Rate limits, quotas and bulkheads
Rate limits and bulkheads both stop one dependency's problems from becoming everyone's.
Client-side rate limits keep you under a provider's quota, so you don't learn about it through 429s. Go's golang.org/x/time/rate package provides a token-bucket Limiter; Wait blocks until a call is allowed (x/time/rate):
// One limiter per provider quota, shared by all workers in the process.
// Divide the provider's quota by the number of processes calling it.
var paycoLimiter = rate.NewLimiter(rate.Limit(40), 10) // 40 calls/s, bursts of 10
func callPayCo(ctx context.Context, op func(context.Context) error) error {
if err := paycoLimiter.Wait(ctx); err != nil {
return err // ctx ended while waiting
}
return op(ctx)
}Bulkheads come from ship design: separate compartments so one leak doesn't sink the ship. In software: “isolate the elements of an application into pools so that if one element fails, the others continue to function” (Azure Architecture Center: bulkhead pattern). In a payment engine that means separate worker pools (or separate queues and consumers, as in Part IV) per dependency, and separate database pools per service (Part V).
Recovering without a second outage
Back to the incident at the start: PayCo is back and you have 50,000 messages waiting. You want to drain them as fast as PayCo and your database can take, and no faster. In order:
- Detect recovery with a few trial calls (the breaker's half-open state), not with every worker at once.
- Start with low concurrency, well below normal.
- Increase gradually while things look healthy: error rate low, latency near normal. Back off quickly at the first sign of strain. This is additive increase, multiplicative decrease (AIMD), the same idea TCP uses to find a network's capacity.
- Remember the database. A backlog of payments means a burst of ledger writes. Cap concurrency by the connection budget (Part V), whatever the provider can take.
// AIMDLimit adjusts how many messages a consumer processes at once.
// It adds one slot after each healthy interval and halves on errors or slowness.
type AIMDLimit struct {
mu sync.Mutex
limit int
min, max int
}
func NewAIMDLimit(start, min, max int) *AIMDLimit {
return &AIMDLimit{limit: start, min: min, max: max}
}
// OnInterval is called every interval (say, 30 s) with what happened in it.
func (a *AIMDLimit) OnInterval(errorRate float64, p99, targetP99 time.Duration) {
a.mu.Lock()
defer a.mu.Unlock()
if errorRate > 0.05 || p99 > targetP99 {
a.limit = max(a.min, a.limit/2)
return
}
a.limit = min(a.max, a.limit+1)
}
func (a *AIMDLimit) Current() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.limit
}The consumer from Part IV received “as many messages as it has free workers”; with this, the number of workers is Current() instead of a constant, and max comes from the connection budget. The queue holds the backlog safely while the limit climbs, and messages waiting in SQS cost you very little compared with work waiting inside your database.
What to monitor
- Retry rate per dependency, as a fraction of calls. A rising retry rate is often the first sign of trouble.
- Budget exhaustion: how often retries were refused by the retry budget.
- Breaker state per dependency, and time spent open.
- Concurrency limit over time (the AIMD value), next to queue age and database connections.
- 429 responses from providers, and how close you run to their quotas.
What to test
- Make a fake provider fail for 5 minutes under load, then recover. Measure peak request rate after recovery: it should stay near the configured ceiling, not spike.
- Check that a permanent error (
422, card declined) is never retried. - Count total calls to the provider for one failing customer action across all layers. It should equal the attempts of the one retrying layer.
- Trip the breaker and confirm workers defer messages without calling the provider until half-open.
Checklist
- Only transient errors are retried, and only for idempotent operations.
- Every retry waits with exponential backoff and full jitter, with a cap.
- Retries are limited per operation and by a retry budget per client.
- Exactly one layer retries; the others fail fast; SDK retries are configured explicitly.
- Queue consumers defer failed messages with growing delays, and poison messages reach a DLQ.
- Each dependency has a circuit breaker and its own bulkhead.
- Provider quotas are respected with client-side rate limits.
- Recovery ramps concurrency up gradually, capped by the database budget.
Chapter 16
Failure handling and compensation
This chapter is a catalogue of things that will happen to a payment system in production, usually within the first year. Each scenario answers the same five questions:
- What happened?
- What state might the system be left in?
- How do we detect it?
- How do we recover safely?
- How do we make sure money doesn't move twice?
Forward recovery or compensation?
Every recovery is one of two kinds. Forward recovery finishes what was started: retry the step, ask the provider what happened, apply the late webhook. Compensation undoes what was done with a new record: a reversal journal, a refund. Part V introduced both, and choosing between them comes down to one question:
Most of the scenarios below are forward recoveries, because most failures leave the outcome unknown rather than negative.
1. The provider times out after accepting a payment
- What happened: We called PayCo to charge a card. PayCo charged it, but our call timed out before the response arrived.
- State left: PayCo: charged. Us:
PROCESSING(if we followed Part I) or, wrongly,FAILED. - Detect: Payments in
PROCESSINGpast a threshold. The success webhook will usually arrive on its own. - Recover: Forward. Wait for the webhook, and run a job that asks PayCo about payments that have been unknown for too long (below).
- No double movement: We sent our payment ID as PayCo's idempotency key, so a retried charge returns the original. The success is applied through the conditional transition, once.
// StatusClient asks the provider about a payment by OUR payment ID, which we sent
// as the provider's idempotency key and reference when we created it.
type StatusClient interface {
GetPaymentStatus(ctx context.Context, paymentID string) (Status, error)
}
// ResolveUnknown applies the provider's answer for payments that have been
// PENDING or PROCESSING too long, through the same guarded path as webhooks.
func ResolveUnknown(ctx context.Context, pool *pgxpool.Pool, provider StatusClient, olderThan time.Duration) error {
rows, err := pool.Query(ctx, `
SELECT id FROM payments
WHERE status IN ('PENDING', 'PROCESSING')
AND updated_at < now() - make_interval(secs => $1)
ORDER BY updated_at
LIMIT 100`, olderThan.Seconds())
if err != nil {
return err
}
ids, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return err
}
for _, id := range ids {
status, err := provider.GetPaymentStatus(ctx, id)
if err != nil {
slog.Warn("status still unknown", "payment_id", id, "err", err)
continue // try again on the next run
}
if err := ApplyProviderStatus(ctx, pool, id, status); err != nil {
slog.Warn("could not apply provider status", "payment_id", id, "err", err)
}
}
return nil
}2. A webhook is delivered twice
- What happened: We processed a webhook, but our
200was lost or late. PayCo sent it again. - State left: Correct, after the first delivery.
- Detect: The
provider_eventsinsert finds a conflict; count these as duplicates. - Recover: Nothing to recover. Return
200. - No double movement: The raw event is deduplicated on PayCo's event ID (Part IV), the consumer's inbox deduplicates on our event ID (Part III), and the status transition and journal source key refuse a second application (Parts I–II).
3. A webhook is never delivered
- What happened: PayCo gave up after its retry window, or our endpoint was misconfigured for a day, or the event was never sent.
- State left: PayCo: succeeded. Us:
PROCESSINGindefinitely. The customer paid and has nothing. - Detect: The same stuck-payment query as scenario 1, and reconciliation (Chapter 20): PayCo's report lists a payment our ledger doesn't have.
- Recover: Forward, with
ResolveUnknown. For a misconfigured endpoint, many providers let you replay events for a time window. - No double movement: Same guards as scenario 2. If the webhook turns up late after polling has applied it, it's a duplicate.
4. The database commit succeeds, but deleting the SQS message fails
- What happened: A worker credited a wallet and committed, then
DeleteMessagefailed or the worker crashed before it. - State left: Correct in the database; the message is still in the queue.
- Detect: Receive counts above 1, and inbox duplicate hits.
- Recover: Nothing to do. After the visibility timeout, the message is redelivered and skipped.
- No double movement: The inbox row was written in the same transaction as the credit (Part III), so the redelivery is recognised.
5. The outbox publish succeeds, but the status update fails
- What happened: The outbox publisher sent an event to SNS, then crashed before marking the row
PUBLISHED. - State left: Event delivered; outbox row still
PENDINGwith a claim lease. - Detect: Not needed for correctness. You'll see the event published twice in logs.
- Recover: Automatic. The lease expires and another publisher republishes it (Part IV).
- No double movement: The republished event has the same
event_id; every consumer's inbox drops it.
6. A payout succeeds, but the acknowledgement is lost
- What happened: We sent a €80 payout to PayCo. PayCo accepted it, but the response never arrived.
- State left: PayCo: payout accepted, money on its way. Us:
PAYOUT_INITIATED. - Detect: Withdrawals in
PAYOUT_INITIATEDpast a threshold (the sweeper from Part V). - Recover: Forward. Resend with the same key,
payout:wd_88. PayCo returns the original payout, and we move toPAYOUT_ACKNOWLEDGED. - No double movement: The derived key. Just as important, we did not treat the timeout as a failure and release the funds, which would have let the customer spend €80 that's already on its way to their bank.
7. The application crashes midway through a workflow
- What happened: A deploy, out-of-memory kill or node failure stopped a worker between steps of a withdrawal or payment.
- State left: Whatever the last committed checkpoint says: for example
FUNDS_RESERVEDwith no payout sent. - Detect: The sweeper's stuck-workflow query; the message being redelivered after its visibility timeout.
- Recover: Forward.
Advanceresumes from the checkpoint (Part V). - No double movement: Each step's effect and checkpoint commit together, and each step is guarded by a compare-and-swap on the status.
Graceful shutdown reduces how often this happens: on a stop signal, a worker stops receiving new messages, lets in-flight ones finish within a deadline, then exits. But design as if shutdown is never graceful, because sometimes it isn't.
8. The database becomes unavailable
- What happened: A failover, a network partition, an exhausted connection limit, or an outage.
- State left: Every transaction in flight either committed or rolled back. Nothing is half-written, thanks to atomic transactions.
- Detect: Connection errors, pool acquire timeouts, health checks.
- Recover: Stop accepting work you can't record. APIs return
503withRetry-After. Webhook ingestion returns5xxso the provider retries later. Workers stop receiving and let messages wait in the queue. When the database returns, ramp up (Chapter 15). - No double movement: Never “buffer” payments in memory or Redis to apply later. If it isn't committed to the database, it didn't happen; let the caller or the queue retry.
One subtle case: a commit whose acknowledgement is lost when the connection drops. The client can't tell whether the transaction committed. It's the database version of scenario 1, with the same answer: the retry runs the same idempotent operation, and the guards make it a no-op if the first attempt did commit.
9. Redis becomes unavailable
- What happened: The Redis cluster is down or unreachable.
- State left: Depends entirely on what you put in Redis.
- Detect: Connection errors from the Redis client.
- Recover: Coordination locks fail open: work proceeds, guarded by the database (Part III, Chapter 8). Caches are bypassed, but with a rate limit, so a cold cache doesn't send every read to the database at once.
- No double movement: Only possible if nothing that guards money lives in Redis. If idempotency keys or balance checks live only in Redis, a Redis outage or failover means duplicates. Keep them in PostgreSQL.
10. A cancellation races with processing
- What happened: The customer cancels a
PENDINGpayment at the same moment PayCo's success webhook arrives. - State left: One of them wins the row lock. Either the payment becomes
SUCCESSand the cancellation is refused, or it becomesCANCELLEDand then the success webhook arrives. - Detect: The second case is an illegal transition,
CANCELLED → SUCCESS: the customer cancelled, but money moved. - Recover: Don't apply it and don't drop it. Record an anomaly, then usually refund through the provider, since the customer asked to cancel.
- No double movement: Both paths lock the payment row and use conditional transitions, so exactly one wins and the other sees the result.
Part I's handler recorded late successes only for FAILED payments. This scenario shows CANCELLED needs the same treatment, so the case becomes:
// In ApplyProviderStatus (Part I): any terminal "no money moved" state that receives
// a success is an anomaly, not an update.
case (current == Failed || current == Cancelled) && reported == Success:
_, err := tx.Exec(ctx, `
INSERT INTO payment_anomalies (payment_id, kind, detail)
VALUES ($1, 'LATE_SUCCESS', $2)
ON CONFLICT (payment_id, kind) DO NOTHING`,
paymentID, fmt.Sprintf("provider reported SUCCESS after we marked %s", current))
return errWhat all ten have in common
If you read the “no double movement” lines again, the same few mechanisms keep appearing:
- stable identities for every operation, derived rather than generated on retry;
- the effect and its record committed in one transaction;
- conditional state transitions that let exactly one attempt win;
- unknown outcomes treated as unknown, and resolved forward;
- reconciliation as the final net for anything that slipped through.
None of these is specific to one failure, and that's deliberate. Rather than writing a special recovery path for each incident, you build every step so that “do it again” is always safe, and then most recoveries come down to doing it again.
Checklist
- Payments and payouts stuck in unknown states are found and resolved forward by a scheduled job.
- Timeouts never trigger compensation; only definite failures do.
- Late successes on
FAILEDorCANCELLEDpayments are recorded as anomalies. - When the database is down, nothing is buffered elsewhere; callers and queues retry.
- Nothing that guards money lives only in Redis.
- Each scenario in this chapter has a test and a runbook entry.
Further reading
- Amazon Builders' Library: timeouts, retries and backoff with jitter.
- Google SRE: handling overload and addressing cascading failures.
- AWS SDKs: retry behaviour: standard and adaptive modes.
- Martin Fowler: CircuitBreaker.
- Azure Architecture Center: bulkhead pattern.
- RFC 9110: Retry-After and RFC 6585: 429 Too Many Requests.
- Stripe: rate limits: a provider's view of backoff.
What's next
Every scenario in this chapter started with “detect”. That's the subject of Part VII, Observability and Production Engineering: structured logs and traces that follow one payment across every service, metrics and alerts built around customer impact rather than CPU, profiling Go services before buying bigger machines, and reconciliation, the final safety net that catches whatever every other layer missed.
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.