OTP, State, and the Functional Core

An introduction to the OTP GenServer along with some tips on using your functional core.

The OTP GenServer

We built some boilerplate to use recursion and message passing to manage the state. The OTP GenServer does precisely that. It creates a process and loops over some state. Then other processes can modify that state by sending the GenServer messages.

In Elixir, OTP uses the magic of macros and functions to make all of this available with little ceremony: the recursive loop, the message passing, and more. They hide many of the messy details from you. It gives the user control of the receive_message function by calling functions called callbacks in your code. We’ll get into the details, but for now, understand that OTP is an Elixir feature that uses concurrency, recursion, and process primitives to track processes and manage state.

Understanding the GenServer

Few concepts are as mysterious or misunderstood as the OTP GenServer. Forget that “gen” is an abbreviation. The word “server” is confusing enough, because GenServers are abstractions that usually don’t have anything to do with network communication at all.

It’s no wonder that this concept is poorly understood by the bulk of programmers that enter the Elixir ecosystem, even though the ideas underneath the architecture are stunningly simple. Remember the loop and the counter. That’s the heart of OTP.

Structure

Since variables in functional languages are immutable, we can’t just change them when we want to change state. Instead, OTP uses function arguments to represent our state and has a recursive loop just calling itself with a new state, as shown in the following diagram. Our counter needs to specify a call message to our process, which increments the counter and sets the new value for the state.

Get hands-on with 1200+ tech skills courses.