Sub topic 7
Modeling payments as a state machine
This chapter assumes you know relational database basics, including transactions, and can read short Python and SQL snippets. It also assumes you know the authorization, capture, and settlement steps from the earlier chapters.
Why a state machine
A payment is a long-lived record that changes over time. A state machine names every state the payment can be in and lists which moves between states are legal. Without one, bugs and duplicate messages can push a payment into an impossible condition, such as capturing a voided payment.
Each payment has exactly one state at a time. Each event, such as "PSP approved" or "merchant requested void", asks to move it to a new state. The rules decide whether the move is allowed.
The states voided, failed, and refunded are terminal. No transition leaves them.
Encoding the rules
Put the allowed transitions in one table. Illegal moves then fail loudly instead of silently corrupting state.
ALLOWED_TRANSITIONS = {
"created": {"authorized", "failed"},
"authorized": {"captured", "voided", "failed"},
"captured": {"refunded"},
"voided": set(),
"failed": set(),
"refunded": set(),
}
def transition(current: str, target: str) -> str:
if target not in ALLOWED_TRANSITIONS.get(current, set()):
raise ValueError(f"illegal transition {current} -> {target}")
return target
print(transition("created", "authorized"))Calling transition("voided", "captured") raises ValueError. The caller must handle that error. It should not swallow it.
Enforcing it in the database
A check in application code is not enough. Two workers can read the same row, both see authorized, and both try to move it. Make the database apply the change only if the state is still what you expect:
UPDATE payments
SET status = 'captured'
WHERE id = :payment_id
AND status = 'authorized';If the update affects zero rows, another process changed the payment first. Reload it and decide what to do. This is a compare-and-set, and it works without holding locks across network calls.
Common errors
- Treating a repeated event as an error. PSPs resend webhooks. If a payment is already
capturedand a second "captured" event arrives, acknowledge it and change nothing. Only reject moves that are actually illegal. - Skipping the state check on the write. Validating in Python but updating with
WHERE id = ...alone leaves a race. - Adding an
unknownstate too late. After a timeout you may not know whether the PSP approved the charge. Record that uncertainty, for example as a pending state, and resolve it by querying the PSP. Do not guessfailed. - Losing history. Overwriting
statushides how the payment got there. Store each transition as a row with a timestamp and its cause.
Exercise
Two workers both read a payment in the authorized state. One runs a capture and the other runs a void. Which database technique ensures only one of them succeeds, and what does the loser see?
Show answer
Use a conditional update such as UPDATE ... SET status = :target WHERE id = :id AND status = 'authorized'. The first update changes one row. The second affects zero rows because the status is no longer authorized, so it knows it lost the race and must reload the payment before deciding what to do.