From my_gen_server to OTP gen_server & Live sys:get_state/1 Introspection
Why This Matters in Production
In Chapters 5 and 6, we designed custom actor loops using spawn, receive, make_ref(), and monitor. In Lesson 6.8, we even built our own my_gen_server.erl from scratch, demonstrating that synchronous calls under the hood are simply a monitor, a tagged message, and a selective receive.
While writing raw actor loops teaches the foundational mechanics of the BEAM, writing raw process loops in production is a severe anti-pattern.
Why? Because a production backend process in WhatsApp, Klarna, or Ericsson must handle dozens of complex system concerns beyond its core domain logic:
- Supervisor Integration: Responding to parent shutdown signals (
{'EXIT', Sup, shutdown}) and graceful termination timeouts. - Hot Code Upgrades: Migrating internal process state across version upgrades without restarting the VM via
code_change/3. - Live System Introspection: Allowing operators to inspect live state using
sys:get_state/1andsys:get_status/1without halting the process or creating concurrency races. - Debug Tracing & Event Logging: Dynamically enabling execution tracing via
sys:trace(Pid, true).
Erlang solves this with OTP Behaviours. An OTP Behaviour uses the Inversion of Control (IoC) pattern: the OTP runtime provides the battle-hardened generic engine that handles concurrency, timeouts, and system messages, while you supply a clean, pure callback module.
Deep Concept Breakdown & Under the Hood
Inversion of Control: The Engine vs. Callback Model
In a raw process loop, your code is in control:
1%% Raw Loop: You control everything (and must handle every edge case!)2loop(State) ->3 receive4 {call, From, Msg} ->5 NewState = handle_msg(Msg, State),6 From ! {reply, ok},7 loop(NewState)8 end.In an OTP Behaviour, OTP is in control. The standard library module gen_server.erl owns the receive loop. When a message arrives, the gen_server engine invokes your exported callback functions:
Generic Engine (gen_server.erl) | Your Callback Module (Mod.erl) | Architectural Responsibility |
|---|---|---|
gen_server:start_link(Mod, Args, Opts) | Mod:init(Args) | Process spawning, linking, and initial state creation. |
gen_server:call(Pid, Request) | Mod:handle_call(Req, From, State) | Synchronous request-reply with monitor crash detection. |
gen_server:cast(Pid, Message) | Mod:handle_cast(Msg, State) | Asynchronous fire-and-forget message handling. |
Raw incoming messages (!, timers, sockets) | Mod:handle_info(Info, State) | Handling out-of-band signals and system timers. |
Supervisor shutdown or gen_server:stop/1 | Mod:terminate(Reason, State) | Cleaning up file handles, sockets, and ports. |
| Live code loading | Mod:code_change(OldVsn, State, Extra) | Transforming state maps between software releases. |
The -behaviour(gen_server). Compiler Contract
Adding -behaviour(gen_server). tells the Erlang compiler to verify that your module exports all required callbacks. If you forget to export handle_call/3 or handle_info/2, erlc emits compilation warnings alerting you before deployment:
1-module(my_server).2-behaviour(gen_server).3 4%% Client API5-export([start_link/0, get_value/1, stop/1]).6 7%% Required gen_server Callbacks8-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).Inspecting Live State with sys:get_state/1
One of the greatest operational superpowers of the BEAM VM is zero-downtime introspection. In languages like C++, Java, or Go, inspecting the private memory of a running thread requires attaching a heavy debugger (like GDB or Delve) that pauses thread execution.
In Erlang, because every gen_server process understands system protocol messages, an operator in the production Erlang shell can run:
1State = sys:get_state(ServerPid).The gen_server engine intercepts the system message, extracts its current internal State term, and replies to the operator without dropping client requests or mutating state!
Because a gen_server processes its mailbox sequentially, calling a slow external API (e.g. httpc:request) or sleeping with timer:sleep/1 inside handle_call/3 freezes the entire server. All subsequent client calls get stuck in the mailbox and will eventually crash with {timeout, {gen_server, call, ...}} after 5,000ms!
Official Erlang Docs & Function Reference
Before inspecting the parallel monitor implementation, familiarize yourself with the official OTP core interfaces:
gen_server:start_link/3,4— Spawns and links a newgen_serverprocess, synchronously callingMod:init/1before returning. Ensures the caller receives exit signals if the server crashes during startup.gen_server:call/2,3— Sends a synchronous request to thegen_serverand suspends caller execution until a reply arrives (or default 5,000ms timeout expires). Uses internal monitors to fail immediately if the target process dies.gen_server:cast/2— Sends an asynchronous, non-blocking fire-and-forget message to thegen_servermailbox and returnsokimmediately.sys:get_state/1,2— Synchronously retrieves the internal state term of an OTP process via the system message protocol without disrupting normal message dispatching.
Parallel Worked Example: The IoT Telemetry Monitor (device_telemetry.erl)
To see how an OTP behaviour separates client API wrappers from internal callback evaluation, consider device_telemetry.erl. This server monitors an IoT edge node: tracking battery percentage, counting transmitted packets asynchronously, and allowing synchronous status queries and live operator inspection with sys:get_state/1.
Notice how the module exports both the Client API (invoked by external processes) and the gen_server Callbacks (invoked internally by the OTP engine):
1-module(device_telemetry).2-behaviour(gen_server).3 4%% Client API5-export([start_link/1, record_packet/2, query_status/1, stop/1]).6 7%% gen_server Callbacks8-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).9 10%% @doc Starts and links the telemetry monitor gen_server with initial battery percentage.11start_link(InitialBattery) ->12 gen_server:start_link(?MODULE, [InitialBattery], []).13 14%% @doc Asynchronously records transmitted telemetry packet bytes without blocking caller.15record_packet(Pid, ByteCount) when is_integer(ByteCount), ByteCount > 0 ->16 gen_server:cast(Pid, {record_packet, ByteCount}).17 18%% @doc Synchronously queries the current telemetry metrics from the server.19query_status(Pid) ->20 gen_server:call(Pid, get_status).21 22%% @doc Synchronously requests clean termination of the telemetry server.23stop(Pid) ->24 gen_server:stop(Pid).25 26%% ── gen_server Callbacks ─────────────────────────────────────────────────────27 28%% @doc Initializes internal state map with initial battery and zeroed packet counts.29init([InitialBattery]) ->30 InitialState = #{31 battery_pct => InitialBattery,32 packets_sent => 0,33 total_bytes => 034 },35 {ok, InitialState}.36 37%% @doc Handles synchronous call requests.38handle_call(get_status, _From, State) ->39 {reply, {ok, State}, State};40handle_call(_Request, _From, State) ->41 {reply, {error, unknown_call}, State}.42 43%% @doc Handles asynchronous fire-and-forget cast messages.44handle_cast({record_packet, ByteCount}, State = #{packets_sent := Pkts, total_bytes := Bytes}) ->45 NewState = State#{46 packets_sent := Pkts + 1,47 total_bytes := Bytes + ByteCount48 },49 {noreply, NewState};50handle_cast(_Msg, State) ->51 {noreply, State}.52 53%% @doc Handles out-of-band signals and raw process messages.54handle_info(_Info, State) ->55 {noreply, State}.56 57%% @doc Cleans up server resources upon termination.58terminate(_Reason, _State) ->59 ok.60 61%% @doc Transforms state across hot code releases.62code_change(_OldVsn, State, _Extra) ->63 {ok, State}.Architectural Deep Dive: What the BEAM is Doing
- Step 1: Inversion of Control & Process Initialization (
init/1)
When device_telemetry:start_link(100) is called, the calling process invokes gen_server:start_link/3. The OTP engine allocates a new BEAM process, atomically links it to the caller, and synchronously invokes device_telemetry:init([100]) in the child process. The child constructs its initial state map (#{battery_pct => 100, packets_sent => 0, total_bytes => 0}) and returns {ok, InitialState}. The OTP engine completes the handshake and returns {ok, ChildPid} to the caller.
- Step 2: Non-Blocking Asynchronous Telemetry Ingestion (
handle_cast/2)
Calling device_telemetry:record_packet(Pid, 64) evaluates gen_server:cast(Pid, {record_packet, 64}). The OTP engine delivers a special tagged tuple {'$gen_cast', {record_packet, 64}} directly into Pid's mailbox and immediately returns ok to the caller. When the server process reaches this message in its mailbox, the OTP engine invokes handle_cast/2. The callback updates its byte count and packet tally, returning {noreply, NewState}.
- Step 3: Synchronous Request-Reply Lifecycle (
handle_call/3)
Calling device_telemetry:query_status(Pid) evaluates gen_server:call(Pid, get_status). The caller sets up a monitor on Pid, generates a unique reference MRef, transmits {'$gen_call', {self(), MRef}, get_status}, and suspends in a selective receive. The server receives the call, invokes handle_call(get_status, From, State), and returns {reply, {ok, State}, State}. The OTP engine sends {MRef, {ok, State}} back to the caller and flushes the monitor.
- Step 4: Live System Introspection via System Protocol Messages (
sys:get_state/1)
When an operator or monitoring tool calls sys:get_state(Pid), the system library transmits a tagged system message {system, From, get_state}. The OTP gen_server engine intercepts this message before invoking normal domain callbacks, queries its internal State variable, and sends the raw state map back to the caller without stopping or modifying the process.
Inspecting Live State in Production
Because device_telemetry implements the standard gen_server behaviour, operators in an Erlang shell or telemetry dashboard can inspect its live metrics at any time without disturbing active packet streams:
1%% In the Erlang shell:2{ok, Pid} = device_telemetry:start_link(95),3device_telemetry:record_packet(Pid, 128),4LiveState = sys:get_state(Pid).5%% => #{battery_pct => 95, packets_sent => 1, total_bytes => 128}Assignment Specification
This is a Guided Runnable Demo. The code in the editor is already fully operational.
- Inspect the pre-written
otp_intro_demomodule in the editor. - Review the structured function definitions below.
- Click
Runbelow to execute the demo and observe the live lifecycle!
1. start_link/0
- Input: None.
- Behavior: Starts and links a
gen_serverprocess executing theotp_intro_democallback module. Initializes internal state withcounterset to0andopstally set to0. - Examples:
otp_intro_demo:start_link()returns{ok, <0.210.0>}.
2. increment/2
- Input: Process identifier
Pid, integerAmount. - Behavior: Asynchronously casts an increment message to
Pid, increasing the internalcounterbyAmountand incrementing theopscount by 1 without blocking the caller. - Examples:
otp_intro_demo:increment(Pid, 10)returnsok.
3. get_count/1
- Input: Process identifier
Pid. - Behavior: Synchronously queries the current integer
countervalue viagen_server:call/2, incrementing the internalopstally by 1. - Examples:
otp_intro_demo:get_count(Pid)returns35.
4. stop/1
- Input: Process identifier
Pid. - Behavior: Synchronously commands the server to terminate cleanly via
gen_server:stop/1. - Examples:
otp_intro_demo:stop(Pid)returnsok.
5. run_demo/0
- Input: None.
- Behavior: Orchestrates the complete demonstration lifecycle:
- Starts the server via
start_link/0. - Issues two asynchronous increments:
increment(Pid, 10)andincrement(Pid, 25). - Pauses briefly (15ms) to permit asynchronous casts to settle in the server mailbox.
- Queries the count with
get_count(Pid). - Inspects live internal state using
sys:get_state/1. - Stops the server with
stop(Pid). - Returns a summary map containing
final_countandlive_state.
- Examples:
otp_intro_demo:run_demo()returns#{final_count => 35, live_state => #{counter => 35, ops => 3}}.
Rules & Verification Constraints
- Must export
start_link/0,increment/2,get_count/1,stop/1, andrun_demo/0. - Must export all 6 mandatory
gen_servercallbacks:init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2, andcode_change/3. - Must verify live state using
sys:get_state/1. - Must invoke
gen_server:start_link/3,gen_server:call/2, andgen_server:cast/2.
Supervisor child order: [1. table_heir, 2. pricing_cache (owns ETS), 3. order_gateway]. Pricing cache holds active ETS table.
gen_server:start_link(Mod, Args, Opts) -> {ok, Pid} | {error, Reason}gen_server:call(ServerRef, Request) -> Replygen_server:cast(ServerRef, Request) -> oksys:get_state(Pid) -> StateWhy is writing raw spawn and receive loops considered an anti-pattern in production Erlang systems?
%% Raw Process Loop:
loop(State) ->
receive Msg -> loop(handle(Msg, State)) end.These rules are verified by bf_ast_verifier:verify_rules/3 on every Submit.
No Tests Executed Yet
Tap Run Tests below to compile your code and inspect Erlang term diffs.