Skip to content

Lesson 6 of 9 · 26m

Channels, Presence, and Authorization at the Edge

Use Phoenix Channels for room-scoped realtime communication, authenticate sockets, authorize topic joins, and design presence and broadcast behavior.

LiveView is ideal when the server owns a page's UI state. Channels are for explicit realtime protocols: chat rooms, multiplayer collaboration, presence lists, game events, or clients that need topic subscriptions independent of page rendering. They are simple to start and easy to authorize badly.

Socket authentication is not topic authorization

The socket authenticates the connection. Channel join authorizes the topic. Those are separate decisions:

channel "room:*", PulseWeb.RoomChannel

def connect(%{"token" => token}, socket, _connect_info) do
  case Pulse.Accounts.verify_socket_token(token) do
    {:ok, account_id} -> {:ok, assign(socket, :account_id, account_id)}
    :error -> :error
  end
end

def id(socket), do: "account_socket:#{socket.assigns.account_id}"

Authorize every join

def join("room:" <> room_id, _payload, socket) do
  if Chat.member?(socket.assigns.account_id, room_id),
    do: {:ok, assign(socket, :room_id, room_id)},
    else: {:error, %{reason: "not authorized"}}
end

Events are application inputs

def handle_in("message:new", %{"body" => body}, socket) do
  case Chat.post_message(socket.assigns.room_id, socket.assigns.account_id, body) do
    {:ok, message} ->
      broadcast!(socket, "message:new", %{id: message.id, body: message.body})
      {:reply, :ok, socket}
    {:error, reason} -> {:reply, {:error, %{reason: to_string(reason)}}, socket}
  end
end

The server creates trusted state before broadcasting. Clients must not speak as other users or invent trusted metadata.

Presence is ephemeral membership, not permission

Phoenix Presence replicates process membership across the cluster. It is excellent for "who appears online" and terrible for permissions, billing, or exact counts that must never be wrong.

{:ok, _} = Presence.track(socket, "room:" <> socket.assigns.room_id, socket.assigns.account_id, %{joined_at: System.system_time(:second)})

Fanout determines load

A broadcast to a room with 100,000 subscribers multiplies work across processes, nodes, serialization, sockets, and client devices. Large payloads amplify every hop. Throttle typing indicators, use small event types, and avoid handle_out/3 transformations that secretly perform expensive work for every subscriber.

Field notes

  • Test topic authorization with two accounts and proven object ownership.
  • Token revocation does not automatically terminate existing sockets unless your design supports it.
  • Do not broadcast whole database structs; build explicit event payloads.
  • Presence is not a mutex, lease, quorum, or permission system.
  • Measure fanout with realistic payload sizes and reconnecting clients.

Was this lesson helpful?

Sign in to rate