What is a GenStateMachine in Elixir?
Answer
GenStateMachine (or :gen_statem in Erlang) is an OTP behaviour for implementing finite state machines as processes. It models a process as a set of states, events, and transitions between states. Each state has a handler function that processes events and returns the next state. Example states for a traffic light: :red, :green, :yellow. Define transitions: def red(:cast, :next, data), do: {:next_state, :green, data}. This is cleaner than a GenServer with a state field because the state machine logic is explicit in the state handler functions. Use cases: network protocol implementations (TCP connection states), order workflows (pending → confirmed → shipped → delivered), authentication flows, connection lifecycle management. The BEAM has been running state machines this way in telecom switches since the 1980s — protocols like SCTP are implemented as gen_statem in Erlang.
Previous
What is Elixir's error handling approach?
Next
How does hot code upgrading work in Elixir/Erlang?
More Elixir Questions
View all →- Intermediate How do Elixir supervisors implement fault tolerance?
- Intermediate What is Phoenix Channels and how do WebSockets work in Elixir?
- Intermediate What is Elixir's concurrency model compared to threads?
- Intermediate What are Elixir behaviours?
- Intermediate What is Elixir's error handling approach?