Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Channels and PubSub

Phoenix PubSub and Broadcasting

Use Phoenix.PubSub to push updates between processes: subscribe, broadcast, handle_info, broadcasting from contexts into LiveView, topic design and clusters.

Imagine two people with the same order page open. One of them marks the order as shipped. How does the other person's page update by itself? The database was changed by one process, but the other page lives in a different process, maybe even on a different server. Phoenix.PubSub is the answer: a small publish/subscribe system built into every Phoenix app. Processes subscribe to a topic, other code broadcasts a message to that topic, and every subscriber receives it in its mailbox.

Channels and LiveView both sit on top of PubSub. Knowing it directly lets you wire any part of your app to any other, without tangled dependencies. If mailboxes and receive are new to you, review Processes and Messages first. Real Phoenix code is read-only here; the editors model the behaviour in JavaScript.

The three functions

Phoenix starts a PubSub server for you. It is in application.ex:

ELIXIR
children = [
  MyApp.Repo,
  {Phoenix.PubSub, name: MyApp.PubSub},
  MyAppWeb.Endpoint
]

After that, three calls cover almost everything:

ELIXIR
# in any process that wants messages
Phoenix.PubSub.subscribe(MyApp.PubSub, "orders:42")

# anywhere: send to every subscriber of the topic
Phoenix.PubSub.broadcast(MyApp.PubSub, "orders:42", {:order_shipped, order})

# every subscriber's process then receives it as a normal message
def handle_info({:order_shipped, order}, state), do: ...

Variants: broadcast_from/4 skips one pid (so the sender does not get its own message), local_broadcast/3 delivers only on the current node, and broadcast!/3 raises on failure instead of returning {:error, reason}. unsubscribe/2 removes a subscription, and a process is also unsubscribed automatically when it exits, so there is no cleanup code to write.

A message can be any Elixir term. The convention is a tagged tuple, such as {:order_shipped, order}, so that handle_info/2 can pattern-match each kind on its own clause.

Broadcasting from a context

Where should broadcasts live? Not in controllers or LiveViews; they belong in the context next to the database change, so that every code path that changes data (a LiveView, a controller, a background job, an IEx session) notifies subscribers. A typical context module exposes subscribe/1 and hides the topic naming:

ELIXIR
defmodule MyApp.Orders do
  alias MyApp.Repo
  alias MyApp.Orders.Order

  def subscribe_order(order_id) do
    Phoenix.PubSub.subscribe(MyApp.PubSub, "order:#{order_id}")
  end

  def ship_order(%Order{} = order) do
    order
    |> Order.changeset(%{status: :shipped})
    |> Repo.update()
    |> broadcast_change(:order_shipped)
  end

  defp broadcast_change({:ok, order}, event) do
    Phoenix.PubSub.broadcast(MyApp.PubSub, "order:#{order.id}", {event, order})
    {:ok, order}
  end

  defp broadcast_change({:error, _} = error, _event), do: error
end

Notice the {:ok, order} / {:error, _} clauses: we broadcast only after a successful write, and the function still returns the same shape to its caller. The pipeline reads naturally with the pipe operator.

Receiving in LiveView

A LiveView is a process, so it can receive PubSub messages in handle_info/2. Subscribe only in the connected mount (see the lifecycle):

ELIXIR
def mount(%{"id" => id}, _session, socket) do
  order = Orders.get_order!(id)
  if connected?(socket), do: Orders.subscribe_order(order.id)
  {:ok, assign(socket, :order, order)}
end

def handle_info({:order_shipped, order}, socket) do
  {:noreply,
   socket
   |> assign(:order, order)
   |> put_flash(:info, "Your order has shipped!")}
end

The sender never knows how many pages are open. Ten viewers or none, ship_order/1 does the same work. That loose coupling is the strength of publish/subscribe.

For LiveView streams, broadcast the changed record and call stream_insert/3 in handle_info/2. The server never holds the list, and every viewer's DOM stays up to date.

A runnable model

This stand-in implements PubSub with subscribers, tagged messages and broadcast_from. Each "process" has a mailbox and a handle_info function. The context broadcasts only on success, as in the real code.

Node.js PubSub with a context broadcasting (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.

Topic design

A topic is just a string, so choose a naming scheme and keep it in one place:

Topic Who subscribes Typical message
"orders" admin dashboard {:order_created, order}
"order:42" pages showing order 42 {:order_shipped, order}
"user:7" all tabs of user 7 {:notification, n}
"room:lobby" chat members {:message_posted, message}

Guidelines:

  • Narrow topics beat filtering. Subscribing to "order:42" is cheaper than subscribing to "orders" and ignoring most messages.
  • Messages should be small. Sending a whole struct is fine inside one node, but across a cluster it is copied to every node. For large records send the id and let subscribers reload.
  • Never put secrets in topics or messages if the topic name could be guessed by a client who can join it through a channel; authorize in join/3.

Delivery guarantees and clusters

PubSub is fire-and-forget, at-most-once. If a process is not subscribed at the moment of the broadcast, it never sees the message, and nothing is stored. Treat it as a hint to refresh, not as the source of truth: the database is the truth. A process that was disconnected for a minute should reload its data after it reconnects (which a LiveView does through a fresh mount/3).

In a cluster of several Elixir nodes, PubSub delivers across nodes too. The default adapter uses Erlang's :pg process groups, so subscribers on node A receive broadcasts made on node B without Redis or any other broker, as long as the nodes are connected (the deployment lesson covers clustering). Messages from one sender to one subscriber arrive in order, but there is no global ordering between different senders.

The model below makes the at-most-once point concrete.

Node.js A late subscriber misses messages (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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which process receives a message sent with Phoenix.PubSub.broadcast/3?

    All current subscribers of the topic get the message in their mailbox.
  2. 2. Where is the best place to broadcast that an order changed?

    Putting it next to the write means every code path that changes the order notifies subscribers.
  3. 3. A page subscribes to a topic after a message was broadcast. What happens to the old message?

    PubSub keeps no history and delivers at most once. Load the current state when you subscribe.
  4. 4. Which callback handles a PubSub message in a LiveView?

    PubSub messages arrive as ordinary process messages, which LiveView passes to handle_info/2.

Summary

  • PubSub gives loose coupling: subscribers listen on a topic, publishers broadcast to it.
  • Broadcast from the context after a successful write; expose subscribe/1 there too.
  • Subscribe in the connected mount and handle messages in handle_info/2.
  • Delivery is at-most-once with no history; the database is the source of truth.
  • It works across nodes in a cluster without an external broker.

Next: Presence: Who Is Online