Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 48 ยท Projects

Project: Chat Room with Processes

Build a chat room from Elixir processes: a room process keeps subscribers, broadcasts messages and uses monitors to drop users who crash or leave.

A chat room is the classic first project for Elixir concurrency. Every user is a process with a mailbox, and a room is one more process that knows who is subscribed and forwards each message to all of them. You do not need a database, threads or locks: processes and messages are enough.

In this project you will design the room, write its message protocol, and then use monitors so the room notices when a subscriber crashes. Elixir and Erlang are not installed on this site, so the real code is read-only. Each stage has a JavaScript actor stand-in that you can run and change. If processes are new to you, read Processes and Message Passing and Links, Monitors and Let It Crash first.

Who does what

Room One process holds the subscribers.
Users Each user is a process with a mailbox.
Broadcast The room sends one message to everyone.
Monitor The room learns when a user dies.

No shared memory, only messages.

1 / 2

The protocol

Before writing code, decide which messages exist. A small, explicit protocol is the heart of any process-based design.

Message to the room Meaning
{:join, pid, name} Subscribe this process under a name
{:leave, pid} Unsubscribe
{:say, pid, text} Broadcast text from this subscriber
Message from the room Meaning
{:chat, from, text} Someone said something
{:notice, text} Someone joined or left

The room's state is a map from pid to name. That is all it needs.

The room in Elixir

ELIXIR
defmodule Room do
  def start do
    spawn(fn -> loop(%{}) end)
  end

  defp loop(members) do
    receive do
      {:join, pid, name} ->
        Process.monitor(pid)
        members = Map.put(members, pid, name)
        broadcast(members, {:notice, "#{name} joined"})
        loop(members)

      {:leave, pid} ->
        loop(remove(members, pid, "left"))

      {:say, pid, text} ->
        case Map.fetch(members, pid) do
          {:ok, name} -> broadcast(members, {:chat, name, text})
          :error -> :ignore
        end

        loop(members)

      {:DOWN, _ref, :process, pid, _reason} ->
        loop(remove(members, pid, "disconnected"))
    end
  end

  defp remove(members, pid, verb) do
    case Map.pop(members, pid) do
      {nil, members} ->
        members

      {name, members} ->
        broadcast(members, {:notice, "#{name} #{verb}"})
        members
    end
  end

  defp broadcast(members, message) do
    for {pid, _name} <- members, do: send(pid, message)
    :ok
  end
end

Read it from top to bottom:

  • loop/1 is a recursive receive loop whose argument is the state, exactly as in Keeping State in a Process. Each clause ends by calling loop again with the next state.
  • On :join the room calls Process.monitor/1. If that process ever exits, for any reason, the room receives a {:DOWN, ref, :process, pid, reason} message. Monitors are one-way and never kill the room, unlike links.
  • broadcast/2 uses a for comprehension (see Comprehensions with for) to send/2 the same message to every pid in the map.
  • Map.pop/2 returns {value, new_map}, and the {nil, members} clause handles a pid that was already removed (for example a user who left and then crashed), so the room never announces the same departure twice.

A user is any process that understands {:chat, ...} and {:notice, ...}:

ELIXIR
room = Room.start()

alice = spawn(fn -> Chat.user_loop("alice") end)
send(room, {:join, alice, "alice"})
send(room, {:say, alice, "hello, room"})

A JavaScript room

The stand-in below builds a tiny actor system: each process has a mailbox and an async loop that handles one message at a time. It is a model of the idea, not the BEAM. JavaScript runs on a single thread and only switches tasks at await, while real processes run in parallel and are scheduled by the VM.

JS A room that broadcasts to subscribers (JavaScript stand-in)

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

No output.

Study the order of lines: because each process handles messages in the order they arrive, everything is deterministic here. Alice leaves before Bob's last message, so only Bob sees it. Alice also never sees her own "left" notice, since she was removed before the broadcast.

Detecting crashes with monitors

A user process can die at any moment: a bug, a closed browser tab, a network drop. If the room kept the dead pid in its map, it would keep sending messages into the void, and the other users would never be told. A monitor solves this without any polling.

sequenceDiagram
    participant U as User process
    participant R as Room
    R->>U: Process.monitor(pid)
    Note over U: crashes
    U--)R: {:DOWN, ref, :process, pid, reason}
    R->>R: remove pid, broadcast notice

The VM itself sends the :DOWN message when a monitored process ends.

Two details matter. First, the :DOWN message arrives even if the process was already dead when you called Process.monitor/1, with the reason :noproc, so there is no race. Second, the room keeps working whatever the user did. This is the "let it crash" idea: the user process may fail, and the room, which is a separate process with its own state, simply cleans up.

In the stand-in, kill removes a process and the room is told through a monitor list:

JS Monitors: the room notices a crashed user (JavaScript stand-in)

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

No output.

Alice's handler throws, which ends only her process. The room receives the DOWN message, removes her and tells Bob. Notice that the room itself was never at risk.

Using a Registry instead of a map

Keeping subscribers in the room's own state is simple, but Elixir also ships a Registry that does this for you. Processes register under a key, and Registry.dispatch/3 calls a function for every process registered there. Registries also remove a process automatically when it dies, so you would not need to write Process.monitor/1 yourself. Phoenix PubSub, used by LiveView, is built on the same idea. See ETS, Registry and Application State. The hand-written room is worth building once, because it shows what a registry does under the hood.

Where to go next

  • Add history: keep the last 50 messages in the room state and send them to a new subscriber on join.
  • Make the room a GenServer with handle_cast for say and handle_info for :DOWN.
  • Start rooms on demand under a DynamicSupervisor (see Supervisors and Supervision Trees), so a crashed room is restarted.
  • Add a typing indicator, but protect the room from slow users: sending is asynchronous and the mailbox of a slow user can grow without limit.

A process mailbox is unbounded. If a user process is slower than the stream of messages, its mailbox keeps growing and uses memory. Real chat systems drop or batch messages for slow consumers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the room receive when a monitored user process exits?

    Monitors deliver a :DOWN message to the watching process, and unlike links they never take the watcher down.
  2. 2. Why is the room's state a map from pid to name?

    The room needs the pids to send messages and the names to build notices; any structure with that information would work.
  3. 3. What is the main risk of an unbounded mailbox in this design?

    send/2 never blocks, so a consumer that cannot keep up accumulates messages.
  4. 4. What happens if you monitor a process that is already dead?

    The VM sends :DOWN immediately with :noproc, so there is no gap in which a death could go unnoticed.

Summary

  • A chat room is one process holding subscribers plus one process per user; everything works by messages.
  • Define the message protocol first, then write a recursive receive loop whose argument is the state.
  • Process.monitor/1 lets the room learn about crashes through :DOWN messages without being affected by them.
  • Registry and Phoenix PubSub package the same pattern for production use.
  • The JavaScript actors are a teaching model, not the BEAM scheduler.

Next up: Project: Job Queue with Supervision.