The BEAM and OTP in one page
The first lesson said that Elixir runs on the Erlang VM and that a process is the unit of work. This page makes those words concrete: what a process is, how two of them talk, what happens when one dies, and what OTP puts around the whole thing. Every idea here has a longer lesson later, and this one is the map.
A process is a small machine
The VM schedules processes itself, in the same way an operating system schedules threads, but a process here costs a few kilobytes instead of a stack of megabytes. A process has a pid, its own heap, its own mailbox, and no pointer into another process. It runs a function and ends when that function returns. Starting one is spawn/1:
isolation.exs
parent = self() crasher = spawn(fn -> Process.sleep(:infinity) end) worker = spawn(fn -> receive do {:ping, from} -> send(from, :pong) end end) ref = Process.monitor(crasher) Process.exit(crasher, :kill) receive do {:DOWN, ^ref, :process, ^crasher, reason} -> IO.puts("the crasher ended: #{inspect(reason)}") end send(worker, {:ping, parent}) receive do :pong -> IO.puts("the other process still answers") end
elixir isolation.exs
the crasher ended: :killed
the other process still answers
One process was killed and the other one kept working, because nothing is shared between them. The killing is not a normal end: the reason is :killed, while a function that simply returns ends with :normal. Process.monitor/1 is how a process watches another one without being linked to it: it asks the VM for one message when the watched process ends.
Messages and the mailbox
A process reaches another one by sending a message. The message is copied into the mailbox of the receiver, which is a queue, and the receiver takes messages out with receive. The sender does not wait: send/2 returns the message immediately, and the work happens in the receiver. This is asynchronous by default, which is why a request that needs an answer carries the pid of the sender:
- send(pid, message) puts one term into the mailbox of pid.
- receive do pattern -> body end takes the first message that matches the pattern.
- self() is the pid of the process that calls it, which is what a reply needs.
The program above uses all three: the child receives {:ping, from} and sends :pong back to the pid in from. A message that matches no pattern stays in the mailbox, and the processes chapter follows the mailbox that grows when nobody reads it.
A supervisor starts it again
A process that crashes is not a disaster, if something is watching it. A supervisor starts child processes, watches them, and starts a new one when a child dies. The child does not rescue its own errors; it lets them happen, and the supervisor decides what to do. This is what "let it crash" means in practice:
supervisor.exs
defmodule Counter do use Agent def start_link(_opts), do: Agent.start_link(fn -> 0 end, name: __MODULE__) def bump, do: Agent.get_and_update(__MODULE__, fn count -> {count + 1, count + 1} end) def crash, do: Agent.get(__MODULE__, fn _count -> raise "boom" end) end {:ok, supervisor} = Supervisor.start_link([Counter], strategy: :one_for_one) IO.puts("count: #{Counter.bump()}") IO.puts("count: #{Counter.bump()}") try do Counter.crash() catch :exit, _reason -> IO.puts("the call did not return") end IO.puts("count after the restart: #{Counter.bump()}") IO.inspect(Supervisor.count_children(supervisor))
elixir supervisor.exs
count: 1
count: 2
the call did not return
count after the restart: 1
%{active: 1, workers: 1, supervisors: 0, specs: 1}
The counter reached 2, the third call raised, and the supervisor started a fresh counter with 0. The caller saw an exit rather than a value, which is why the call sits in a try block. The supervisor also prints a crash report on the error stream, between the second and the third printed line; the time, the pids and the function index in it change on every run, so the block above leaves it out and the check does not compare it. This is one run of that report:
06:38:22.902 [error] GenServer Counter terminating
** (RuntimeError) boom
supervisor.exs:6: anonymous fn/1 in Counter.crash/0
(elixir 1.19.7) lib/agent/server.ex:16: Agent.Server.handle_call/3
(stdlib 6.2.2.5) gen_server.erl:2381: :gen_server.try_handle_call/4
(stdlib 6.2.2.5) gen_server.erl:2410: :gen_server.handle_msg/6
(stdlib 6.2.2.5) proc_lib.erl:329: :proc_lib.init_p_do_apply/3
Last message (from #PID<0.95.0>): {:get, #Function<1.96949460/1 in Counter.crash/0>}
State: 2
Client #PID<0.95.0> is alive
(stdlib 6.2.2.5) gen.erl:260: :gen.do_call/4
(elixir 1.19.7) lib/gen_server.ex:1139: GenServer.call/3
supervisor.exs:15: (file)
(elixir 1.19.7) src/elixir_compiler.erl:81: :elixir_compiler.dispatch/4
(elixir 1.19.7) src/elixir_compiler.erl:56: :elixir_compiler.compile/4
(elixir 1.19.7) src/elixir_compiler.erl:43: :elixir_compiler.maybe_fast_compile/2
(elixir 1.19.7) src/elixir_lexical.erl:17: :elixir_lexical.run/3
(elixir 1.19.7) src/elixir_compiler.erl:21: :elixir_compiler.quoted/3
Supervisor.count_children/1 is the report a supervisor gives about itself: one worker and one child specification, and no nested supervisors. The supervisors lesson builds a tree of several children and explains the restart strategies.
What OTP adds
OTP is the part of Erlang that turns this machinery into a library: ready-made behaviours for the processes a system needs, and a way to package, start and stop a whole application. The pieces a reader meets first are:
- GenServer: a process with a state and a set of callbacks. The Agent above is a small GenServer with its callbacks already written.
- Supervisor: a process whose only job is to start children and restart them, with a strategy that says what a failure takes down with it.
- An application: a mix.exs with an application/0 function, a supervision tree, and a start and stop command. mix compiles it, and mix release packages it.
- Tables and registries outside a process, as in :ets and Registry, for the data that outlives one process or needs a name.
None of this is a framework laid over the language: it is the standard library of the runtime, and an Elixir program uses it without a dependency. The OTP chapter of the course takes the four pieces one at a time.
The mistake: send never fails
Sending to a process that has already ended is not an error. The message is accepted, the sender continues, and nothing reports that the receiver is gone. A program that expects a reply and never checks for it waits on a mailbox that will never fill:
deadsend.exs
pid = spawn(fn -> :ok end) ref = Process.monitor(pid) receive do {:DOWN, ^ref, :process, ^pid, reason} -> IO.puts("the worker ended: #{inspect(reason)}") end send(pid, :hello) IO.puts("send/2 to a dead process returned")
elixir deadsend.exs
the worker ended: :normal
send/2 to a dead process returned
The monitor is what told the program the worker was gone. A real program watches its workers, or links to them, and treats a message that never arrives as a failure with a timeout. The processes lesson shows the timeout form of receive.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a process share with another process on the BEAM?
Answer
Nothing: it holds its own memory and reaches others by messages
Processes are isolated; a message is a copy, not a shared reference.
-
What does "let it crash" mean in an OTP system?
Answer
A process stops on an error and a supervisor starts a new one
The supervisor owns the recovery, so the worker does not need code for every failure.
-
What is OTP?
Answer
The Erlang library of behaviours and applications around processes
OTP ships with Erlang: GenServer, Supervisor, applications and the tools around them.
-
What does
Process.monitor/1do?Answer
It sends a message when the watched process ends
A monitor is a one-way watch: the caller receives a DOWN message when the process ends.
-
What does this program print?
pid = spawn(fn -> Process.sleep(:infinity) end) ref = Process.monitor(pid) Process.exit(pid, :kill) receive do {:DOWN, ^ref, :process, ^pid, reason} -> IO.inspect(reason) endAnswer
:killed
Process.exit/2 with :kill cannot be trapped and the monitor reports the reason :killed.
-
What does this program print?
pid = spawn(fn -> :ok end) ref = Process.monitor(pid) receive do {:DOWN, ^ref, :process, ^pid, _reason} -> IO.puts(Process.alive?(pid)) endAnswer
false
The DOWN message arrives after the process ended, so Process.alive?/1 is false.
-
What does this program print?
pid = spawn(fn -> :ok end) ref = Process.monitor(pid) receive do {:DOWN, ^ref, :process, ^pid, _reason} -> :ok end send(pid, :hello) IO.puts("sent")Answer
sent
send/2 accepts a message for a dead pid and returns it; only a monitor reports the death.
-
What does this program print?
Process.flag(:trap_exit, true) pid = spawn_link(fn -> exit(:boom) end) receive do {:EXIT, ^pid, reason} -> IO.inspect(reason) endAnswer
:boom
With trap_exit set, the linked exit arrives as an EXIT message instead of killing the caller.
-
What does this program do?
raise "boom"Answer
A RuntimeError, because the message is boom
raise/1 with a binary raises a RuntimeError carrying that message.
-
A supervisor starts a child with
strategy: :one_for_one. What happens when the child raises?Answer
The supervisor starts a new child, and the other children keep running
One-for-one restarts only the failed child; the rest of the tree is untouched.
Автор статьи: Arthur Isaev