Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Channels and PubSub

Phoenix Presence: Who Is Online

Learn Phoenix.Presence: track and list users, understand metas and presence_diff, show an online list in LiveView and why it works across a cluster.

"Alice is online." "3 people are viewing this document." "Bob is typing..." These features look simple, but they are hard to build correctly. Users close laptops without logging out, phones lose signal, one person has three tabs open, and in a cluster, different people are connected to different servers. A naive "online users" table in the database goes stale the moment a server crashes.

Phoenix.Presence solves this for you. It tracks processes, not rows: when a tracked process dies for any reason, the entry disappears automatically, and every node in the cluster agrees on the state without a central database. This lesson shows the real API in read-only blocks and a runnable stand-in for the idea behind it.

Setting it up

Define a presence module and start it in your supervision tree, after PubSub:

ELIXIR
defmodule MyAppWeb.Presence do
  use Phoenix.Presence,
    otp_app: :my_app,
    pubsub_server: MyApp.PubSub
end

# application.ex
children = [
  MyApp.Repo,
  {Phoenix.PubSub, name: MyApp.PubSub},
  MyAppWeb.Presence,
  MyAppWeb.Endpoint
]

Presence uses PubSub underneath, which is why the order matters (see PubSub and Broadcasting).

Track, update, list

Three calls do the work. You track a process (usually self()) under a topic and a key (usually the user id), with a map of metadata:

ELIXIR
alias MyAppWeb.Presence

# start tracking: this process is present in "room:lobby" as user 42
{:ok, _ref} =
  Presence.track(self(), "room:lobby", "42", %{
    name: "Alice",
    online_at: System.system_time(:second)
  })

# change the metadata of an existing entry (e.g. typing indicator)
Presence.update(self(), "room:lobby", "42", fn meta -> Map.put(meta, :typing, true) end)

# read the current state
Presence.list("room:lobby")
#=> %{
#=>   "42" => %{metas: [%{name: "Alice", online_at: 1_760_000_000, typing: true}]},
#=>   "7"  => %{metas: [%{name: "Bob", online_at: 1_760_000_050}]}
#=> }

The result is a map from key to %{metas: [...]}. The value is a list of metas because the same key can be tracked by several processes at once, for example one user with two browser tabs. Each tab contributes one meta, and the user is "online" as long as the list is not empty. That is why showing a user means looking at the keys, not counting the metas.

When a tracked process exits, its meta is removed. Closing a tab ends the LiveView process, so the entry goes away without any terminate code.

Presence in a channel

In a channel you track after a successful join. The usual pattern sends after_join to yourself, because you cannot track inside join/3 directly:

ELIXIR
def join("room:lobby", _payload, socket) do
  send(self(), :after_join)
  {:ok, socket}
end

def handle_info(:after_join, socket) do
  {:ok, _} =
    Presence.track(socket, socket.assigns.user_id, %{
      name: socket.assigns.user_name,
      online_at: System.system_time(:second)
    })

  push(socket, "presence_state", Presence.list(socket))
  {:noreply, socket}
end

The client then keeps a local copy in sync using the Presence helper from phoenix.js: it receives presence_state (the full list) once and presence_diff events after each change:

JavaScript
import { Socket, Presence } from "phoenix";

const presence = new Presence(channel);
presence.onSync(() => {
  const names = presence.list((id, { metas: [first] }) => first.name);
  renderOnlineList(names);
});

Presence in LiveView

In a LiveView you subscribe to the topic, track the current process, and react to the diff:

ELIXIR
@topic "room:lobby"

def mount(_params, _session, socket) do
  user = socket.assigns.current_scope.user

  if connected?(socket) do
    Phoenix.PubSub.subscribe(MyApp.PubSub, @topic)
    {:ok, _} = Presence.track(self(), @topic, to_string(user.id), %{name: user.name})
  end

  {:ok, assign(socket, :online, list_online())}
end

def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff"}, socket) do
  {:noreply, assign(socket, :online, list_online())}
end

defp list_online do
  @topic
  |> Presence.list()
  |> Enum.map(fn {_id, %{metas: [meta | _]}} -> meta.name end)
  |> Enum.sort()
end

The presence_diff payload carries %{joins: %{...}, leaves: %{...}}. For a small list you simply re-read Presence.list/1. For large rooms, apply the diff to a stream instead.

How it works (the short version)

Each node keeps the entries of its own tracked processes and shares them with the others through PubSub using a conflict-free replicated data type (CRDT). There is no leader and no database. When nodes lose contact and reconnect, they merge their states and converge. Entries of processes that lived on a crashed node are removed once the other nodes notice it is gone. Because of that, Presence.list/1 is eventually consistent: it is right after a short delay, and perfect for "who is online", but not for anything that needs a strict guarantee, like a seat lock.

A runnable model

The stand-in below implements the data structure: a map from key to a list of metas, with one meta per "process". It computes joins and leaves diffs the way a presence server reports them, and shows that a user with two tabs leaves only when the last tab closes.

Node.js Keys, metas and presence_diff (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Typing indicators with update

Metadata changes should also be cheap. A typing indicator updates the meta of one key and broadcasts a presence_diff that lists the new meta as a join and the old one as a leave. The next model applies an update and renders a status line.

Node.js Updating metadata for a typing indicator (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real chat, you send the "typing" update from phx-keydown with a debounce, and clear it with a timer, so the server is not flooded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Phoenix.Presence track?

    When a tracked process exits, its entry disappears automatically, even after a crash.
  2. 2. Why is the value for a key a list of metas?

    Each tracked process adds a meta. The user is present while the list is not empty.
  3. 3. Which message tells a subscribed LiveView that someone joined or left?

    Presence broadcasts a presence_diff event on the topic whenever its state changes.
  4. 4. What consistency does Presence offer across nodes?

    Nodes merge their states without a central coordinator, so results converge shortly after changes.

Summary

  • Phoenix.Presence tracks processes under a topic and key with a map of metadata.
  • track/4, update/4 and list/1 are the core API; entries vanish when the process ends.
  • A key maps to a list of metas, so multi-tab users work correctly.
  • React to presence_diff in channels and LiveViews; it works across a cluster without a database.
  • It is eventually consistent: use it for "who is online", not for strict locks.

Next: Authentication with mix phx.gen.auth