Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 10 — Phoenix & LiveView

Phoenix is the flagship of the Web domain — and for Erlang developers it is the most natural fit in the ecosystem: its real-time model maps directly onto BEAM concepts you already use.

The chapter’s core claim, proven below: LiveView is a GenServer whose mailbox receives DOM events and whose “reply” is a diffed UI update.

10.1 The Architecture Is OTP

flowchart TD
    PHX["Phoenix"] --> LV["LiveView"]
    PHX --> CH["Channels"]
    PHX --> PS["PubSub"]
    LV --> P["BEAM processes"]
    CH --> P
    PS --> P
    P --> S["Stateful"]
    P --> C["Concurrent"]
    P --> I["Isolated<br/>fault-tolerant"]

LiveView, Channels, and PubSub are thin layers over processes. The three properties at the bottom come from the runtime, not framework code.

Stateful

Each browser tab gets a dedicated LiveView process:

flowchart TD
    B["Browser"] <-->|"WebSocket"| LVP["LiveView process"]
    LVP --> ST["state (assigns)"]
    LVP --> TM["timers (:timer.send_interval)"]
    LVP --> SUB["subscriptions (Phoenix.PubSub)"]
    LVP --> EV["UI events (handle_event)"]

You don’t reconstruct application state from every HTTP request. The state lives in the process — exactly like a GenServer’s loop data. Refresh the page and the process dies; that’s your “session” boundary, enforced by the VM rather than by cookies.

Concurrent

flowchart TD
    BEAM["BEAM scheduler pool"] --> UA["User A → LiveView process"]
    BEAM --> UB["User B → LiveView process"]
    BEAM --> UC["User C → LiveView process"]
    BEAM --> ROOM["Chat room → GenServer"]
    BEAM --> PRESENCE["Presence → :pg / Phoenix.Presence"]
    BEAM --> NOTIF["Notifications → GenServer"]

One process per connection. The scheduler spreads millions of them across all cores preemptively. No event loop that one slow handler can block — a slow user’s render cannot stall another user’s events, because they aren’t sharing a thread.

Fault Tolerant (Isolated)

flowchart LR
    CRASH["process crashes"] --> EXIT["supervisor notices<br/>(:EXIT message)"]
    EXIT --> RESTART["process restarted<br/>(per restart strategy)"]
    RESTART --> OK["system continues<br/>— other users untouched"]

If one user’s connection crashes, only that process restarts under Phoenix.Endpoint’s supervision — everyone else is untouched. This is your let-it-crash philosophy with a browser attached.

Distributed

flowchart LR
    NA["Node A"] <--> PUBSUB["Phoenix.PubSub<br/>(Erlang distribution)"]
    NB["Node B"] <--> PUBSUB
    NC["Node C"] <--> PUBSUB

Phoenix.PubSub broadcasts across nodes via standard Erlang distribution. No Redis, no external message bus needed for cluster-wide real-time. Your net_kernel knowledge transfers directly — same cookie, same connect calls.

Where the Processes Live

Two facts worth having on hand when something misbehaves:

  • Your LiveView module runs in its own process, spawned per tab beneath the endpoint’s supervision. Crash it and the client reconnects and remounts fresh; the transport and every other user survive untouched.
  • PubSub rides on :pg — Erlang process groups, OTP 23+. Presence (§10.5) layers replica-consistent metadata on exactly that machinery.

The raw Erlang baseline shows what you stop maintaining. With cowboy_websocket you own the registry, heartbeat, and fan-out yourself:

%% you track peers, pings, and broadcasts by hand:
websocket_handle({text, Msg}, State) ->
    ring_broadcast(peers(), Msg),          % your own registry walk
    {ok, State}.

Phoenix hands you the registry (PubSub.subscribe/2), the heartbeat, the diffing, and recovery — all as ordinary supervised processes you can find in Observer.

10.2 Stateless Web vs LiveView

Traditional: every request pays deserialize → authorize → fetch state → compute → serialize, with state parked in DB/Redis/session store.

sequenceDiagram
    participant Br as Browser
    participant Ct as Controller (stateless)
    participant St as DB / Cache / Redis
    Br->>Ct: HTTP request
    Ct->>St: fetch session/state
    St-->>Ct: state
    Ct-->>Br: response (state rebuilt every time)

LiveView: persistent connection; state lives with the process; events are messages; workers and other nodes are just more processes.

flowchart TD
    BR["Browser"] <-->|"WebSocket (persistent)"| LVP["LiveView process<br/>assigns · timers · subscriptions · handle_event"]
    LVP -->|"BEAM messages"| PS["PubSub<br/>other nodes"]
    LVP -->|"BEAM messages"| WK["Workers<br/>background jobs"]

The performance consequence: after mount/3, event handling costs no HTTP round trip and no state reconstruction — you’re just sending a message to a process that already holds everything it needs.

Assigns Diffing: What Actually Crosses the Wire

After each event, LiveView re-renders your template against the new assigns and compares with the last result. Only changed fragments travel:

  1. HEEx compiles templates into static chunks (sent once per page load) and dynamic holes (functions of assigns).
  2. After handle_event/3 returns, the new render fills the holes; the runtime diffs hole-by-hole.
  3. Only indices whose values changed serialize into the message — typically tens of bytes rather than an HTML document.

Rendering cost therefore lives in your process and scales with what changed, not what the page contains. Two disciplines follow directly: keep socket.assigns minimal (every assign participates in diffing), and never park large blobs there — streams (§10.5) and external processes are the right homes for collections and heavy data.

10.3 How Phoenix Generates HTML

Templates in Phoenix are not parsed at request time. Every .html.heex file is compiled to an ordinary Elixir function at build time — the same transformation your Erlang knowledge would predict for any serious template system: partial evaluation into code that builds iodata. (If you ever used erlydtl, which compiles Django templates to Erlang modules, you already hold the mental model.)

The full path of a request’s HTML

flowchart LR
    R["Plug router"] --> C["Controller action<br/>assigns data"]
    C --> RD["render(conn, :show, ...)<br/>dispatches by format"]
    RD --> T["Compiled template fn<br/>assigns → iodata"]
    T --> L["Layout component<br/>wraps content"]
    L --> P["Plug.Conn response<br/>iodata → socket"]
  1. The controller puts data into conn.assigns.
  2. render/3 looks up the compiled template for the format. Phoenix 1.7+ takes an atom (render(conn, :show, user: user)) and resolves the template module from the controller; the older string form render(conn, "show.html") is pre-1.7 and you will not meet it in new Phoenix apps.
  3. The template function takes the assigns and returns iodata — nested lists of binaries, the same structure as io_lib:format/2 output.
  4. The layout wraps it; Plug.Conn sends the iodata straight to the socket without flattening.

EEx vs HEEx

EEx (.html.eex)HEEx (.html.heex)
What it isTemplate literal with <%= %> holesEEx + HTML-aware compiler
HTML validationnone — output is a string souptags/attributes validated at compile time
Componentspartials via string renderingfunction components <.my_component />
Escapingmanual html_escapeautomatic — values are escaped unless wrapped in raw/1

HEEx knows HTML syntax. That single fact buys three things: malformed markup fails at compile time; every interpolated value is escaped by default (XSS safety is the default, not a discipline); and tags can compile to function components — any def component(assigns) in a module becomes reusable markup invoked as <.component attr={value} />.

What a template compiles to

A template like this:

<section id={@id}>
  <h1>{@title}</h1>
  <p :for={item <- @items}>{item.name}</p>
</section>

compiles (conceptually — the real code is expanded by macros at compile time) into something shaped like:

def render(assigns) do
  [
    "<section id=\"",
    Phoenix.HTML.safe_to_string(to_safe(assigns.id)),
    "\">\n  <h1>",
    Phoenix.HTML.safe_to_string(to_safe(assigns.title)),
    "</h1>\n",
    Enum.map(assigns.items, fn item ->
      ["<p>", Phoenix.HTML.safe_to_string(to_safe(item.name)), "</p>"]
    end),
    "</section>"
  ]
end

Three properties fall out of this shape:

  • Rendering is just building a list. No interpreter walks a DOM; the template is the code, and the BEAM compiles it like any other.
  • Static parts are binaries evaluated once per call — which is what LiveView exploits for diffing (§10.2): the static chunks are shared, only the dynamic holes re-evaluate.
  • Escaping is inline and unconditional — each hole passes through Phoenix.HTML safe conversion, so injecting <script> in @title renders literal text.

From Erlang you know

Erlang worldPhoenix world
erlydtl compiling Django templates to modulesHEEx compiling templates to Elixir functions
io_lib:format/2 → iodataevery render returns iodata
xmerl structural checksHEEx compile-time tag/attribute validation
manual escaping before outputautomatic Phoenix.HTML safe conversion

Where LiveView fits

render/1 in a LiveView uses the same HEEx compiler — the only difference is the caller: a controller renders once per request, a LiveView re-renders per event into the diffing pipeline of §10.2. Components (<.component />) work identically in both, which is why the generated mix phx.new --live app shares one CoreComponents module between controller views and LiveViews.

10.4 The Minimal Mental Model

A LiveView is a GenServer whose “messages” include DOM events and whose “reply” is a diffed UI update:

# Conceptual model:
state = %{users_online: 42}

event = {:user_joined, "alice"}

case event do
  {:user_joined, _user} -> %{state | users_online: state.users_online + 1}
end
# receive event → update state → render changes

Real LiveViews add handle_event/3, handle_info/2, and assign/3 — but the loop shape is gen_server:handle_call with rendering attached. If you can write the GenServer above from memory (you can), you understand LiveView.

The Lifecycle in Callback Terms

The full callback surface, mapped to what each message means:

CallbackFires whenGenServer analogue
mount/3connection established; again on reconnectinit/1
render/1after any state changereply, rendered
handle_event/3DOM event arriveshandle_call from a browser
handle_info/2any BEAM messagehandle_info
handle_params/3URL params changehandle_call variant
terminate/2process exitsbest-effort cleanup

terminate/2 deserves the caution flag it gets in Ch 23: it is not reliable unless the process has Process.flag(:trap_exit, true) set. A LiveView killed by the supervisor’s brutal_kill, or any untrapped exit, skips it entirely. Put anything that must happen on a schedule or in a DynamicSupervisor, not in terminate/2.

One click, end to end:

sequenceDiagram
    participant Br as Browser
    participant LVP as LiveView process
    Br->>LVP: phx-click="inc"
    LVP->>LVP: handle_event → assign(count + 1)
    LVP-->>Br: diff {count: 41} — changed holes only
    Note over Br: DOM patched in place,<br/>no page reload

Note that mount/3 runs twice per tab: once during the initial HTTP render (connected?(socket) is false) and once when the WebSocket connects. Timers and subscriptions belong behind the connected?/1 check so static HTML generation stays side-effect free.

10.5 Step-by-Step: First Real-Time App

mix phx.new realtime_demo --live     # generates app + LiveView setup
cd realtime_demo
mix ecto.create && mix ecto.migrate  # optional if you keep the DB (Ch 11)
mix phx.server                       # http://localhost:4000

The generated app is a textbook OTP release: RealtimeDemo.Application starts Telemetry → PubSub → Endpoint under one supervisor. Open Observer (:observer.start() in iex -S mix phx.server) and find the LiveView process appear/disappear as you open and close browser tabs. Watching that correlation once teaches more than any diagram.

Add a cluster-wide broadcast in two lines:

  1. use YourAppWeb, :live_view in any LiveView module.
  2. Phoenix.PubSub.subscribe(YourApp.PubSub, "room") in mount/3 (behind connected?/1).
  3. Broadcast from anywhere: Phoenix.PubSub.broadcast(YourApp.PubSub, "room", {:user_joined, user}). Every connected tab receives it in handle_info/2.

That is PubSub — fire-and-forget, no state. When you also want who is connected (counts, join/leave diffs, deduplicated rejoins), that is Phoenix.Presence, which is a CRDT-backed wrapper on the same PubSub topic:

# application.ex — Presence must be supervised, after PubSub, before Endpoint
children = [
  {Phoenix.PubSub, name: YourApp.PubSub},
  YourAppWeb.Presence,   # the `use Phoenix.Presence` module
  YourAppWeb.Endpoint
]

# LiveView
def mount(_params, _session, socket) do
  if connected?(socket) do
    YourAppWeb.Presence.track(self(), "room", socket.id, %{online_at: System.system_time(:second)})
  end
  {:ok, assign(socket, :room, "room")}
end

def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff"}, socket) do
  {:noreply, assign(socket, :users, YourAppWeb.Presence.list("room"))}
end

Distinguish the two directions before you build on them: push_event/3 goes server → a specific browser’s JS (it is a client-side hook, not a cluster message), while Phoenix.PubSub.broadcast/3 goes node → node and lands in handle_info/2.

Background work from a LiveView uses supervised tasks — never bare spawn. The Task.Supervisor has to be in the tree first:

# application.ex
children = [
  RealtimeDemo.Repo,
  {Task.Supervisor, name: RealtimeDemo.TaskSup},   # required
  {Phoenix.PubSub, name: RealtimeDemo.PubSub},
  RealtimeDemoWeb.Endpoint
]

Then, in the LiveView. Note the task receives a user_id, not socket.assigns.user: the socket is LiveView-shaped state and has no business crossing into a worker process.

def handle_event("export", %{"user_id" => user_id}, socket) do
  task = Task.Supervisor.async_nolink(RealtimeDemo.TaskSup, fn ->
    HeavyExport.run(user_id)
  end)

  {:noreply, assign(socket, :export_task, task)}
end

def handle_info({ref, :ok}, %{assigns: %{export_task: %Task{ref: ^ref}}} = socket) do
  Process.demonitor(ref, [:flush])          # normal-task result arrives twice
  {:noreply, put_flash(socket, :info, "Export finished")}
end

def handle_info({:DOWN, ref, :process, _, reason},
                %{assigns: %{export_task: %Task{ref: ^ref}}} = socket) do
  {:noreply, put_flash(socket, :error, "Export failed: #{inspect(reason)}")}
end

Two details that are load-bearing:

  • The :DOWN clause matches the ref against socket.assigns.export_task. A catch-all def handle_info({:DOWN, _ref, ...}, socket) fires for every monitor this process happens to hold — including Phoenix’s own — and will report someone else’s crash as your export failing.
  • async_nolink means a crashing export does NOT crash the user’s LiveView; the crash arrives as a :DOWN message you choose how to handle.

No client framework, no separate websocket server — the supervision tree handles lifecycle.

Streams: Large Collections Without Assign Bloat

The old habit — stuffing thousands of rows into assigns — costs memory twice: in your process and in client-side bookkeeping. Streams fix both ends with per-item operations that bypass regular assigns entirely:

# Load a page, not the table. `stream/3` still materializes whatever you hand
# it, so 50_000 rows here would still be 50_000 rows in the LiveView process.
def mount(_params, _session, socket) do
  {:ok, stream(socket, :logs, Logs.recent(200))}
end

def handle_info({:new_log, log}, socket) do
  {:noreply, stream_insert(socket, :logs, log, at: 0)}
end
<tbody id="logs" phx-update="stream">
  <tr :for={{id, log} <- @streams.logs} id={id}>
    <td>{log.level}</td>
    <td>{log.message}</td>
  </tr>
</tbody>

(HEEx prefers {...} interpolation, but it is EEx-based and <%= ... %> still compiles inside a .heex template; new code uses {}.)

(Stream items render as {id, item} pairs and each DOM node must carry the matching id attribute — LiveView raises on a stream container whose children lack ids.)

One lifecycle rule to internalize: a stream is rebuilt from scratch on every mount. Navigate away and back, and your placeholder rows are gone until mount/3 loads again. Any cursor, filter, or scroll position you want to survive a remount has to be in the URL params or session and reapplied in mount/3 — streams buy you efficient updates, not persistent state.

Properties worth internalizing:

  • Streamed items never enter socket.assigns — server memory stays O(batch), not O(collection).
  • stream_insert/4 with at: 0 prepends; the client moves one DOM node instead of re-rendering the list.
  • Streams reset on remount. They are view state, not truth — reload from source in mount/3.

Rule of thumb: assigns for scalar and summary state; streams for collections the user scrolls.

10.6 Why This Wins for Real-Time Workloads

PropertyWhy It Matters
StatefulConnection state lives with the process
ConcurrentConnections naturally isolated
Fault tolerantSupervisors restart failed components
DistributedBEAM nodes coordinate across cluster
Real-timeWebSockets/Channels/PubSub first-class
ObservableTelemetry + process introspection
ComposablePlug/PubSub/behaviours assemble cleanly

Natural fits: chat & messaging, collaborative docs/whiteboards, multiplayer, live dashboards (trading/sports), location tracking, notifications, IoT control planes.

Phoenix isn’t just a web framework that added WebSockets. It is a web architecture built on a runtime whose fundamental abstraction is already concurrent, stateful, isolated processes.

10.7 Telemetry: Watching the Machine Think

Phoenix emits :telemetry events at every interesting boundary — the same instrumentation convention you know from OTP libraries that wrap logger:

EventWhat it measures
[:phoenix, :endpoint, :stop]full request duration
[:phoenix, :live_view, :mount, :stop]time to first render per tab
[:phoenix, :live_view, :handle_event, :stop]event handling latency

(LiveView events are span-style: each has :start and :stop variants — attach to the :stop event to read its duration measurement.)

Attaching a handler is plain function registration:

:telemetry.attach(
  "lv-event-log",
  [:phoenix, :live_view, :handle_event, :stop],
  fn _event, measurements, metadata, _config ->
    # duration is in NATIVE time units, not milliseconds. Log raw
    # `measurements.duration` and it looks like a huge number.
    ms = System.convert_time_unit(measurements.duration, :native, :microsecond)
    Logger.debug("#{metadata.event} handled in #{ms}µs")
  end,
  %{}
)

That :native is a general telemetry fact, not a Phoenix quirk: every duration in every :telemetry.span/3 is in native units until you convert. Logging it raw is the single most common telemetry bug.

In production, Telemetry.Metrics aggregates the same events into console, StatsD, or Prometheus reporters — metrics without an agent process invented by you. Combined with Observer (§10.5) you get both micro views (one process) and macro views (fleet-wide rates) on day one.

Phoenix 1.7–1.8 specifics an Erlang reader will trip on

Four things a 1.5-era tutorial would have taught you that are now different:

OldCurrent
Cowboy as the endpoint serverBandit (1.7+ default)
render(conn, "show.html")render(conn, :show, assigns)
string paths for linksverified routes — ~p"/users/#{user}"
hand-rolled authmix phx.gen.auth

Verified routes are the one worth adopting immediately: ~p returns a *path* at compile time, so a renamed route is a compile error rather than a 404 in production. The compiler parses the sigil, so you get route existence and path-param count checked at compile time; query strings are URL-encoded and interpolated safely.

# verified
<%= link "Edit", to: ~p"/users/#{@user}/edit" %>
<.button navigate={~p"/users"}>All users</.button>

# unverified — still legal, still a runtime 404 if the route moved
<%= link "Edit", to: "/users/#{@user}/edit" %>

Auth is one command: mix phx.gen.auth Accounts User users generates sign-up, log-in, log-out, password reset, and confirmation-email flows against Accounts, plus a live_session block in the router that enforces authentication in on_mount — which is the LiveView-native way to guard a LiveView, and where Ch 27’s live_session explanation becomes load-bearing.

Explore More

  • Phoenix guides — start with “Request lifecycle” then “Channels”
  • LiveView docs — the assign/ handle_event lifecycle diagram is worth printing
  • Presence guide — CRDT-based presence built on PubSub; zero extra infra
  • Exercise idea: build the presence demo from §10.5, then kill a node (kill -9 the daemon!) and watch Presence update across survivors — fault tolerance as a spectator sport

Checkpoint

  1. What plays the role of GenServer state in a LiveView?
  2. How does an event reach LiveViews on other nodes?
  3. What happens to other users when one user’s LiveView crashes?
  4. Why Task.Supervisor.async_nolink instead of plain Task.async inside handle_event/3?
Answers
  1. socket.assigns — updated via assign/3; persisted across events for the connection’s lifetime.
  2. Phoenix.PubSub.broadcast/3 over Erlang distribution; subscribers’ handle_info/2 fires locally on each node.
  3. Only their own process restarts per the supervision strategy; others are unaffected.
  4. Task.async/1 links the task to the caller — a crash would take down the user’s whole LiveView. nolink isolates failures while still delivering results/:DOWN messages.

Next: Chapter 11 — Ecto: The Data Layer