A finite state machine (FSM) is a model of behavior built from a fixed set of states, the events that trigger transitions between them, and the actions that run on entry, exit, or during a transition. To design one, you define its scope and interface, enumerate states and events, build a transition table, choose a representation (switch-based, table-driven, or state pattern), implement it with explicit guards and actions, then test every transition and reject invalid input. The key condition is that the machine must be finite and deterministic in intent: every relevant event in every state either has a defined response or an explicit, documented rejection.
That definition sounds abstract, so it helps to see where the approach pays off. A media player's play/pause logic, an ATM session, a vending machine's coin handling, a TCP connection's lifecycle, and a checkout wizard with validation steps are all naturally stateful. They behave differently depending on history, and that history can be captured in a small number of named conditions. When you can say "the system is in one of these N situations, and this event moves it to that one," an FSM is usually the right tool.
Start With Scope, Interface, and the Decision to Use an FSM
Before drawing circles and arrows, decide what the machine owns. An FSM should control one coherent piece of behavior: a connection, a session, a device mode, an order's fulfillment status. If you try to model an entire application as a single machine, you get a combinatorial explosion of states that no one can review.
Write down four things first:
The boundary. What events come in from outside (user input, network messages, timers)? What outputs does the machine produce (commands, return values, emitted events, UI changes)? The owner. Which object, module, or service holds the current state, and who is allowed to send events to it? The lifecycle. When is the machine created, reset, and destroyed? Does its state persist across restarts, and if so, where? The invariants. What must always be true regardless of state, such as "at most one active connection" or "a refund is never issued before payment clears"?
A quick test for whether you need an FSM: list the behaviors that depend on "what happened before." If there are more than two or three such conditions and they interact, a boolean-flag approach (isLoading && !hasError && isRetrying) becomes unreadable fast. An FSM replaces that tangle with named states that are mutually exclusive.
Conversely, avoid an FSM for purely stateless transformations or for behavior with exactly one condition. Wrapping a single boolean in a state machine adds ceremony without clarity.
One more scoping decision: does the machine need to be deterministic? A deterministic finite automaton (DFA) has exactly one transition per state-event pair, so its behavior is fully predictable and easy to test. A nondeterministic design allows multiple possible transitions, which is sometimes useful for modeling ambiguity, but in software you almost always want determinism with explicit guards rather than true nondeterminism. If two transitions from the same state share an event, distinguish them with guard conditions that are mutually exclusive and ordered.
Enumerate States as Named, Mutually Exclusive Conditions
A state answers the question "what is true right now that changes how I respond to the next event?" Good state names are adjectives or noun phrases describing a condition, not actions: Idle, Connecting, Connected, Disconnecting, Failed. Bad names are verbs like Connect, because actions are transitions, not states.
Here is a practical procedure for finding states:
1: Collect the distinct situations from requirements, user stories, or the existing code's conditional branches. Read every if that checks a historical flag. 2: Merge situations that behave identically for all events. If two conditions produce the same response to every input, they are one state for this machine's purpose. 3: Split situations that differ in allowed events, outputs, or invariants. If one situation silently ignores an event that another must reject loudly, they are different states. 4: Name each state and write a one-line definition of what it means. 5: Identify exactly one initial state and the conditions under which the machine resets to it.
A worked example keeps this concrete. Consider a simplified vending machine that accepts coins, dispenses an item, and returns change:
States: Idle (no credit), HasCredit (some money inserted, below price), Ready (credit at or above price), Dispensing (item being released), Refunding (returning inserted money). Events: InsertCoin(value), SelectItem, Cancel, DispenseComplete, RefundComplete. Actions: increment or decrement credit, release the item, return coins, log a transaction.
Notice the design choice: HasCredit and Ready could theoretically be merged with a guard (credit >= price). Splitting them is usually cleaner because the "what can happen next" differs: Ready permits SelectItem, while HasCredit must reject selection with an "insert more" response. Guards would work too, but the split states make the table easier to read. Either choice is defensible; the important part is that it is a deliberate decision, not an accident.
Distinguishing states from state data
A common error is encoding changing data as separate states. If a shopping cart can hold 1, 2, or 10 items, you do not want CartWithOneItem, CartWithTwoItems, and so on. You want a single Active state with an items collection as data. The rule: states capture control flow; variables and collections capture data. Move anything that scales with input into state data.
The flip side is over-merging. If a payment flow has AwaitingCard, Authorizing, Authorized, and Declined, collapsing them into Processing loses the difference between "still trying" and "done, successfully" and "done, failed." Each of those permits different next events.
Handling orthogonal behavior
Some systems have several independent dimensions: a media player might be playing or paused on one axis and connected or offline on another. Modeling all combinations as flat states yields PlayingConnected, PlayingOffline, PausedConnected, and so on. Two options exist: accept the product of states if the number stays small, or model each dimension as its own smaller machine and coordinate them. Flat states are simpler to reason about; separate machines are easier to extend. Choose based on how many combinations realistically exist versus how many behaviors actually differ.
Define Events, Transitions, Guards, and Actions
States are half the model; the event alphabet is the other half. List every event the boundary defined, including internal ones like timeouts and completion callbacks. For each event, note whether it is delivered to a specific state or broadcast.
For every state-event pair, decide one of four outcomes:
Transition to another state, optionally with a guard. Internal action with no state change, such as incrementing credit on InsertCoin. Ignore the event with no effect, which is appropriate for harmless, frequent events like duplicate heartbeats. Reject the event explicitly, logging or returning an error, which is appropriate for invalid user actions like pressing "payout" while the machine is idle.
Write the rejection rules as deliberately as the happy path. Most FSM bugs in production trace to undefined behavior for unexpected events, and the silent ignore is often worse than a loud rejection because it hides the logic error.
Guards are conditions checked before a transition is taken. They must be side-effect-free and deterministic, because a guard that reads mutable state can produce surprising results when evaluated twice. If a transition has a guard, define what happens when it fails: fall through to another transition, stay put, or reject.
Actions come in three flavors, and keeping them distinct prevents a lot of confusion:
Entry actions run once when a state is entered: allocate a resource, start a timer, update a UI label. Exit actions run once when leaving: cancel the timer, release the lock. Transition actions run on a specific edge: emit a message, persist a record.
The classic failure is putting a side effect in the wrong slot. If Connecting starts a retry timer in its entry action, then any transition into Connecting—including a retry loop back to itself—correctly restarts the timer. If instead you put the timer start in a transition action from Idle only, the retry path silently skips it.
State entry and exit actions also pair naturally into setup and teardown, which is how you guarantee cleanup even when many events can leave a state. That symmetry is one of the strongest arguments for entry/exit actions over ad hoc code in transition handlers.
Build the Transition Table and Audit It
The transition table is the FSM's contract. Rows are states, columns are events, and each cell contains the next state, any guard, and any output. If you maintain it as documentation alongside code, it becomes the artifact reviewers read first.
Continuing the vending example, here is a compact version (credit and price are variables):
| State | InsertCoin | SelectItem | Cancel | DispenseComplete | RefundComplete |
|---|---|---|---|---|---|
| Idle | HasCredit (if value adds credit) | Reject | Ignore | Reject | Reject |
| HasCredit | HasCredit or Ready (guard: credit >= price) | Reject | Refunding | Reject | Reject |
| Ready | HasCredit or Ready (credit changes) | Dispensing (if credit >= price) | Refunding | Reject | Reject |
| Dispensing | Reject | Reject | Ignore | Idle (after change) | Reject |
| Refunding | Reject | Reject | Ignore | Reject | Idle |
Two things are worth noticing. First, the HasCredit row's transition on InsertCoin either stays or moves to Ready depending on a guard, which is why guards belong in the table rather than in prose. Second, every cell has an entry—no blanks—because a blank cell is an undefined behavior waiting to happen.
Now audit the table systematically. These checks catch most design defects before any code exists:
Reachability. Every state must be reachable from the initial state. An unreachable state is either dead code or a sign of a missing transition. Co-reachability. Every state must be able to reach a terminal or reset state. A "black hole" state with no outgoing transitions is a hang. Completeness. Every state-event pair has a defined outcome, even if the outcome is "reject." Determinism. For each state and event, at most one transition's guard can be true at a time, and guard ordering is explicit. Orphan events. Every event should do something in at least one state; an event with no effect anywhere is probably a scoping mistake. Invariant preservation. Walk each transition and ask whether any invariant from the scope step can be violated in between.
For small machines, the audit is a ten-minute reading exercise. For larger ones, draw the diagram and look for states with identical rows—they often indicate an accidental duplicate—and states with only one inbound edge, which may be vestigial.
Choose a Representation: Switch, Table-Driven, or State Pattern
The same transition table can be implemented in several ways, and the right choice depends on team familiarity, the number of states, and how often the machine changes.
Nested switch (or match) statements are the most direct translation. The outer switch selects the state, the inner switch selects the event, and each branch performs the transition and actions. This is perfectly readable for five to ten states and makes the transition logic visible in one place. Its weakness appears as the machine grows: the function becomes long, and reusing behavior across states means duplicating code.
Table-driven implementations store transitions as data (a map keyed by state and event, or an array indexed by enums) and use a single loop to look up and execute them. Actions become function pointers or lambdas. This scales well, keeps the whole contract in one data structure, and makes it trivial to write a generic test harness that iterates every row. The cost is indirection: readers must follow a lookup to understand behavior.
The state pattern, where each state is a class implementing a common interface with a handler per event, distributes the logic into small, focused units. Adding a state means adding a class, which is convenient when states are developed independently or carry substantial behavior. The trade-off is that the transition graph is spread across files, so a table or diagram must be maintained separately to see the whole picture.
A practical recommendation: start with the switch if the machine has fewer than about eight states, because the explicit code is easiest to review. Move to a table or the state pattern when the switch exceeds roughly one screen, when the same machine appears in multiple variants, or when you want automated exhaustive testing. Mixing approaches within one codebase is fine as long as each machine is internally consistent.
Whichever you pick, keep three things out of the state-handling code: business calculations, I/O that can fail unpredictably, and presentation logic. The FSM should decide what happens next and emit effects; other layers should decide how. This separation is what lets you test transitions without a database or a screen.
Implement With Explicit Guards, Actions, and Failure Handling
The implementation step is where the design becomes real, so follow an order that keeps the contract intact.
1: Encode states and events as enums or a sealed hierarchy so the compiler or linter can catch typos and missing cases. 2: Create a single handle(event) entry point that is the only way to send events. Having multiple pathways into the machine is how state gets corrupted. 3: Look up the transition using state plus event, evaluate guards in a fixed order, and if no guard passes, apply the documented fallback (stay, ignore, or reject). 4: Run exit actions for the current state, apply the transition, run entry actions for the new state, in that order. If you use transition actions too, define whether they run before or after the state change and be consistent across the machine. 5: Emit effects through a narrow interface—return values, a queue, or an injected callback—rather than mutating external systems inside handlers. 6: Serialize state explicitly if persistence is needed, storing the state identifier plus the state data, and validate it on load so a corrupted or outdated value fails loudly instead of silently resuming in a wrong state.
Thread safety deserves a sentence of its own. If events can arrive concurrently, serialize them through a queue or protect the state with a lock, so that reading the current state, evaluating guards, and applying the transition happen as one atomic step. Otherwise two events can both see Idle and both transition, losing one.
For failure handling, decide what happens when an action throws. The safest pattern is to complete the state change and then run effects, or to run effects in a way that records failure as a new event (for example, a failed emit becomes a SendFailed event that the machine handles in a recovery state). Letting an exception unwind mid-transition leaves the machine in an ambiguous combination of old state and partially executed side effects.
A short implementation sketch in pseudocode, using the table lookup style:
This is not the only correct shape, but it demonstrates the essential properties: one entry point, guarded deterministic selection, and exit-before-entry ordering. If your code cannot be expressed this compactly, ask whether a layer of indirection has crept in.
Test Every Edge, Not Just the Happy Path
Testing an FSM is unusually tractable because the model is exhaustive by construction. Two complementary strategies cover it well.
Structural coverage walks the transition table. Write a test for every row—every state-event pair—and assert the next state and the outputs. If the table has 40 cells, you have at least 40 assertions, and gaps in coverage are easy to see. Add tests for each guard boundary: exactly at the threshold, one unit below, one unit above. In the vending example, test SelectItem with credit equal to price, below price, and zero, before and after insertion.
Sequence coverage tests paths through the graph: the normal purchase flow, cancel midway, cancel from idle, coin insertion during dispensing, duplicate DispenseComplete, and a reset mid-session. These catch the bugs that per-cell tests miss, especially ordering errors in entry and exit actions.
A cheap technique for small machines is to generate random event sequences, deliver them to the real machine, and compare the resulting state against a reference model that is just the transition table interpreted in a few lines of test code. If the reference and the implementation ever disagree, you have either a bug or a table update you forgot to mirror—both worth knowing.
Track which (state, event) cells and which guard branches have been exercised. A coverage report over the transition table is far more meaningful than line coverage for this kind of code, because line coverage can hit every line while missing an entire guard outcome.
Debug, Document, and Review Before Committing
When an FSM misbehaves, resist patching symptoms. The usual failure modes and their fixes:
A transition happens from the wrong state. Symptom: an action fires when it should not. Cause is usually a missing or unordered guard, or an event routed past the handle entry point. Fix the table, not the handler. The machine hangs. Symptom: no response to any input. Cause is a state with no outgoing transition for the expected event, or a guard that can never pass. Check co-reachability. An action runs twice or not at all. Symptom: duplicated side effects or lost cleanup. Cause is action placement in the wrong slot (entry versus transition) or an exception aborting a transition midway. State resurrects incorrectly after restart. Symptom: the system resumes in an impossible situation. Cause is persisted state without validation, or data that changed shape between versions.
For diagnosis, add a single logging point at the handle entry that records the incoming state, event, guard outcome, and next state, with an identifier for the instance. One structured log line per event makes almost every bug reproducible.
Documentation should be small and generated from the model where possible: the state list with definitions, the transition table or diagram, the event alphabet, and the invariants. Update the diagram in the same change as the code; a stale diagram is worse than none because reviewers trust it.
For review, ask these questions of any FSM change: Is every new state reachable and co-reachable? Does every new event have a defined outcome in every state? Are the guards mutually exclusive and ordered? Do entry and exit actions pair up? Does the new path preserve all invariants? Is there a test for each new cell? These questions are answerable by reading the table, which is the whole point of having one.
Knowing When an FSM Is the Wrong Model
An FSM is a poor fit when behavior depends on long histories that cannot be compressed into a small state set, when many independent dimensions interact freely (the product-of-states problem), or when the system is essentially a pipeline of transformations. In those cases, consider a statechart with hierarchical and parallel states, which scales the same ideas; a workflow or saga pattern that coordinates several machines; or plain functional code when there is no meaningful state at all.
Even when an FSM fits, keep it modest. If the table no longer fits on a page or two, split the behavior into smaller machines with clear interfaces rather than growing one monolith. The discipline that makes FSMs valuable—mutually exclusive named conditions, exhaustive event handling, and testable edges—is also what makes them easy to decompose.
A final sanity check before you commit: hand the state list and transition table to someone unfamiliar with the code and ask them to predict the machine's response to three event sequences. If they get all three right, the model is clear enough to maintain. If they hesitate, the ambiguity they found is probably also a bug waiting to happen.