Sub topic 7
Modeling payments as a state machine
A payment changes over time. It is created, authorized, captured, and sometimes refunded or voided. A state machine makes those changes explicit. This chapter shows how to model a payment as one, how to enforce the allowed transitions safely under concurrency, and which edge cases cause real bugs.
This chapter assumes you know basic HTTP APIs, relational transactions and unique constraints, and short Python and SQL snippets. It also builds on the earlier chapters on authorization, capture, and idempotency.
Why a state machine
A payment record with a free-form status string invites bugs. Any code path can write any value. A retry, a late webhook, or a bad deploy can then move a payment into a state that makes no business sense, such as capturing a payment that was already voided.
A state machine fixes this with three pieces:
- A finite set of states, such as
createdorcaptured. - A set of transitions, which are the only allowed moves between states.
- A rule that every status change goes through one function that checks the transition.
Illegal moves then fail loudly instead of silently corrupting data.
The states
This chapter uses six states.
| State | Meaning | Terminal? |
|---|---|---|
| `created` | The payment exists and the request was accepted. No money is held. | No |
| `authorized` | The issuer approved the payment and holds the funds. | No |
| `captured` | The merchant claimed the held funds. Settlement follows. | No |
| `voided` | The authorization was cancelled before capture. | Yes |
| `failed` | The payment could not be authorized or completed. | Yes |
| `refunded` | Money from a captured payment was returned. | Yes |
A terminal state has no outgoing transitions. Once a payment reaches one, its status never changes again. This is a useful guarantee. Reporting, reconciliation, and webhook logic can rely on it.
Real systems often add more states, such as pending for asynchronous methods, partially_refunded, or disputed. Add a state only when the business needs to act differently in it. Each new state multiplies the transitions you must reason about.
Enforcing transitions in code
Put the allowed transitions in one table. The check lives in one function.
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 targetThe table is data, so you can review it, test it, and print it as documentation. An unknown current state returns an empty set, so it also fails.
A quick check shows the behavior:
print(transition("created", "authorized")) # authorized
try:
transition("voided", "captured")
except ValueError as error:
print(error) # illegal transition voided -> capturedThe check alone is not enough
The Python function validates a transition in memory. It does not stop two servers from acting on the same payment at the same time. Consider this sequence:
- Request A reads the payment as
authorized. - Request B reads the same payment as
authorized. - A validates
authorized -> capturedand writescaptured. - B validates
authorized -> voidedand writesvoided.
Both checks passed against stale data. The payment ends as voided even though capture was already sent to the PSP. This is a lost update.
The fix is to make the database enforce the precondition. Use a conditional update that only succeeds if the status is still what you expected. This is called optimistic concurrency control.
UPDATE payments
SET status = 'captured'
WHERE id = :payment_id
AND status = 'authorized'
RETURNING id;If the statement returns no row, another request changed the payment first. The caller must reload the payment and decide what to do. The check and the write happen atomically in one statement, so there is no gap for a second request to slip into.
An alternative is pessimistic locking with SELECT ... FOR UPDATE, which blocks other writers until your transaction ends. It is simpler to reason about but holds locks while you work. Never hold a row lock across a call to an external PSP, because a slow PSP would then block every other request for that payment.
Putting the check and the write together
A safe update combines both ideas. It validates the transition in code and then writes with the expected current status.
def apply_transition(conn, payment_id, expected, target):
transition(expected, target) # raises on an illegal move
row = conn.execute(
"UPDATE payments SET status = %s "
"WHERE id = %s AND status = %s RETURNING id",
(target, payment_id, expected),
).fetchone()
if row is None:
raise RuntimeError("payment changed concurrently, reload and retry")The code check catches programming errors early. The SQL condition catches races.
Recording history
The status column shows only where the payment is now. To answer "how did it get here?", write each transition as an append-only row in the same transaction.
CREATE TABLE payment_events (
id BIGSERIAL PRIMARY KEY,
payment_id UUID NOT NULL REFERENCES payments (id),
from_status TEXT NOT NULL,
to_status TEXT NOT NULL,
reason TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);Update the status and insert the event in one transaction. If either fails, both roll back. This history helps with debugging, audits, and disputes. It also feeds the outbox pattern covered in a later chapter.
Handling the hard cases
Duplicate and late messages
A retry or a repeated webhook may ask for a transition that already happened. Capturing a payment that is already captured is not an error from the caller's view. Treat a request whose target equals the current state as a successful no-op and return the existing result. Reject only moves that conflict with the current state. This keeps retries safe and works together with idempotency keys.
Out-of-order events
Asynchronous PSP events can arrive in the wrong order. You may receive "captured" before "authorized". Do not apply events blindly. Compare each event with the current state, ignore events that describe an earlier state, and park or re-query when an event skips ahead.
Unknown outcomes
A timeout during authorization leaves you not knowing whether the PSP approved. Do not move to failed on a timeout. A later authorization could still succeed and hold the customer's money. Many designs add an intermediate state such as pending and resolve it by querying the PSP or waiting for a webhook. Only a confirmed result should move the payment to a terminal state.
Partial amounts
Partial captures and partial refunds do not fit a single status value well. Keep the status coarse and track amounts in separate fields, such as captured_minor and refunded_minor. Validate that refunded_minor never exceeds captured_minor.
Testing the machine
The table makes exhaustive tests cheap. Test every pair of states, not only the paths you expect.
STATES = list(ALLOWED_TRANSITIONS)
def test_all_pairs():
for current in STATES:
for target in STATES:
allowed = target in ALLOWED_TRANSITIONS[current]
try:
transition(current, target)
assert allowed
except ValueError:
assert not allowed
test_all_pairs()
print("all transition pairs behave as specified")Also test concurrency against a real database. Run two simultaneous updates on the same payment and assert that exactly one succeeds.
Summary of decisions
| Decision | Recommended choice | Reason |
|---|---|---|
| Where to define transitions | One table in code | Easy to review and test |
| How to prevent races | Conditional `UPDATE` on expected status | Atomic, no lock held |
| How to treat repeats | Same-state request returns success | Retries stay safe |
| How to treat timeouts | Stay in a pending state | Avoids wrongly failing a payment |
| How to keep history | Append-only event rows in the same transaction | Audit and outbox support |
Exercise
Two servers both read a payment as authorized. One tries to capture it and the other tries to void it. Both pass the in-memory transition check. Which technique ensures only one of them succeeds, and how does it work?
Show answer
Use a conditional update such as UPDATE payments SET status = 'captured' WHERE id = :id AND status = 'authorized' RETURNING id. The database applies the status check and the write atomically. The first statement changes the row. The second finds the status is no longer authorized, updates zero rows, and returns nothing, so that server knows it lost the race and must reload the payment.
Exercise
An authorization call to the PSP times out. Should the payment move to failed? Explain why or why not.
Show answer
No. A timeout means the outcome is unknown. The PSP may have approved the authorization and be holding the customer's funds. Marking the payment failed could lead to a second attempt and a double hold, or to money held with no matching record. Keep the payment in a pending or unresolved state, then query the PSP or wait for a webhook. Move to a terminal state only after a confirmed result.