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

Resilience and failure recovery

Why a retry loop can turn a twenty-minute outage into a two-hour one, how to recover from a backlog without knocking the dependency over again, and what to do in each of the ten failures every payment system meets.

Chapters 15–1638 min readPublished 23 Nov 2026

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.

An uncontrolled recovery versus a controlled ramp-upLeft: after an outage, every worker retries at once, load spikes far above capacity, the dependency falls over again, and the cycle repeats. Right: after the same outage, load increases in small steps and settles just below capacity while the backlog drains. every worker retries at oncecontrolled ramp-upload on PayCotimeload on PayCotimecapacitycapacityoutageoutagespike, fall over, againdrains steadily
The outage isn’t the worst part; the recovery is. On the left, a backlog that built up for twenty minutes arrives in twenty seconds, and the dependency goes down again. On the right, the same backlog is let through in steps the dependency can absorb.

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).

Which failures to retry
FailureRetry?Why
Timeout, connection resetYes, with the same idempotency keyOutcome unknown; the key makes a repeat harmless
HTTP 5xxYesUsually temporary
HTTP 429 Too Many RequestsYes, slowerYou're being rate-limited; respect Retry-After if present
PostgreSQL 40001 serialization failure, 40P01 deadlockYesThe database is asking you to try again
PostgreSQL 55P03 lock not available, 57014 query cancelled (timeouts)Yes, with backoffContention or overload; waiting helps
PostgreSQL 53300 too many connectionsYes, with backoff, and fix the budgetSee Part V
HTTP 400, 401, 403, 404, 409, 422NoThe request is wrong; it will fail the same way
Card declined, insufficient fundsNoA 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).

retry/classify.goGo
// 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).
When six clients retry under three strategiesWith a fixed one-second delay, all six clients retry at exactly the same moments. With exponential backoff, they still retry together, just less often. With exponential backoff plus jitter, the retries are spread out over time. fixed 1 sexponentialexponential + jittertime after the failure →everyone retries togetherretries spread out
Backoff alone doesn’t break up a crowd; randomness does. Clients that failed together and back off by the same formula will retry together, in ever larger waves. Adding a random component spreads them out.

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.

An illustrative backoff schedule
AttemptExponential limit (base 200 ms, cap 30 s)Full-jitter wait
1200 msrandom 0–200 ms
2400 msrandom 0–400 ms
3800 msrandom 0–800 ms
41.6 srandom 0–1.6 s
53.2 srandom 0–3.2 s
66.4 srandom 0–6.4 s
825.6 srandom 0–25.6 s
9+30 s (cap)random 0–30 s
retry/backoff.goGo
// 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.

retry/do.goGo
// 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:

consumer/defer.goGo
// 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.

Retries multiplying across layersA mobile app, an API and a payment service each try three times, so one tap can cause up to 27 calls to PayCo. The fix is to retry in one layer and fail fast in the rest. mobile app× 3 triesAPI× 3 triespayment service× 3 tries (SDK)PayCo1 tap → up to 27 calls to PayCoretry inONE layerfail fast in the rest
Retries multiply, they don’t add. Three layers each making three attempts means 3 × 3 × 3 = 27 calls for one customer action, all arriving at a dependency that is already struggling.

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).

The circuit breaker state machineCLOSED: calls go through. After too many failures it moves to OPEN, where calls fail fast without being made. After a cool-down it moves to HALF-OPEN and lets a few calls try. If they succeed it returns to CLOSED; if one fails it goes back to OPEN. CLOSEDcalls go throughOPENfail fast, no callsHALF-OPENlet a few calls trytoo many failuresafter a cool-downtrial calls succeeda trial fails
A breaker stops you hammering a dependency that is already down. While it’s open, work fails fast and goes back on the queue instead of tying up workers and connections waiting on timeouts.
resilience/breaker.goGo
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):

resilience/limit.goGo
// 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).

Bulkheads: separate worker pools per dependencyLeft: one shared pool of 12 workers, all stuck waiting on PayCo, so ledger work and emails stop too. Right: separate pools for PayCo, the ledger and email; PayCo’s four workers are stuck but the others keep working. one shared worker poola pool per dependencyall 12 stuck waiting on PayCocredits and emails stop tooPayColedgeremailPayCo’s 4 are stuck; the rest keep working
A slow dependency fills every slot it’s allowed to. Bulkheads limit how many it’s allowed: “isolate the elements of an application into pools so that if one element fails, the others continue to function”.

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:

  1. Detect recovery with a few trial calls (the breaker's half-open state), not with every worker at once.
  2. Start with low concurrency, well below normal.
  3. 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.
  4. 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.
Stepping concurrency back up after a recoveryAfter the circuit breaker goes half-open, worker concurrency starts low and rises by one step each healthy minute. When latency rises it is halved, then it climbs again and levels off just below the dependency’s limit. worker concurrencyminutes after recoverydatabase / PayCo limitbreaker half-openlatency rose: halve+1 each healthy minute
Increase slowly, back off quickly. Adding a little capacity after every healthy interval and halving it at the first sign of strain finds the dependency’s real limit without overshooting it. Steps are illustrative.
resilience/aimd.goGo
// 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:

  1. What happened?
  2. What state might the system be left in?
  3. How do we detect it?
  4. How do we recover safely?
  5. How do we make sure money doesn't move twice?
Where the ten failure scenarios happenA pipeline from app to API to PayCo to webhook to SQS and worker to the database, with numbered markers one to ten placed where each failure scenario in Chapter 16 occurs. appAPIPayCowebhookSQS → workerDB12345678910numbers match the scenarios in Chapter 16
Every hop is a place where one side knows something the other doesn’t. Each numbered marker is one of the scenarios below: what happened, what state it leaves, how to notice, and how to recover without moving money 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:

Choosing forward recovery or compensationWhen a step didn’t finish, ask whether we know it failed. If the outcome is unknown, recover forward by retrying with the same key or asking the provider. If it definitely failed, compensate by reversing earlier steps with new records. A step didn’t finishDo we know it failed?no, unknownyes, definitelyforward recoveryretry / ask the providercompensatereverse with a new recordsame key, same operationonly after a definite “no”
Compensating an unknown outcome is how money gets paid twice. If a payout might still arrive, giving the money back to the wallet means the customer can end up with both.

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 PROCESSING past 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.
recovery/unknown.goGo
// 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 200 was lost or late. PayCo sent it again.
  • State left: Correct, after the first delivery.
  • Detect: The provider_events insert 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: PROCESSING indefinitely. 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 DeleteMessage failed 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 PENDING with 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_INITIATED past 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 to PAYOUT_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_RESERVED with no payout sent.
  • Detect: The sweeper's stuck-workflow query; the message being redelivered after its visibility timeout.
  • Recover: Forward. Advance resumes 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 503 with Retry-After. Webhook ingestion returns 5xx so 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 PENDING payment at the same moment PayCo's success webhook arrives.
  • State left: One of them wins the row lock. Either the payment becomes SUCCESS and the cancellation is refused, or it becomes CANCELLED and 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:

payments/events.go (updated case, sketch)Go
// 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 err

What 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 FAILED or CANCELLED payments 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

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.

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.