Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 50 ยท Projects

Project: An Order Workflow State Machine

Design an order life cycle as a state diagram, implement it with a transition table, guards and actions in Node.js, then test it and check it exhaustively.

An online order moves through a life cycle: it is drafted, placed, paid, shipped and delivered, and along the way it can be cancelled or refunded. Bugs in such workflows are expensive. Ship an unpaid order, refund an order twice, or cancel something already on a truck, and real money and trust are lost. In this project you will design the order life cycle as a state machine, implement it so the rules live in one table, and then test it both with hand-written cases and with an exhaustive check.

You already met the notation in State, Component and Deployment Diagrams; here you build a more complete, tested version. The code runs as Node.js programs on the site's code runner (a single file, no packages, plain node:assert). The order, its prices and rules are an invented model: there is no payment provider, database or shipping system behind it.

Step 1: list the states, events and rules

Start with plain sentences, as you did in the library project:

  • An order starts as a draft; items can be added only while it is a draft.
  • A draft with at least one item can be placed.
  • A placed order is paid when a payment of exactly the order total arrives.
  • A paid order can be shipped only if it has a shipping address.
  • A shipped order is delivered when the carrier confirms it.
  • A draft or placed order can be cancelled with nothing to refund. A paid order can still be cancelled, which refunds the money. A shipped order cannot be cancelled.
  • A delivered order can be refunded within 14 days of delivery.

Now separate the vocabulary. The states are conditions the order stays in: draft, placed, paid, shipped, delivered, cancelled, refunded. The events are things that happen: place, pay, ship, deliver, cancel, refund. A guard is a condition that must hold for an event to take effect (items exist, amount matches, address present, within 14 days). An action is work done as part of the transition (record the paid amount, record the refund). Final states (cancelled, refunded, and in practice delivered once the refund window passes) allow no further normal progress.

The parts of a state machine

State Where the order is now.
Event Something that happens.
Guard A condition that must be true.
Action Work done during the move.

A transition fires only when the event arrives in the right state and the guard passes.

1 / 2

Step 2: draw the state diagram

Draw before you code. A diagram is a cheap place to find missing rules. Every state needs at least one way in, and every non-final state needs a way out.

stateDiagram-v2
    [*] --> draft
    draft --> placed : place [has items]
    draft --> cancelled : cancel
    placed --> paid : pay [amount matches total]
    placed --> cancelled : cancel
    paid --> shipped : ship [has address]
    paid --> refunded : cancel / refund all
    shipped --> delivered : deliver / record day
    delivered --> refunded : refund [within 14 days]
    cancelled --> [*]
    refunded --> [*]

The order life cycle. Eight arrows are allowed; every other combination of state and event is forbidden.

Study the diagram for questions before moving on, because each is a possible bug:

  • Can a shipped order be returned if the delivery fails? (We say no for now: the model has no "failed delivery" event. That is an explicit gap, not an oversight.)
  • Is "cancel after payment" really a refund state, or should it be a separate "cancelled and refunded"? We chose one refunded state for both paths to keep the table small, and the payment record tells which path was taken.
  • What happens after the 14-day window? The order stays delivered forever; no event moves it. That is correct, but it is worth stating in the requirements.

Step 3: implement the transition table

The standard implementation is a transition table: for each state, which events are allowed, where they go, with what guard and action. The fire method is the only code that changes the state, so the rules cannot be bypassed accidentally. Guards return null when the transition is allowed, or a human-readable reason when it is not, so callers (and tests) can show why an event was refused. Money is stored in whole cents and "time" is a plain day number, so every run is repeatable.

The test runner at the bottom is a few lines of code around node:assert. The program prints one line per test and a summary; it does not use node:test because that prints timing numbers that change on every run.

Node.js The order state machine with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three design choices are worth noticing. First, a refused event changes nothing: the tests check that the state is still placed or paid afterwards. Second, fire returns a result object instead of throwing, because a refused event is a normal outcome (a customer clicking "ship" too early), not a program error; only a real misuse, such as editing items after the draft, throws. Third, the refund-window tests sit on both sides of the boundary (day 24 is fine, day 25 is not), the technique from test design.

Step 4: check the whole machine exhaustively

Hand-written tests cover the cases you thought of. A state machine has a bonus: it is small enough to check completely. The second program describes the same transitions as plain data and then:

  • prints the full state by event matrix, where a dash means "forbidden";
  • finds unreachable states (a state nobody can enter is dead design) and final states;
  • runs 1,000 random walks with a fixed seed, firing random events and checking invariants, statements that must always hold: an order is never shipped without having been paid, and never delivered without having been shipped.

The random walk is a simple form of property-based testing: instead of choosing examples, you state a rule and try many inputs. It uses a small seeded random number generator so the output is the same on every run. This program deliberately uses only the transition data, not the guards, so it checks the shape of the diagram. The guards are covered by the tests above. In a real project the table would live in one module that both programs import; here each example is a single file, so the table is repeated.

Node.js Exhaustive checks of the transition table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The matrix makes the key fact visible: only 8 of the 42 combinations are allowed, so 34 are forbidden, and each forbidden cell is a rule the code must enforce. Every state is reachable, and the final states are cancelled and refunded. The walks find no violation. To see the invariants work, add a bad row such as ["placed", "ship", "shipped"] to transitions and run again: unpaid orders can now be shipped, and the walks report violations. That is how an exhaustive check catches a wrong edit in a table, even one that looks harmless in a code review.

Step 5: extend the machine

Real workflows keep growing. Try these as exercises, each as a change to the diagram first, then the table, then the tests:

  1. Failed delivery: add fail-delivery from shipped back to paid (or to a new return-to-sender state). What happens to the refund rules?
  2. Partial refunds: the action should refund only some of the paid amount. Where do you store how much is already refunded so you cannot refund more than was paid?
  3. Payment timeout: a placed order that is not paid within 3 days becomes cancelled on a timeout event. Who sends that event?
  4. Audit trail: store every transition with a timestamp, event and actor. The log array is a first step. What must be recorded so a disputed refund can be explained months later?
  5. Persistence: the state must survive a restart and two servers might handle the same order at once. What must a database do so two pay events cannot both succeed? (Think about an atomic update that checks the current state.)

The pattern scales further than you might expect: payment flows, document approvals, support tickets, build pipelines and even parsers are state machines. When a workflow has more than a dozen states, consider nested states (as in the UML notation) so each level stays readable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the transition table, what is a guard?

    Guards decide whether a transition that exists in the table actually fires, such as 'the order has items' or 'the payment equals the total'.
  2. 2. What should happen to the order's state when an event is refused by a guard?

    A refused event must change nothing. The tests check the state and the data are the same afterwards.
  3. 3. Why does the exhaustive check show 34 forbidden combinations?

    Seven states times six events is 42 pairs. The table lists eight allowed transitions, so the other 34 are forbidden and must be refused by the code.
  4. 4. What is an invariant in a random walk test?

    Property-based tests state invariants and try many inputs. If any path breaks the rule, the test reports a violation.
  5. 5. Why is a refused event returned as a result object instead of thrown as an error?

    A customer pressing 'ship' too early is an expected case. Exceptions are for misuse and unexpected failures.

Summary

  • A state machine for a workflow lists states, events, guards and actions; drawing the diagram first exposes missing rules and unanswered questions.
  • A transition table keeps all the rules in one reviewable place, and a single fire method is the only code that changes the state.
  • Refused events change nothing and report a reason; tests cover the happy path, each guard and both sides of boundaries such as the 14-day refund window.
  • Because the machine is small, you can check it completely: print the state by event matrix, look for unreachable states and test invariants with random walks.
  • The same pattern scales to payments, approvals, tickets and pipelines, and each extension starts with the diagram and a failing test.

Next: Project: A Sprint and Velocity Simulator.