Lesson 5 of 9 · 28m
LiveView State, Events, and Failure Modes
Model LiveView as a server-side process lifecycle, manage assigns carefully, handle events idempotently, and design reconnect behavior.
LiveView feels like cheating the first time you build a reactive page without writing a JavaScript state machine. Then production arrives: reconnects, stale events, double-clicks, expensive assigns, and users with terrible networks. The correct mental model is simple: a LiveView is a stateful server process rendering diffs to a client.
The lifecycle is server-first
LiveView renders through HTTP, then upgrades to a websocket. mount/3 initializes state, handle_params/3 reacts to navigation, render/1 emits markup, and event callbacks update assigns:
def mount(%{"room_id" => room_id}, _session, socket) do
room = Chat.get_room_for_account!(socket.assigns.account_id, room_id)
messages = Chat.list_messages(room, limit: 50)
{:ok, assign(socket, room: room, messages: messages)}
endAssigns are your rendering cost model
Every assign is data the diff engine may compare and transmit. Whole nested object graphs create oversized diffs and memory pressure. Keep assigns shaped for the view:
socket
|> assign(:room_id, room.id)
|> assign(:room_name, room.name)
|> assign(:messages, messages)Events are untrusted input
A client event is no more trustworthy than a form submission. Validate input and authorization inside the callback or the context it calls:
def handle_event("send_message", %{"body" => body}, socket) do
case Chat.post_message(socket.assigns.room_id, socket.assigns.account_id, body) do
{:ok, _message} -> {:noreply, assign(socket, :error, nil)}
{:error, reason} -> {:noreply, assign(socket, :error, reason)}
end
endNever trust a hidden user_id supplied by the browser. Identity belongs in authenticated connection state.
Double events and reconnects are normal
Users double-click, networks drop, and clients retry. If an event creates a record, duplication is a business invariant problem:
post message idempotency token or dedupe key
join room naturally idempotent by membership key
start export return existing job for same key
payment submit idempotency key, never blind retryWhen other users need updates, broadcast through PubSub and implement handle_info/2. Keep payloads small and explicit. A reconnect after deploy or network failure can remount thousands of LiveViews at once, so expensive mount queries are part of the availability design.
Field notes
handle_eventmust be fast; move slow work to a task or job and update asynchronously.- Do not store privileged object graphs in assigns merely because the client cannot inspect server memory.
- Authorize both initial mount and every event; joining once does not imply perpetual permission.
- Test disconnected behavior with throttled or dropped networks, not only the happy path.
- Streams help large collections, but their reset and update semantics differ from ordinary assigns.
Was this lesson helpful?