What is Phoenix Channels and how do WebSockets work in Elixir?
Answer
Phoenix Channels provide real-time, bidirectional communication over WebSockets (or long polling as fallback). Each connected client gets a dedicated BEAM process (lightweight, ~2KB) — a server handling 2 million concurrent connections uses only ~4GB RAM for the connection processes. Channel structure: Socket: the WebSocket connection handler. Channel: a topic-based room within a socket: defmodule MyAppWeb.RoomChannel do; use Phoenix.Channel; def join("room:" <> _id, _params, socket), do: {:ok, socket}; def handle_in("message", %{"body" => body}, socket) do; broadcast!(socket, "message", %{body: body}); {:noreply, socket}; end; end. Client connects: socket.channel("room:123").push("message", {body: "hello"}). Presence: built-in distributed user tracking — know who is online across multiple nodes. Discord used Phoenix Channels to serve 5 million concurrent WebSocket connections on a single server before needing to scale horizontally.
Previous
How do Elixir supervisors implement fault tolerance?
Next
What is Elixir's concurrency model compared to threads?