Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Getting Started

Phoenix and the BEAM: Processes and Supervision

See how Phoenix applications use BEAM processes, the application supervision tree, the endpoint, the Ecto pool and PubSub to stay fast and fault tolerant.

Phoenix feels fast and stays up under load because of the platform below it. Understanding the BEAM (the Erlang virtual machine) turns many Phoenix design choices from mysterious into obvious: why each request is a process, why your app has a supervision tree, why a crash is not an emergency.

This lesson connects Elixir's process model to what happens inside a running Phoenix app. If processes are new to you, read processes and messages and supervisors first.

One process per request

The web server accepts a connection and starts a process to handle it. That process runs your plugs, router and controller from start to finish and then exits. Processes are tiny (a few kilobytes), start in microseconds and share no memory with each other. Consequences:

  • A slow request never blocks others: the scheduler gives every process a time slice.
  • An exception in a controller kills only that process. The user gets a 500 page; everyone else is unaffected.
  • There are no global request objects. Per-request state is just variables in that process.
flowchart TB
  S["Supervisor"] --> E["Endpoint"]
  E --> R1["Request process 1"]
  E --> R2["Request process 2"]
  E --> R3["Request process 3"]
  R2 -->|crash| X["only 2 dies"]

A crash in request 2 does not touch requests 1 and 3.

The application supervision tree

Open lib/blog/application.ex in your project:

ELIXIR
def start(_type, _args) do
  children = [
    BlogWeb.Telemetry,
    Blog.Repo,
    {DNSCluster, query: Application.get_env(:blog, :dns_cluster_query) || :ignore},
    {Phoenix.PubSub, name: Blog.PubSub},
    BlogWeb.Endpoint
  ]

  opts = [strategy: :one_for_one, name: Blog.Supervisor]
  Supervisor.start_link(children, opts)
end

Each child is a long-running process or a supervisor of processes:

  • Telemetry collects metrics.
  • Repo owns a pool of database connections.
  • PubSub is the message hub used by channels and LiveView.
  • Endpoint starts the web server and the code that serves requests.

With :one_for_one, if a child dies the supervisor restarts only that child. If the Repo crashes because the database hiccuped, it is restarted and reconnects without restarting the whole app. The order matters: children start top to bottom, so the Repo is ready before the endpoint accepts traffic.

Where your own processes go

Sooner or later you need a long-lived process: a cache, a rate limiter, a scheduler. Add it as a child:

ELIXIR
children = [
  Blog.Repo,
  {Phoenix.PubSub, name: Blog.PubSub},
  Blog.RateLimiter,          # a GenServer you wrote
  {Task.Supervisor, name: Blog.TaskSupervisor},
  BlogWeb.Endpoint
]

Use a GenServer (see GenServer) for state and a Task.Supervisor for fire-and-forget work such as sending an email without making the user wait:

ELIXIR
Task.Supervisor.start_child(Blog.TaskSupervisor, fn ->
  Blog.Mailer.deliver_welcome(user)
end)

If that task crashes, the supervisor logs it; the request that spawned it has already finished.

Do not start unsupervised processes with spawn inside controllers. They are invisible to the supervision tree, so crashes go unnoticed and shutdown is messy. Use Task.Supervisor or a supervised child instead.

The database pool

Elixir processes are cheap but database connections are not. Ecto keeps a pool (10 connections by default, set by pool_size). A request that needs the database checks one connection out, runs its query and checks it back in. If all connections are busy, the next caller waits in a queue. Hence two tuning rules: keep queries short, and size the pool for your database server's limit, not for the number of requests.

Let it crash

Erlang's philosophy is "let it crash": do not litter code with defensive checks for conditions you cannot recover from; let the process die and let a supervisor restart it in a clean state. In Phoenix this appears as:

  • Controllers pattern match on the data they expect. If %{"id" => id} is missing, the match fails and Phoenix returns an error response.
  • Repo.get!/2 raises if a record is missing, and Phoenix converts the Ecto.NoResultsError into a 404 automatically.

Handle expected failures (invalid form input, record not found for a user-facing page) with normal return values like {:error, changeset}. Reserve crashes for the unexpected.

A supervisor, modeled

The stand-ins below imitate processes (as objects that may fail) and a one_for_one supervisor.

JS one_for_one restart

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

No output.

Only Repo restarted. PubSub and Endpoint kept their state, which is the point of :one_for_one.

A connection pool, modeled

JS A pool of three connections

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

No output.

Requests 4 and 5 waited until a connection returned. In Phoenix the wait has a timeout; when it expires you see the familiar DBConnection.ConnectionError: connection not available message, a signal to speed up queries or raise pool_size.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when one request's process crashes in Phoenix?

    Processes are isolated, so a crash is contained to the one handling that request.
  2. 2. What does the :one_for_one strategy do?

    With one_for_one, only the child that terminated is restarted.
  3. 3. Where should a long-lived GenServer for your app be started?

    Adding it to the supervision tree makes it supervised, restartable and visible.
  4. 4. What is the Ecto pool for?

    Connections are expensive, so Ecto keeps a fixed pool that requests check out and return.

Summary

  • Each request runs in an isolated, cheap BEAM process, so crashes stay local.
  • application.ex defines the supervision tree: Telemetry, Repo, PubSub and Endpoint start in order and restart independently.
  • Add your own long-lived processes as supervised children; use Task.Supervisor for background work.
  • Handle expected errors with return values and let unexpected ones crash.

Next: Router and pipelines