← Lessons

quiz vs the machine

Gold1380

System Design

The Payment State Machine

Modeling a payment as explicit states and allowed transitions to prevent illegal moves.

5 min read · core · beat Gold to climb

Why model states

A payment passes through stages such as created, authorized, captured, failed, and refunded. Modeling these as a state machine makes the allowed paths explicit and blocks impossible jumps like capturing a failed payment.

States and transitions

  • Each state has a defined set of valid next states.
  • A transition is triggered by an event such as an authorization response or a capture call.
  • Reaching a terminal state like refunded or failed means no further transitions are allowed.

Guarding the machine

  • Store the current state and only apply a transition if it is allowed from that state.
  • Make transitions atomic so two events cannot both move the payment.
  • Record each transition in an audit log with the event that caused it.

Why it helps

  • It turns scattered conditional checks into one declarative table.
  • It makes reconciliation easier because every payment is in a known state.

Key idea

A payment state machine encodes the legal lifecycle of a payment, rejecting invalid transitions and giving every payment a single well defined status.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a state machine reject?

2. What characterizes a terminal state?