Skip to main content

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​

RuleWhy
Define states and transitions in one table per aggregateThe table is the specification, the test input and the documentation
Every transition has a guard and a named eventRejects "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 columnConcurrent writers cannot both win
In the same transaction, write the history row and the outbox eventNo status change without a record and an event
Treat external events as claims, not commandsThey 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.

FromEventToGuardSide effects
draftsubmitsubmittedRequired fields and at least one principal presentStart KYC/KYB checks
submittedreview_startedin_reviewScreening results receivedAssign analyst
in_reviewinfo_requestedneeds_informationReason recordedNotify applicant, start a response clock
needs_informationinfo_receivedin_reviewDocuments attachedRe-run affected checks
in_reviewapproveapprovedRequired checks passed, approver differs from submitter (if your policy requires dual control)Create sub-merchant and account, assign fee schedule
submittedauto_declinedeclinedAutomatic screening hit that policy treats as a hard stopReason recorded, adverse-action and notification handling per counsel
in_reviewdeclinedeclinedReason code recordedAdverse-action and notification handling per counsel
draft, needs_informationwithdrawwithdrawnNoneClose open tasks

Once approved, the account has its own status:

FromEventToGuardSide effects
activerestrictrestrictedRestriction type recorded (for example payouts_paused)Payout scheduler skips the account; processing may continue
restrictedliftactiveApprover recorded, cause clearedResume payouts
active, restrictedsuspendsuspendedReason, actorReject new authorizations, keep refunds and dispute handling
suspendedreinstateactiveApprovalNotify platform
active, restricted, suspendedstart_closingclosingReason, actorStop new processing, final payout scheduled, keep the debit account and any reserve
closingterminateterminatedNo 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​

FromEventToGuardSide effects
noneattempt_createdauthorizingIntent in initiated or requires_payment_method, no other attempt in authorizing or unknownSend authorization
authorizingapprovedauthorizedResponse matches the attemptStore auth code, network transaction ID, validity
authorizingdeclineddeclinedNoneStore response code; decline recovery is a separate decision
authorizingtimeoutunknownNoneStart the resolution job
unknownresolved_approved, resolved_declinedauthorized, declinedEvidence from a status query or confirmed outcomeClear the resolution job
unknownreversal_confirmedreversedReversal acknowledged by the processorRecord 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​

FromEventToGuardSide effects
initiatedattempt_startedauthorizingSub-merchant active, idempotency key uniqueCreate attempt
authorizingattempt_authorizedauthorizedAttempt in authorizedKeep identifiers on the authorization
authorizingattempt_failedrequires_payment_methodAttempt declined or reversedNotify caller; a new attempt is allowed
requires_payment_methodattempt_startedauthorizingNo attempt in unknownCreate attempt
authorizedcapture(amount)partially_captured or capturedCumulative captures do not exceed authorized, not expiredCapture row, journal entry
authorizedvalidity_elapsedexpiredClock past validityRelease hold; see Authorization Types
partially_capturedcapture(amount)partially_captured or capturedSame as aboveCapture row, journal entry
partially_capturedcaptures_settledsettledEvery capture settled; the uncaptured remainder has been reversed or has expiredMove funds to available per balance rules; record the remainder release on the authorization
capturedsettlement_confirmedsettledAll captures matched to settlement recordsMove funds to available per balance rules
captured, settled, partially_refundedrefund(amount)partially_refunded or refundedFor each capture, sum of refunds does not exceed capture amountRefund row, journal entry
settled, partially_refundedchargeback_receiveddisputedDispute linked to a captureSave pre_dispute_status, provisional debit
disputeddispute_wonpre_dispute_status (settled or partially_refunded)Dispute won and closed by the processorReverse provisional debit
disputeddispute_lostcharged_backDispute lost and closedFinalize 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.

Aggregate Status Is a Summary

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.

FromEventToGuardSide effects
nonechargeback_receivedopenCapture found via ARN or network transaction IDStore due_by, reason code, amount
openresponse_requestedneeds_responsedue_by in the futureNotify platform, create evidence record
needs_responseevidence_submittedunder_reviewEvidence complete, before due_bySubmit via processor, lock evidence
needs_responseacceptacceptedAuthorized actorFinalize debit
needs_responsedeadline_elapsedlostdue_by passedFinalize debit
under_reviewoutcome_wonwonNetwork or processor outcomeReverse provisional debit
under_reviewoutcome_lostlostNetwork or processor outcomeFinalize debit
noneinquiry_receivedinquiryRetrieval request or inquiry linked to a captureStore due_by, create evidence record
inquiryescalatedopenChargeback received for the same caseStore new due_by, reason code, amount
inquiryresolvedclosedProcessor closes the inquiryNone
under_reviewissuer_escalatedpre_arbitrationPre-arbitration notification after the merchant's responseNew due_by, reopen response task
pre_arbitrationescalatedarbitrationNotificationEscalate to risk team
pre_arbitration, arbitrationoutcome_won, outcome_lostwon, lostNetwork or processor outcomeReverse 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.

FromEventToGuardSide effects
nonecreatescheduledAccount not restricted, destination verified, balance covers amountLedger posts Dr sub-merchant payable (available) / Cr payout clearing (in transit)
scheduledsubmitpendingStill releasableWrite an outbox row that submits to the rail (no ledger entry)
scheduled, pendingcancelcanceledNot yet released to the railReversing ledger entries
pendingacceptedin_transitRail acknowledgementStore trace reference
pending, in_transitrejectedfailedRail errorReversing ledger entries, notify, consider restriction
in_transitconfirmedpaidBank or rail confirmationConfirm the clearing entry
paidreturn_receivedreturnedMatches payout by trace referenceRe-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:

  1. Deduplicate by the external event ID, stored with the history row, before doing anything.
  2. 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_stale with the reason, so the audit trail shows it arrived.
  3. 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.
  4. 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.
  5. 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.
  6. 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 (paid to returned).
  • 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.

References​

Share: