Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Processes and Message Passing

Process loops and state

Learn how Erlang processes keep state without variables that change: tail-recursive receive loops, counters, servers, hot code loading, and clean shutdown.

Erlang variables never change, yet processes can hold state that changes over time. The trick is simple and beautiful: the state is an argument of a recursive function. Each time the loop handles a message it calls itself with the new state. The state lives exactly as long as the loop does.

The basic shape

ERLANG
-module(counter).
-export([start/0, increment/1, value/1, stop/1]).

start() ->
    spawn(fun() -> loop(0) end).

loop(Count) ->
    receive
        increment ->
            loop(Count + 1);
        {value, From, Ref} ->
            From ! {Ref, Count},
            loop(Count);
        stop ->
            ok
    end.

Every clause that wants to continue ends with a call to loop/1. This is a tail call: the last thing the function does is call itself, so the BEAM reuses the stack frame and the loop can run for years without growing. The stop clause simply returns, the function ends, and the process ends with it. Forgetting the recursive call in a clause is a classic bug: the process quietly dies after one message.

The public functions hide the protocol:

ERLANG
increment(Pid) ->
    Pid ! increment,
    ok.

value(Pid) ->
    Ref = make_ref(),
    Pid ! {value, self(), Ref},
    receive
        {Ref, N} -> N
    after 1000 -> {error, timeout}
    end.

stop(Pid) ->
    Pid ! stop,
    ok.

Callers never see messages; they use counter:increment(Pid). This interface function pattern keeps the protocol in one module and lets you change it later.

ERLANG
1> C = counter:start().
2> counter:increment(C), counter:increment(C).
3> counter:value(C).
2

Richer state: a key-value store

State can be any term. A map is natural for a small store:

ERLANG
loop(Store) ->
    receive
        {put, Key, Value} ->
            loop(Store#{Key => Value});
        {get, From, Ref, Key} ->
            From ! {Ref, maps:get(Key, Store, undefined)},
            loop(Store);
        {delete, Key} ->
            loop(maps:remove(Key, Store))
    end.

Because data is immutable, Store#{Key => Value} builds a new map and the old one is garbage collected. Concurrency is safe without locks: only this process ever touches Store, and it handles one message at a time. The mailbox is a natural queue of operations, so all updates are applied one after another in arrival order.

Several kinds of state

When state grows, use a record or a map with named fields instead of many arguments:

ERLANG
-record(state, {count = 0, started_at, last_seen}).

loop(#state{count = C} = S) ->
    receive
        ping -> loop(S#state{count = C + 1, last_seen = erlang:system_time(second)})
    end.

A state machine in a loop

Another typical use is a state machine, where the function name or an argument says which state you are in. This traffic light runs through its states by calling a different function for each:

ERLANG
red()    -> receive next -> green()  end.
green()  -> receive next -> yellow() end.
yellow() -> receive next -> red()    end.

OTP has a ready-made behaviour for this, gen_statem, which you will meet in gen_server and friends.

State lives in the loop

Tail call loop(NewState) at the end
One message at a time No locks needed
Immutable values New state, old one is garbage
Stop = do not recurse Function returns, process ends

A forgotten recursive call kills the process silently.

1 / 2

Hot code loading

A long-lived loop can also be upgraded without stopping. Calls written as ?MODULE:loop(State) (a fully qualified call) switch to the newest loaded version of the module, while a plain loop(State) call stays in the old one. That is the whole mechanism behind Erlang's famous live upgrades:

ERLANG
loop(State) ->
    receive
        upgrade ->
            ?MODULE:loop(State);        % jump to the new code, keep the state
        Msg ->
            loop(handle(Msg, State))
    end.

You only need this for hand-written loops; OTP behaviours handle it for you.

Run it: the counter and store as stand-ins

The following is JavaScript, not Erlang. A process is an async function whose "state" is a parameter that is passed on, mirroring loop(Count). The recursion becomes a while loop over a new state value.

JS Stand-in: counter loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: key-value store loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Non-tail recursion. loop(S) -> receive M -> X = loop(S2), X end keeps the stack growing. Call loop last.
  • Blocking the loop with a long computation. While busy, the process handles no messages. Spawn a worker for slow tasks.
  • Forgetting to return state in a clause: every branch must call loop(...) with the right state.
  • Putting a huge state in a message just to read one field; ask the process for the field instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does an Erlang process keep changing state if variables are immutable?

    The loop function calls itself with the updated state, so each iteration sees a new value.
  2. 2. What happens if a clause in the receive loop forgets to call the loop again?

    Nothing keeps the process alive except the loop; returning ends it.
  3. 3. Why does the loop not overflow the stack?

    A call in tail position is compiled into a jump, so the stack does not grow.
  4. 4. Why are no locks needed for the key-value store process?

    The state is private to one process, and its mailbox serialises all access.

Summary

  • State is an argument to a tail-recursive receive loop.
  • Every clause that continues must call the loop with the new state; omitting that ends the process.
  • Interface functions hide the message protocol from callers.
  • Immutable data plus a single-threaded mailbox gives lock-free consistency.
  • ?MODULE:loop(State) enables live code upgrades; OTP behaviours do this for you.

Next: Registered processes and the process dictionary