Lesson 6 of 9 · 26m
Payment State Machines and Recovery Jobs
Normalize provider events into explicit local states, prevent illegal transitions, and build reconciliation workers for abandoned or interrupted payments.
The most dangerous payment state is the one nobody designed. It appears when a customer closes a bank redirect, when webhook delivery fails for six hours, or when capture succeeded but your worker crashed. If your system has only paid and unpaid, production will invent five more states in the dark. Make the state machine explicit before production does it for you.
Normalize provider detail into merchant states
Provider states are important evidence, but your application needs a smaller operational vocabulary:
draft local order exists, no payment attempt yet
payment_pending provider object created or customer action in progress
paid money captured or payment finally confirmed
payment_failed attempt failed terminally, order may be retryable
expired payment attempt abandoned past deadline
refund_pending refund accepted or processing
refunded money fully returned
partially_refunded some amount returned
disputed chargeback or PayPal dispute activeStore both the normalized state and the raw provider status. Do not make support or business logic decode every Stripe and PayPal status string forever.
Explicit transitions catch corruption
A transition table is boring in the best way:
ALLOWED = {
"draft": {"payment_pending", "expired"},
"payment_pending": {"paid", "payment_failed", "expired"},
"payment_failed": {"payment_pending", "expired"},
"paid": {"refund_pending", "disputed"},
"refund_pending": {"refunded", "partially_refunded", "paid"},
}If a webhook tries to move refunded back to payment_pending, that is not a normal customer journey. It is reordering, bad mapping, or operator error. Log and quarantine it rather than blindly applying the update.
Recovery jobs close the asynchronous gap
Webhook delivery is reliable enough to depend on, but not magical. Build periodic jobs that find stuck orders and query provider truth:
payment_pending older than 15 minutes -> fetch provider object
paid but unfulfilled -> enqueue fulfillment
refund_pending older than provider SLA -> fetch refund state
draft with provider object attached -> inspect orphan attemptThis is not redundant engineering. It is how you recover from deploys, queue outages, webhook endpoint misconfiguration, expired secrets, and customer abandonment.
Timeouts need product decisions
An abandoned payment attempt should not lock inventory forever, but canceling too early can race a customer who is completing authentication. Encode the rules:
redirect methods: allow longer pending windows
cards with immediate confirmation: shorter windows
inventory reservation: explicit expiration timestamp
subscriptions: provider retry/dunning behavior may supersede local expiryThe state machine is where product, finance, and engineering meet. Engineering alone should not improvise these rules during an incident.
Keep a transition audit trail
A single mutable status column tells you where you ended, not how you got there. Store transitions:
CREATE TABLE payment_state_transitions (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL,
from_state TEXT,
to_state TEXT NOT NULL,
reason TEXT NOT NULL,
provider_event_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);During disputes, refunds, or customer support escalations, that table turns guesswork into evidence.
Field notes
- Never let old asynchronous events overwrite newer terminal states without a comparison rule.
- Expire attempts, not necessarily the underlying customer order; users often need a clean retry path.
- A provider object can exist without a local row after partial failure; reconciliation must search both directions.
- Avoid distributed state machines spread across frontend, backend, and provider dashboard. Your backend should own transitions.
- Alerts should fire on stuck-state volume, not every individual abandoned checkout.
Was this lesson helpful?