Skip to main content

Finite state machines and automata

Deterministic and non-deterministic automata, modeling behavior, verifying reachability and liveness properties. (no, reachability property).

What do you think about this article?

Finite state machines and automata
Formal Methodsfedericocalo.dev

At a Glance

Deterministic and non-deterministic automata, modeling behavior, verifying reachability and liveness properties. (no, reachability property).

A finite state machine is a model that captures system behavior: which states it can occupy, and how it transitions between them in response to input. It is not an alternative to code, it is a language for thinking about behavior before implementing. You use an automaton when system behavior depends on history (not just current input). Trivial example: toggle on/off (state = on or off, input = click). Real example: e-commerce cart (EMPTY, ITEMS, CHECKOUT, PAYING, COMPLETE, CANCELLED), TCP protocol (LISTEN, SYN_SENT, SYN_RCVD, ESTABLISHED, FIN_WAIT, CLOSED), elevator (IDLE, MOVING_UP, MOVING_DOWN, DOOR_OPENING, DOOR_CLOSING). Modeling as automaton lets you answer: "Can the cart go from ITEMS directly to COMPLETE without CHECKOUT?" (no, reachability property). "Is there a state I cannot exit?" (yes = deadlock, no = liveness).

Historical context and formalization

McCulloch & Pitts (1943) describe abstract neurons as simple automata: one stimulus (input) activates neuron (state transition). Turing (1936) invents Turing machine as universal automaton (infinite states, infinite symbols): most powerful computation model. Rabin & Scott (1959) distinguish deterministic automata (DFA: from one state, one input leads to one state) from non-deterministic (NFA: from one state, one input, multiple possible states). Thompson (1968) shows regex and NFA are equivalent. In 1980s-90s UML State Machines become industrial standard for modeling real-time and embedded systems. Today, "state machines" are in DNA of every framework (Angular state management, Redux for React, Xstate for JavaScript).

Series outline: Formal Methods

  1. (1722) When it pays off: ROI, critical sectors
  2. (1723) Logic for specification: propositional, first-order, triples, invariants
  3. (1724) Finite state machines and automata: modeling behavior
  4. Temporal logic (LTL, CTL) for time-varying properties
  5. Model checking: automating temporal property verification
  6. Petri nets: modeling concurrent and distributed systems

Definition and components of an automaton

A finite state automaton is a quintuple (Q, Σ, δ, q₀, F) where:

  • Q: finite set of states (e.g., {EMPTY, ITEMS, CHECKOUT, PAYING, COMPLETE, CANCELLED})
  • Σ: input alphabet (symbols automaton can receive, e.g., {add_item, remove_item, checkout, pay, cancel})
  • δ: transition function, δ: Q × Σ → Q (from state and input, next state)
  • q₀: initial state (e.g., EMPTY)
  • F: set of final/accepting states (e.g., {COMPLETE}-happy states)

Concrete example: e-commerce cart

  • Q = {EMPTY, ITEMS, CHECKOUT, PAYING, COMPLETE, CANCELLED}
  • Σ = {add_item, remove_item, checkout, pay, cancel}
  • δ: EMPTY + add_item → ITEMS, ITEMS + checkout → CHECKOUT, CHECKOUT + pay → PAYING, PAYING → COMPLETE or PAYING → CANCELLED (if payment fails)
  • q₀ = EMPTY
  • F = {COMPLETE} (success state)

Deterministic automata (DFA) vs non-deterministic (NFA)

DFA: Deterministic Finite Automaton

In a DFA, from one state and one input follows exactly one new state. δ(q, a) = q' (single q'). This is the "normal" situation: behavior is predictable. Algorithm to simulate is trivial:

def simulate_dfa(dfa, string):
    """
    dfa: (Q, Σ, δ, q0, F)
    string: sequence of input
    Returns True if string accepted (terminates in a state in F)
    """
    state = dfa.q0
    for symbol in string:
        if symbol not in dfa.sigma:
            return False  # unrecognized symbol
        state = dfa.delta[state, symbol]  # transition
    return state in dfa.F

# Example
cart_dfa = {
    'Q': {'EMPTY', 'ITEMS', 'CHECKOUT', 'PAYING', 'COMPLETE'},
    'Σ': {'add_item', 'checkout', 'pay'},
    'δ': {
        ('EMPTY', 'add_item'): 'ITEMS',
        ('ITEMS', 'checkout'): 'CHECKOUT',
        ('CHECKOUT', 'pay'): 'PAYING',
        ('PAYING', 'confirm'): 'COMPLETE'
    },
    'q0': 'EMPTY',
    'F': {'COMPLETE'}
}

# Simulation: add item, checkout, pay
sequence = ['add_item', 'checkout', 'pay', 'confirm']
print(simulate_dfa(cart_dfa, sequence))  # True

NFA: Non-deterministic Finite Automaton

In an NFA, from one state and one input can follow zero, one, or multiple states. δ(q, a) = {q₁, q₂, ...}. Like saying "this input might take me to one of these states; I do not know which, but explore all paths". Used in model checking: from one abstract state (representing multiple concrete states), one input leads to a set of states; model checker explores all paths searching for property violation.

Example NFA: payment with optional failure

  • δ(PAYING, timeout) = {PAYING, CANCELLED}-timeout could leave you in PAYING (retry) or go to CANCELLED (timeout exhausted). Non-deterministic: system could choose either.

An NFA is convertible to equivalent DFA (powerset construction), but DFA can have 2^|Q| states.

Subset construction: from NFA to DFA (Powerset Construction)

Algorithm by Rabin & Scott (1959): for every NFA state, create a DFA state representing the set of all possible NFA states simultaneously reached.

Central idea: In DFA, one state is a subset of NFA states. This eliminates non-determinism: from one DFA state (a subset), one input leads to exactly ONE new DFA state (union of all possible NFA states reachable).

Procedure on concrete example: NFA recognizing "(a|b)*abb" (a or b repeated, followed by abb).

NFA:
Q = {q0, q1, q2, q3}
Σ = {a, b}
δ:
  q0 + a → q0, q1      (stay in q0 OR go to q1 if start matching "abb")
  q0 + b → q0          (stay in q0)
  q1 + a → (fails)     (fails if expect "abb" but receive "a")
  q1 + b → q2          (second char "ab")
  q2 + b → q3          (third char "abb")
  q3 + a, b → (fails)  (reject, match complete)
q0 = q0
F = {q3}

Powerset construction:
DFA Q' = {
  [q0],                           # state with only q0
  [q0, q1],                       # states q0 and q1 simultaneously
  [q0, q1, q2],                   # states q0, q1, q2 simultaneously
  [q0, q1, q2, q3]                # states q0, q1, q2, q3 simultaneously
}

δ' (DFA transition):
  [q0] + a → [q0, q1]             # from q0, "a" reaches {q0, q1}
  [q0] + b → [q0]                 # from q0, "b" reaches {q0}

  [q0, q1] + a → [q0, q1]         # from q0 "a" → q0, q1; from q1 "a" → fails; union = [q0, q1]
  [q0, q1] + b → [q0, q2]         # from q0 "b" → q0; from q1 "b" → q2; union = [q0, q2]

  [q0, q2] + a → [q0, q1]         # from q0 "a" → q0, q1; from q2 "a" → fails; union = [q0, q1]
  [q0, q2] + b → [q0, q3]         # from q0 "b" → q0; from q2 "b" → q3; union = [q0, q3]

  [q0, q3] + a → [q0, q1]         # new match starts
  [q0, q3] + b → [q0]             # continue outer loop

F' = {[q0, q3]}                   # state containing q3 (final state)

Word "aabb":
q0 + a → [q0, q1]
[q0, q1] + a → [q0, q1]
[q0, q1] + b → [q0, q2]
[q0, q2] + b → [q0, q3]           # ACCEPTED! [q0, q3] is final.

Complexity: DFA has at most 2^n states (one per subset of NFA states). But if NFA is small (e.g., n ≤ 4), DFA is manageable. For complex regex with large |Σ|, powerset construction produces exponentially-exploding DFA.

DFA minimization

A DFA can have redundant states: two states behaving identically (recognize same language from that point onward). Minimization removes redundancy: the minimal DFA has fewest states possible and is unique up to isomorphism.

Hopcroft's algorithm (O(n log n)): Partition states into equivalence groups (states i and j are equivalent if they recognize same continuation). Then merge groups recursively.

Simple example: DFA recognizing strings ending in "01" (alphabet {0, 1}).

Original DFA:
q0 (start) + 0 → q1, + 1 → q0
q1 + 0 → q1, + 1 → q2
q2 (accepting, finished "01") + 0 → q1, + 1 → q0

Are q0 and q0 (from q1 + 1 → q2 + anything) equivalent?
No: q0 is non-accepting (not final state q2), so they are distinct.

Minimization: q0 stays, q1 stays, q2 stays (all necessary).
DFA is already minimal.

But if we had added duplicate states (e.g., q3 = q0 copy), minimization merges them.

Importance: Minimal DFA is best trade-off between state count and correct recognition. Used in regex engines (e.g., Perl regex compile does this minimization for performance).

Pumping Lemma and non-regular languages

Not all languages are regular (recognizable by DFA). How do you prove a language is NOT regular? With the pumping lemma.

Statement: If L is regular, then there exists constant p (pump length) such that every word w ∈ L with |w| ≥ p can be written as w = xyz where:

  • |y| ≥ 1 (pumped part is non-empty)
  • |xy| ≤ p (first part is within length p)
  • For every i ≥ 0, xy^i z ∈ L (you can repeat y any number of times)

Intuition: DFA has finitely many states (p = state count). If you read word of length p+1, by pigeonhole, visit some state twice. Substring between two visits is part y you can repeat.

Example: L = {a^n b^n : n ≥ 0} = {ε, ab, aabb, aaabbb, ...} is NOT regular.

Proof by contradiction: Suppose L is regular. Then p exists. Take w = a^p b^p ∈ L with |w| = 2p ≥ p. Write w = xyz with |xy| ≤ p and |y| ≥ 1.

Since |xy| ≤ p and xy is prefix of a^p b^p, xy consists only of "a" (we have not reached "b" part yet). So y = a^j for some 1 ≤ j ≤ p.

By pumping lemma, xy^2 z ∈ L. But xy^2 z has more "a" than "b": contains a^{p+j} b^p, where j ≥ 1. Not form a^n b^n. Contradiction. So L is not regular. ∎

Implication: If you want to recognize balanced-count languages (parentheses, HTML tags), you need at least pushdown automaton (context-free), not DFA (regular).

Output automata: Mealy and Moore

A classic DFA says yes/no: accepts word or rejects. But what if you want to translate input to output? Use output automata.

Moore automaton: Output is associated with states. δ(q, a) = q', and simultaneously emit λ(q) (output of state q).

Mealy automaton: Output is associated with transitions. δ(q, a) = q' and simultaneously emit λ(q, a) (output of transition).

Example Moore: binary → unary. Read bit sequence, emit number of "1" equal to length.

Moore: Σ = {0, 1}, Δ (output) = {1}
q0 → λ(q0) = "" (no output, start)
+ 0 → q1 → λ(q1) = "1"
+ 1 → q1 → λ(q1) = "1"
q1 + 0 → q1 → emit "1"
q1 + 1 → q1 → emit "1"

Input "01" → transitions q0 + 0 → q1 (emit "1"), q1 + 1 → q1 (emit "1") → Output "11"

Example Mealy: bit complement. Read bit, emit complement (0 → 1, 1 → 0).

Mealy: Σ = {0, 1}, Δ = {0, 1}
q (single state)
+ 0 / 1 → q (at state q, read 0, emit 1; stay in q)
+ 1 / 0 → q (read 1, emit 0; stay in q)

Input "0101" → Output "1010"

Equivalence: Mealy and Moore are equivalent in power: every Mealy converts to Moore (add states) and vice versa. Mealy tends to be more compact (fewer states); Moore often simpler conceptually.

When to use: Hardware encoder (convert clock to command signal): Mealy is natural. Language translator (read token, emit AST): Moore is natural.

Modeling a real system as automaton

Example: HTTP connection

An HTTP connection can be modeled as automaton:

Q = {CLOSED, CONNECTING, CONNECTED, SENDING, RECEIVING, CLOSING, ERROR}
Σ = {open, send_request, receive_response, close, timeout, error}

δ:
CLOSED + open → CONNECTING
CONNECTING + [success] → CONNECTED
CONNECTING + timeout → ERROR
CONNECTED + send_request → SENDING
SENDING + [request sent] → RECEIVING
RECEIVING + receive_response → CONNECTED
CONNECTED + close → CLOSING
CLOSING + [close ack] → CLOSED
[any state] + error → ERROR
ERROR + reset → CLOSED

What can we verify?

  • Reachability: "From CLOSED, can we reach CONNECTED?" Yes, via CONNECTING. "Can we reach infinite loop?" No, CLOSING → CLOSED.
  • Deadlock-freedom: "Is there a state I cannot exit?" No, every state has at least one transition.
  • Safety: "Can I receive response without sending request?" No, RECEIVING only reachable from SENDING.

Example: elevator

Q = {IDLE_1, IDLE_2, IDLE_3, MOVING_UP, MOVING_DOWN, DOOR_OPENING, DOOR_CLOSING}

Σ = {call_1, call_2, call_3, door_open_complete, door_close_complete, arrival}

δ:
IDLE_1 + call_3 → MOVING_UP
MOVING_UP + arrival → DOOR_OPENING
DOOR_OPENING + door_open_complete → IDLE_3
... and so on

Invariant (safety property): "Door does not open while elevator moves"
Verify: no MOVING_* state is successor of DOOR_OPENING without passing through arrival.

Verifying automaton properties

Reachability

Given target state, can we reach it from q₀? Algorithm: BFS or DFS from initial state. If you find target, it is reachable.

Deadlock-freedom

A state is deadlock if no outgoing transitions (and is non-final). Automaton is deadlock-free if from q₀ you cannot reach deadlock. Verify: DFS + check every reachable state (that is not final) has at least one transition.

Liveness

"If system continues, does it always reach a final state?" (e.g., if no errors, does order always complete). Verify: from every reachable state, a path leads to a final state.

Trade-off reasoning

I chose to show simple DFA (toggle, cart) before complex NFA because DFA is intuitive: one state after another, deterministic. NFA is bridge to model checking (one abstract state represents multiple concrete states). In practice: use DFA to verify systems with precise behavior (implementations), use NFA to explore all possible behaviors (specification, model checking).

Advanced connections

Regular expressions (regex): Are automata in textual form. `a*b+` is automaton reading zero or more 'a' followed by one or more 'b'. Thompson's construction (1968) converts regex to NFA in O(n) time.

Network protocols: TCP/IP handshake, 802.11 WiFi, BLE pairing are all formal automata. RFC 793 (TCP) describes protocol as state transition table.

Games and game theory: Games are modelable as automata with two players (turn-based). From one state, Player 1 chooses action (transition), then Player 2 chooses. Model checker can find winning strategy.

Synchronization and concurrency: When multiple processes run in parallel, the "product" of two automata (Cartesian product) models global state. If not synchronized, global state can explode (state space explosion).

Pitfalls and common mistakes

  • "One state = one code variable". Wrong. One state is a pair (combination) of variable values. Example: elevator IDLE on floor 3 is one state, not two ("IDLE" + "floor 3").
  • "Automaton with 100 states is unnecessarily complex". Depends. If it is the correct abstract model of behavior, then it is precise. Complexity is in problem, not model. (Note: if due to state explosion from concurrency, use abstraction or composition.)
  • "Non-determinism = randomness". Wrong. NFA means "multiple possible paths"; used in model checking to explore all paths finding property violations. No randomness, it is exploratory.
  • "If my system is DFA, it is deterministic". Wrong. If your specification is NFA and implementation is DFA, you may have added determinism. Check implementation refines specification (formally: implementation is contraction of NFA).

Advanced exercises

  1. Model a system you know: Take a simple feature you implement (e.g., login form: password reset button, input validation, submit). Draw states and transitions. How many states? Which inputs?
  2. Verify reachability: From your automaton, write BFS algorithm: "From EMPTY, can we reach COMPLETE?" If not, add transitions until reachable.
  3. Convert regex to NFA (Thompson): Take regex `a(b|c)*d` (a followed by zero or more b or c, followed by d). Draw corresponding NFA. Then test: which string is accepted? Which rejected?
  4. Model check a protocol: Take TCP handshake (SYN, SYN-ACK, ACK). Write as automaton. Verify: "Can connection happen without final ACK?" (No = safety). "From receiving SYN, do we always reach ESTABLISHED?" (Yes = liveness).

Essential bibliography

  • Jiacun Wang, William Tepfenhart, Formal Methods in Computer Science, CRC Press, 2019. (Ch. 4: Finite Automata; Ch. 5-7: Temporal Logic and Model Checking)
  • Michael Rabin, Dana Scott, "Finite Automata and Their Decision Problems", IBM Journal of Research and Development, 1959. (Foundational paper on DFA/NFA)
  • Ken Thompson, "Regular Expression Search Algorithm", Communications of the ACM, 1968. (Regex to NFA conversion)
  • David Harel, "State Machines for Statechart Semantics", Handbook of Theoretical Computer Science, Elsevier, 1990. (State machines and UML)
  • Gerard Holzmann, Spin Model Checker, manual online: spinroot.com (Practical tool for model checking concurrent systems)

Technical prerequisites

  • Propositional and first-order logic (articles 1722-1723)
  • Sets and relations (domain, codomain)
  • Notion of partial and total function
  • Graph search (BFS, DFS)
  • Python: dicts (represent δ as dict), sets (represent Q and F), loops and recursion

Related resources

Article published 2026-10-08, graduate level.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects