Skip to content

Payments · 6 of 6

Step 1 · The pattern

A payment has a lifecycle

The provider reports each stage. First authorized: the money is reserved. Then captured: the money is taken. Your service records the status as events arrive.

  • event
  • authorized
  • captured

In short

Payment state machine: how it works and how it breaks

A payment moves through a small set of states: created, authorized (money reserved), captured (money taken) and perhaps refunded. The events that drive those moves arrive over the network, so they can be late, repeated or out of order. If your code handles each event by writing its status straight into the row, the last event to arrive wins, not the last to happen. A delayed 'authorized' landing after 'captured' moves the payment backwards: the customer has paid and your system says they have not. The fix is to treat the lifecycle as a state machine. List every allowed transition, and make each update conditional on the current state, for example with a WHERE clause on the status column. Anything else is rejected and logged. A repeated event becomes a harmless no-op, and impossible sequences surface as alerts instead of silent corruption.

How this comes up in interviews

"Your service updates a payment's status from provider events. A delayed event arrives after a later one. What happens, and how do you prevent it?"

Then they ask

  1. How do you make the state check and the update a single atomic step?
  2. The same event is delivered twice. What does your design do with the second copy?
  3. What do you do with an event whose transition is not allowed: drop it, alert, or something else?

A strong answer covers

  • Events arrive over the network, so they can be late, repeated or out of order.
  • Writing each event's status straight into the row means the last to arrive wins, not the last to happen.
  • List every allowed transition and make each update conditional on the current state.
  • Put the expected state in the WHERE clause and check the row count, so the check and the write are one step.
  • A repeated event becomes a no-op, and illegal moves are rejected and logged.

Points to cover, not a script. Say them in your own words and tie them to a system you have worked on.

On one page: the track cheat sheet.

Last updated: Official documentation

Diagrams are our own simulations: the timings, rates and counts in them are illustrative, not measurements. Captions are original wording.