Payment State Machines
Last Updated: 2026-12-01 Status: Complete
A payment state machine is an explicit list of states, allowed transitions and the conditions that guard them. Payment platforms run on four of them (onboarding application, payment, dispute, payout), and most production incidents in this area come from a status column that anyone could set to anything. This page gives you transition tables for all four, then the code to enforce them in NestJS, and a way to cope with events that arrive late or out of order.
Quick Reference
| Rule | Why |
|---|---|
| Define states and transitions in one table per aggregate | The table is the specification, the test input and the documentation |
| Every transition has a guard and a named event | Rejects "set status = captured" shortcuts |
| Terminal states have no outgoing transitions (except documented exceptions) | Money records must not reopen silently |
Apply a transition with a conditional update (WHERE status = :from) or a version column | Concurrent writers cannot both win |
| In the same transaction, write the history row and the outbox event | No status change without a record and an event |
| Treat external events as claims, not commands | They can be late, duplicated or contradictory |
Why Use Explicit State Machines?
A state machine turns "what can happen next" from tribal knowledge into data. For each aggregate you define:
- States and which are terminal.
- Events (a named cause:
capture_requested,processor_confirmed,chargeback_received). - Transitions: from state, event, to state.
- Guards: conditions that must hold (captured amount does not exceed authorized amount; authorization not expired).
- Side effects: what the transition triggers (ledger entry, event, notification).
Each applied transition writes one append-only row in a status history table and one event through the transactional outbox, so downstream services (ledger, webhooks, reporting) learn about it exactly when the database does. The delivery mechanics are in Event-Driven Architecture. An invalid transition is rejected and logged, never coerced.
Designing the Onboarding Application and Account Status Machines
Keep two machines: the application (a request to be onboarded, which ends) and the account (the live sub-merchant, which continues). Mixing them into one status makes "approved" ambiguous. The business context is in Merchant Lifecycle.
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| draft | submit | submitted | Required fields and at least one principal present | Start KYC/KYB checks |
| submitted | review_started | in_review | Screening results received | Assign analyst |
| in_review | info_requested | needs_information | Reason recorded | Notify applicant, start a response clock |
| needs_information | info_received | in_review | Documents attached | Re-run affected checks |
| in_review | approve | approved | Required checks passed, approver differs from submitter (if your policy requires dual control) | Create sub-merchant and account, assign fee schedule |
| submitted | auto_decline | declined | Automatic screening hit that policy treats as a hard stop | Reason recorded, adverse-action and notification handling per counsel |
| in_review | decline | declined | Reason code recorded | Adverse-action and notification handling per counsel |
| draft, needs_information | withdraw | withdrawn | None | Close open tasks |
Once approved, the account has its own status:
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| active | restrict | restricted | Restriction type recorded (for example payouts_paused) | Payout scheduler skips the account; processing may continue |
| restricted | lift | active | Approver recorded, cause cleared | Resume payouts |
| active, restricted | suspend | suspended | Reason, actor | Reject new authorizations, keep refunds and dispute handling |
| suspended | reinstate | active | Approval | Notify platform |
| active, restricted, suspended | start_closing | closing | Reason, actor | Stop new processing, final payout scheduled, keep the debit account and any reserve |
| closing | terminate | terminated | No open disputes, no in-flight payouts, return window elapsed, no negative balance (or explicit, recorded override) | Close bank accounts effective-dated, release reserve per policy |
closing is the wind-down: refunds and dispute handling continue, and the debit account and reserve stay in place until the cases and return windows close. Jumping straight to terminated strands chargebacks and returns with nothing to recover from.
Model restricted as a status plus a set of typed restrictions (payouts paused, volume cap) so it does not need a new status for every combination. Triggers for these transitions come from Ongoing Monitoring.
Designing the Payment State Machine
The payment aggregate spans authorization, capture, refund, dispute and settlement. It includes an explicit unknown state for a timed-out authorization, as in Idempotency in Payments: when no response arrives, nobody knows whether the issuer approved, and the platform must resolve that by status query (where one exists) or reversal, never by blindly creating a new payment. The authorization on its own is modeled in How Should I Model an Authorization State Machine?; this machine is the aggregate above it.
Because a customer can retry after a decline, split the model in two: an attempt machine (one try with a payment method) and an intent status (the aggregate). A declined or reversed attempt is terminal for the attempt, but not for the intent, which goes to requires_payment_method and returns to authorizing when a new attempt starts.
Attempt Machine
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| none | attempt_created | authorizing | Intent in initiated or requires_payment_method, no other attempt in authorizing or unknown | Send authorization |
| authorizing | approved | authorized | Response matches the attempt | Store auth code, network transaction ID, validity |
| authorizing | declined | declined | None | Store response code; decline recovery is a separate decision |
| authorizing | timeout | unknown | None | Start the resolution job |
| unknown | resolved_approved, resolved_declined | authorized, declined | Evidence from a status query or confirmed outcome | Clear the resolution job |
| unknown | reversal_confirmed | reversed | Reversal acknowledged by the processor | Record reversal reference |
Resolving unknown. Against an ISO 8583 host there is no status inquiry: resolve with a reversal (0400) for the original attempt. A status query exists only where the processor or gateway API offers one. If the reversal is not confirmed, retry it to a limit you set and then escalate to an operator; do not mark the attempt reversed without confirmation, and do not start a new attempt while one is unknown.
Intent Machine
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| initiated | attempt_started | authorizing | Sub-merchant active, idempotency key unique | Create attempt |
| authorizing | attempt_authorized | authorized | Attempt in authorized | Keep identifiers on the authorization |
| authorizing | attempt_failed | requires_payment_method | Attempt declined or reversed | Notify caller; a new attempt is allowed |
| requires_payment_method | attempt_started | authorizing | No attempt in unknown | Create attempt |
| authorized | capture(amount) | partially_captured or captured | Cumulative captures do not exceed authorized, not expired | Capture row, journal entry |
| authorized | validity_elapsed | expired | Clock past validity | Release hold; see Authorization Types |
| partially_captured | capture(amount) | partially_captured or captured | Same as above | Capture row, journal entry |
| partially_captured | captures_settled | settled | Every capture settled; the uncaptured remainder has been reversed or has expired | Move funds to available per balance rules; record the remainder release on the authorization |
| captured | settlement_confirmed | settled | All captures matched to settlement records | Move funds to available per balance rules |
| captured, settled, partially_refunded | refund(amount) | partially_refunded or refunded | For each capture, sum of refunds does not exceed capture amount | Refund row, journal entry |
| settled, partially_refunded | chargeback_received | disputed | Dispute linked to a capture | Save pre_dispute_status, provisional debit |
| disputed | dispute_won | pre_dispute_status (settled or partially_refunded) | Dispute won and closed by the processor | Reverse provisional debit |
| disputed | dispute_lost | charged_back | Dispute lost and closed | Finalize debit |
settled means every capture has settled. Refunds and disputes apply per capture, so keep the invariant sum(refunds on a capture) <= capture.amount_minor on the capture, not only on the intent. A refund before settlement is allowed (from captured): the capture may not have cleared yet, and whether that becomes a void or a credit is decided by clearing status, see Authorization Types. While any dispute is open the intent shows disputed; with several disputes it returns to pre_dispute_status only when none is open.
The truth is in the child rows: attempts, captures, refunds and disputes. The status summarizes them and the guards compute from them. Releasing the uncaptured remainder of a partially captured authorization (a partial reversal, or letting it expire) is recorded on the authorization, as in Module 4's authorization machine, not as a terminal intent status: once a capture exists, refunds and disputes can still follow, so the intent moves on to settled instead of ending at reversed or expired.
Designing the Dispute State Machine
A dispute (see Chargeback Lifecycle) is the third machine. Its states mirror the network case, but your due_by deadline is read from the processor or network notification for each dispute, never hardcoded, because it varies by network, reason and stage.
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| none | chargeback_received | open | Capture found via ARN or network transaction ID | Store due_by, reason code, amount |
| open | response_requested | needs_response | due_by in the future | Notify platform, create evidence record |
| needs_response | evidence_submitted | under_review | Evidence complete, before due_by | Submit via processor, lock evidence |
| needs_response | accept | accepted | Authorized actor | Finalize debit |
| needs_response | deadline_elapsed | lost | due_by passed | Finalize debit |
| under_review | outcome_won | won | Network or processor outcome | Reverse provisional debit |
| under_review | outcome_lost | lost | Network or processor outcome | Finalize debit |
| none | inquiry_received | inquiry | Retrieval request or inquiry linked to a capture | Store due_by, create evidence record |
| inquiry | escalated | open | Chargeback received for the same case | Store new due_by, reason code, amount |
| inquiry | resolved | closed | Processor closes the inquiry | None |
| under_review | issuer_escalated | pre_arbitration | Pre-arbitration notification after the merchant's response | New due_by, reopen response task |
| pre_arbitration | escalated | arbitration | Notification | Escalate to risk team |
| pre_arbitration, arbitration | outcome_won, outcome_lost | won, lost | Network or processor outcome | Reverse or finalize the debit |
Pre-arbitration is filed by the issuer after the merchant's response (representment). In some networks' allocation flows the acquirer's own challenge is also filed as pre-arbitration, so confirm the filing party with your processor; the network detail is on Chargeback Lifecycle. Treat won and lost as final only when the processor closes the case; a result that is still inside the issuer's escalation window can be reopened, so keep the due_by and the processor's status on the dispute row.
Financial impact is recorded separately. Create ledger movements for each financial event: a provisional debit when the chargeback arrives (and a fee if applicable), a reversal if the merchant wins, nothing further if the debit is final. Keeping money in the ledger and lifecycle in the state machine means a status bug cannot create or destroy funds. The journal entries are covered in Double-Entry Ledger.
Designing the Payout State Machine
A payout moves funds to the sub-merchant's bank. Rails, schedules and amounts are in Payouts; here is only the lifecycle.
| From | Event | To | Guard | Side effects |
|---|---|---|---|---|
| none | create | scheduled | Account not restricted, destination verified, balance covers amount | Ledger posts Dr sub-merchant payable (available) / Cr payout clearing (in transit) |
| scheduled | submit | pending | Still releasable | Write an outbox row that submits to the rail (no ledger entry) |
| scheduled, pending | cancel | canceled | Not yet released to the rail | Reversing ledger entries |
| pending | accepted | in_transit | Rail acknowledgement | Store trace reference |
| pending, in_transit | rejected | failed | Rail error | Reversing ledger entries, notify, consider restriction |
| in_transit | confirmed | paid | Bank or rail confirmation | Confirm the clearing entry |
| paid | return_received | returned | Matches payout by trace reference | Re-credit the returned amount to the sub-merchant balance, block the destination, pause payouts until a new account is verified |
paid is not final. An ACH return can arrive after a payout looked successful (most returns: Two banking days from the settlement date (unauthorized consumer debits allow longer); other return types can come later, so do not assume a fixed cutoff), so returned must be reachable from paid. A returned payout is not a negative balance: the funds go back to the merchant's balance and the destination is blocked. Recovery applies only if that balance has since been spent. Return handling is covered in Payouts and ACH and Nacha.
How Do You Enforce Transitions in Code?
Represent the machine as data, with explicit enums and a map from state to the events allowed from it.
export enum IntentStatus {
Initiated = 'initiated', Authorizing = 'authorizing',
RequiresPaymentMethod = 'requires_payment_method',
Authorized = 'authorized', PartiallyCaptured = 'partially_captured',
Captured = 'captured', Settled = 'settled',
PartiallyRefunded = 'partially_refunded', Refunded = 'refunded',
Voided = 'voided', Reversed = 'reversed', Expired = 'expired',
Disputed = 'disputed', ChargedBack = 'charged_back',
}
export enum IntentEvent {
AttemptStarted = 'attempt_started', AttemptAuthorized = 'attempt_authorized',
AttemptFailed = 'attempt_failed', Capture = 'capture',
CapturesSettled = 'captures_settled', Refund = 'refund',
ChargebackReceived = 'chargeback_received',
// ...remaining events
}
type Transitions = Record<
IntentStatus,
Partial<Record<IntentEvent, IntentStatus[]>>
>;
export const INTENT_TRANSITIONS = {
[IntentStatus.Initiated]: {
[IntentEvent.AttemptStarted]: [IntentStatus.Authorizing],
},
[IntentStatus.Authorizing]: {
[IntentEvent.AttemptAuthorized]: [IntentStatus.Authorized],
[IntentEvent.AttemptFailed]: [IntentStatus.RequiresPaymentMethod],
},
[IntentStatus.RequiresPaymentMethod]: {
[IntentEvent.AttemptStarted]: [IntentStatus.Authorizing],
},
[IntentStatus.Authorized]: {
[IntentEvent.Capture]: [IntentStatus.PartiallyCaptured, IntentStatus.Captured],
},
// ...one entry per status (satisfies fails the build if one is missing);
// terminal statuses map to {}
} satisfies Partial<Transitions>;
The attempt, dispute and payout machines follow the same shape. Use satisfies Transitions (without Partial) once every entry is written, so the compiler rejects a status with no entry.
Some events have more than one possible target (a capture is partial or full); the service computes the target from the guard and checks it is in the allowed list. The service applies the transition atomically:
@Injectable()
export class PaymentTransitionService {
constructor(private readonly dataSource: DataSource) {}
async apply(
intentId: string, event: IntentEvent, to: IntentStatus,
cause: { actor: string; externalEventId?: string },
): Promise<void> {
await this.dataSource.transaction(async (manager) => {
if (cause.externalEventId) {
// Duplicate delivery: a unique index on (intent_id, external_event_id)
// in the history table is the backstop for races.
const seen = await manager.exists(PaymentStatusHistory, {
where: { intentId, externalEventId: cause.externalEventId },
});
if (seen) return;
}
const intent = await manager.findOneOrFail(PaymentIntent, {
where: { id: intentId },
});
const table: Partial<Transitions> = INTENT_TRANSITIONS;
const allowed = table[intent.status]?.[event] ?? [];
if (!allowed.includes(to)) {
throw new ConflictException(
`Invalid transition ${intent.status} -> ${to} on ${event}`,
);
}
// Conditional update: only wins if nobody changed the row meanwhile
const result = await manager.update(
PaymentIntent,
{ id: intentId, status: intent.status, version: intent.version },
{ status: to, version: intent.version + 1 },
);
if (result.affected !== 1) throw new ConflictException('Concurrent update');
await manager.insert(PaymentStatusHistory, {
intentId, fromStatus: intent.status, toStatus: to, event, ...cause,
});
await manager.insert(OutboxEvent, {
aggregateId: intentId, type: `payment.${to}`,
payload: { intentId, from: intent.status, to },
});
});
}
}
Guards (amount limits, expiry, sub-merchant state) run before apply, inside the same transaction when they read rows that could change. The status plus version condition is optimistic locking; the equivalent in SQL is UPDATE ... WHERE id = :id AND status = :from, checking the affected row count. Callers decide whether a ConflictException is retried (a concurrent writer) or surfaced (an invalid transition).
A retry must not repeat the business action. The conditional update protects the status, not the amounts. Two concurrent partial captures can both pass a status check and each insert a row, so a lost race that "re-reads and tries again" can capture twice. Give every capture and refund request a request_key, enforce UNIQUE (intent_id, request_key) on the child table, and have retries resend the same key: the second insert fails and the caller returns the first result. Also lock the intent row (SELECT ... FOR UPDATE) while checking cumulative amounts. See Payment Platform Data Model for the DDL.
How Do You Handle Late or Out-of-Order External Events?
Processors and networks send webhooks and files that can be delayed, repeated or reordered (see Webhooks and Event-Driven Architecture). A captured notification arriving after you recorded refunded is not an error in the processor, it is a reordering. Rules:
- Deduplicate by the external event ID, stored with the history row, before doing anything.
- Compare to the current state. If applying the event would move backwards (the target is earlier in the lifecycle than the current state), do not apply it. Record it in the history as
ignored_stalewith the reason, so the audit trail shows it arrived. - Ask the source of truth when an event contradicts local state: fetch the current object from the processor and reconcile to that, rather than trusting arrival order.
- Derive from child rows. Aggregate status can be recomputed from captures, refunds and disputes, so a stale event cannot corrupt facts, only delay the summary.
- Park unmatched events (for example a dispute whose capture you cannot find yet) in a retry table with a limit and an alert, not drop them.
- Money-affecting events always go through the ledger idempotently, regardless of status handling.
Unknown states need an owner: a job that resolves each unknown attempt by status query (only where the processor or gateway API offers one) or by reversal, retries an unconfirmed reversal to a limit, then escalates to an operator.
How Do You Test State Machines Exhaustively?
Because the machine is data, the tests can be generated from it:
- Transition matrix: for every (state, event) pair, assert it is either in the table (and reaches the listed target) or rejected. This catches a new state with no entry.
- Terminal states: assert no event leaves them, except the documented exceptions (
paidtoreturned). - Property tests: random event sequences never reach an unlisted state and never violate invariants (refunds do not exceed captures).
- Concurrency: two simultaneous transitions from the same state, exactly one succeeds.
- Replay: applying the same external event twice changes nothing.
See Testing Payment Systems for the wider approach, including simulating disputes.
Related Topics
- Payment Platform Data Model — the records these machines govern
- Event-Driven Architecture — outbox, ordering and idempotent consumers
- Authorization Types — the authorization-level state machine
- Chargeback Lifecycle — network stages and deadlines
- Check your understanding: Data Modeling Quiz
References
- Idempotency in Payments — Payments Mastery, 2026 (payment state machine with an explicit Unknown state)
- Transactional outbox pattern — Chris Richardson, microservices.io
- Originator Essentials (RMAG) — Nacha, 2024 (ACH return timeframes)