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.