State machine diagram

State diagrams are the right tool whenever something has a status field. They make the illegal transitions obvious, which is where most bugs in status handling live.

Draw the states the system actually has, including the ones nobody planned.


#When to draw one

  • Anything with a lifecycle: orders, tickets, subscriptions, documents.

  • Designing a status field before implementing it.

  • Finding the transitions nobody handled.


#What is on the diagram

Element

Meaning

State

A box, sometimes with entry and exit actions

Transition

An arrow, labelled with the event that causes it

Guard

A condition in brackets on a transition

Initial and final

Filled circle, and bullseye

Composite state

A state containing its own state machine


#A worked example

A subscription lifecycle, including the states nobody plans for:

State machine diagram

The source, which you can paste into a new diagram and edit:

stateDiagram-v2
  [*] --> Trialling
  Trialling --> Active: payment succeeds
  Trialling --> Expired: trial ends, no payment
  Active --> PastDue: payment fails
  PastDue --> Active: payment retried successfully
  PastDue --> Cancelled: 3 failures
  Active --> Cancelled: customer cancels
  Cancelled --> Active: reactivated within 30 days
  Cancelled --> [*]: after 30 days
  Expired --> [*]

  note right of PastDue
    Retries on days 1, 3 and 7
  end note

#A few things that catch people out

  • Every state needs a way out, or it is a trap. Cancelled with no exit is often a real bug.

  • Label transitions with the event, not the resulting state. The arrow already shows the state.

  • Guards in brackets are how you express "only if", which is usually where the rules live.



Four types cover most of it.