Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 48 ยท Concurrency and OTP

Links, Monitors and Let It Crash

Learn how Elixir processes find out about each other's failures with spawn_link, Process.monitor and trap_exit, and why 'let it crash' works.

Processes are isolated, so when one crashes the others keep running. That is useful, but it raises a question: who finds out? If a worker dies in silence, nobody can restart it or clean up after it. Elixir answers with two mechanisms, links and monitors, that let processes observe each other's deaths.

Together they support Erlang's famous philosophy: let it crash. Instead of wrapping every line in defensive checks, you write the happy path and let a supervisor deal with failure. This lesson builds the foundation for GenServer and Supervisors. As before, real Elixir blocks are read-only, and the editors use a JavaScript model of exit signals.

Two ways to watch a process

Link Two-way. If one dies, the other dies too.
Monitor One-way. You get a message when it dies.

Links share fate; monitors only report it.

1 / 2

What happens when a process crashes

A process ends when its function returns (reason :normal) or when something goes wrong: an unhandled exception, a failed match, an explicit exit/1. The reason travels with the death. Without a link or monitor, nothing else is told.

ELIXIR
pid = spawn(fn -> raise "boom" end)
Process.sleep(100)
IO.inspect(Process.alive?(pid))   # false

The VM logs an error report, and the spawning process carries on as if nothing happened. That is fault isolation at its simplest.

spawn_link/1 starts a process and links it to the caller in one atomic step. Links are bidirectional. When either end exits for a reason other than :normal, it sends an exit signal to everyone linked to it, and by default that signal kills them too.

ELIXIR
spawn_link(fn ->
  Process.sleep(50)
  raise "worker failed"
end)

Process.sleep(500)
IO.puts("this line is never reached")

The worker crashes and the exit signal takes down the caller. In an IEx shell the shell restarts for you, which is why this looks harmless there; in a script the whole program ends. Why is this good? A group of processes that depend on each other should all fail together, so nothing keeps running in a half-broken state. A normal exit (:normal) does not propagate.

You can also link an existing process with Process.link/1, and remove the link with Process.unlink/1.

Trapping exits

A process can ask to receive exit signals as ordinary messages instead of dying. This is called trapping exits:

ELIXIR
Process.flag(:trap_exit, true)

pid = spawn_link(fn -> exit(:oops) end)

receive do
  {:EXIT, ^pid, reason} -> IO.puts("worker exited: #{inspect(reason)}")
end

This prints worker exited: :oops. The message has the shape {:EXIT, pid, reason}, which you match with the pin operator to pick the right child. Supervisors work exactly this way: they trap exits, link to their children and react when an :EXIT message arrives.

One exception: Process.exit(pid, :kill) cannot be trapped. The target dies and its links see the reason :killed.

Trapping exits is a tool for processes that manage others. Ordinary workers should not trap exits, or they will refuse to die with their parents.

Monitors: watching without sharing fate

Process.monitor/1 is the gentler option. It returns a reference and arranges for you to get one message when the target process ends, with no effect on your own life:

ELIXIR
pid = spawn(fn -> Process.sleep(50) end)
ref = Process.monitor(pid)

receive do
  {:DOWN, ^ref, :process, ^pid, reason} ->
    IO.puts("process ended: #{inspect(reason)}")
end

The :DOWN message carries the reference, the pid and the exit reason (:normal here). A monitor is one-way and you can create many on the same process; each gets its own message. If the target is already dead when you monitor it, you get :DOWN immediately with the reason :noproc, so there is no race. spawn_monitor/1 starts and monitors in one step. Use Process.demonitor(ref, [:flush]) to stop watching and drop a pending message.

Link Monitor
Direction Both ways One way
Default effect of a crash Kills the other side Sends :DOWN message
Can be stacked No (one link per pair) Yes, many references
Typical use Supervision, groups that must live together Clients waiting for a server
flowchart LR
    S["Supervisor<br/>(traps exits)"] -- link --> W1["Worker A"]
    S -- link --> W2["Worker B"]
    W2 -. "{:EXIT, pid, reason}" .-> S

A supervisor links to its workers and receives an EXIT message when one dies.

Let it crash

With these tools, the style of Elixir code changes. Instead of this:

ELIXIR
def handle(request) do
  try do
    do_work(request)
  rescue
    _ -> {:error, :something_went_wrong}
  end
end

you usually write only do_work(request), and let a failure end the process. A supervisor starts a fresh one in a known good state. The reasoning:

  • You cannot predict every failure, and half-handled errors leave corrupt state behind.
  • A restart is cheap because processes are cheap.
  • Error handling code is itself code that can be wrong; fewer branches mean fewer bugs.

"Let it crash" does not mean ignoring expected errors. A missing file or invalid user input is normal and is best returned as {:error, reason}, as you will see in Error Handling. Crash on the unexpected; handle the expected.

A JavaScript model of exit signals

The editors below simulate a tiny process world in JavaScript. It is not asynchronous and has no real scheduler: signals are delivered immediately, so output is deterministic. Real Erlang signals are asynchronous messages, and the details (such as signal ordering across processes) are richer than this model.

JS Links and trapping exits (JavaScript stand-in)

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

No output.

Case 1 is the default: the crash travels over the link. Case 2 shows that a trapping process survives and finds an EXIT message in its mailbox. Case 3 shows that :normal is harmless.

The second model adds monitors and shows fault isolation: only linked processes share a fate.

JS Monitors and fault isolation (JavaScript stand-in)

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

No output.

db, cache and web form a chain of links, so they die together. logger has no link to them and is unaffected until it crashes itself, and admin merely collects DOWN messages and stays alive.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Process A is linked to process B. B crashes with reason :boom. What happens to A by default?

    Links are bidirectional and an abnormal exit sends an exit signal that terminates the linked process unless it traps exits.
  2. 2. What does a process that called Process.flag(:trap_exit, true) receive when a linked process dies?

    Trapped exit signals are turned into {:EXIT, pid, reason} messages. The :DOWN shape belongs to monitors.
  3. 3. Which statement about monitors is true?

    Monitors are one-way and stackable. The watcher just gets a :DOWN message with the reason.
  4. 4. Which situation fits 'let it crash' best?

    Expected problems become {:error, reason} results. Unexpected, state-corrupting failures are best handled by crashing and restarting clean.
  5. 5. What does an exit with reason :normal do to linked processes that do not trap exits?

    A :normal exit is not propagated through links to processes that are not trapping exits.

Summary

  • A crashing process is isolated: unless linked or monitored, nobody else notices.
  • spawn_link/1 creates a two-way link; an abnormal exit kills the linked process unless it traps exits.
  • With Process.flag(:trap_exit, true) you receive {:EXIT, pid, reason} messages instead.
  • Process.monitor/1 is one-way and delivers {:DOWN, ref, :process, pid, reason}.
  • :normal exits do not propagate; :kill cannot be trapped.
  • Let it crash for unexpected failures, and return {:error, reason} for expected ones.

Next up: Keeping State in a Process.