Building a Chat Server in Erlang
Erlang's actor model maps naturally onto a TCP chat server: instead of using shared memory and locks to coordinate connected clients, the design spawns lightweight processes that communicate exclusively by sending messages to each other's mailboxes. A typical chat server has three moving parts — a listener process that accepts incoming TCP connections, one process per connected client that reads from and writes to that client's socket, and a central 'room' process that fans messages out to everyone. Because Erlang processes are isolated and share nothing, a bug or crash in one client's handling code cannot corrupt another client's state, and a supervisor can restart the failed piece without taking the whole server down.
Cricket analogy: Just as MS Dhoni behind the stumps coordinates fielders by calling out instructions rather than physically repositioning them himself, Erlang processes coordinate purely by sending messages to each other instead of sharing memory directly.
Accepting Connections with gen_tcp
The server starts by calling gen_tcp:listen/2 with a port number and a list of options such as {packet, line} to frame incoming bytes on newline boundaries, {active, false} to require an explicit gen_tcp:recv/2 call rather than receiving data as unsolicited messages, and {reuseaddr, true} to allow immediately rebinding the port after a restart. The resulting ListenSocket is then passed to gen_tcp:accept/1, which blocks the calling process until a client connects and returns a new, connected Socket. Because accept/1 blocks, the accepting process immediately spawns a fresh process to call gen_tcp:accept/1 again before doing anything else, so the server keeps accepting new connections concurrently instead of handling clients one at a time.
Cricket analogy: Setting {active, false} on the listening socket is like a bowler such as Jasprit Bumrah holding the ball at the top of the run-up until conditions are ready, releasing control only on an explicit signal rather than continuously.
-module(chat_listener).
-export([start/1, accept_loop/1]).
start(Port) ->
{ok, ListenSocket} = gen_tcp:listen(Port,
[binary, {packet, line}, {active, false}, {reuseaddr, true}]),
spawn_link(fun() -> accept_loop(ListenSocket) end).
accept_loop(ListenSocket) ->
{ok, Socket} = gen_tcp:accept(ListenSocket),
%% Immediately spawn the next acceptor so new clients aren't blocked
spawn(fun() -> accept_loop(ListenSocket) end),
ClientPid = spawn(fun() -> chat_client:init(Socket) end),
ok = gen_tcp:controlling_process(Socket, ClientPid),
ClientPid ! {socket_ready, Socket}.One Process Per Connected Client
Each accepted socket is handed off to its own client process, which becomes the socket's controlling process via gen_tcp:controlling_process/2 — a required step, since the acceptor, not the client process, originally owned the socket. In passive mode ({active, false}), the client process calls gen_tcp:recv/2 in a loop to pull one line of input at a time, forward it to the chat room, and recurse; in active mode ({active, true} or {active, once}), it instead receives {tcp, Socket, Data} and {tcp_closed, Socket} as ordinary Erlang messages in its receive block. Either style keeps a client's read loop, and any bug in parsing that client's input, fully contained inside one process.
Cricket analogy: Spawning a dedicated process per connected client is like assigning a fielder to cover Virat Kohli's favored cover-drive zone specifically, so one fielder's mistake doesn't affect the rest of the field placement.
gen_tcp:controlling_process/2 must be called from the process that currently owns the socket (usually the acceptor) to transfer ownership to the new client process. Forgetting this step means TCP data delivered as messages, in {active, true} mode, arrives at the wrong process, and gen_tcp:recv/2 calls from the intended client process will fail with {error, not_owner}.
Broadcasting Through a Central Room Process
Rather than having client processes message each other directly, a single room process holds the shared state — typically a map from each connected Pid to its {Socket, MonitorRef} pair — and every client sends it a {broadcast, FromPid, Text} message when it has a line to share. The room process then walks the map, pushing the text to every socket except the sender's own. This can be written as a plain tail-recursive receive loop for a learning exercise, but production code should implement it as a gen_server so that join and leave operations go through handle_call/handle_cast with OTP's standard timeout, tracing, and hot code-upgrade support built in.
Cricket analogy: The room process fanning a message out to every connected client is like a stadium PA announcer relaying the same over-by-over update, e.g. Rohit Sharma's century, to every section of the ground simultaneously.
-module(chat_room).
-export([start/0, loop/1]).
start() ->
Pid = spawn(fun() -> loop(#{}) end),
register(chat_room, Pid),
Pid.
loop(Clients) ->
receive
{join, Pid, Socket} ->
Ref = erlang:monitor(process, Pid),
loop(maps:put(Pid, {Socket, Ref}, Clients));
{broadcast, FromPid, Text} ->
[gen_tcp:send(S, Text)
|| {P, {S, _Ref}} <- maps:to_list(Clients), P =/= FromPid],
loop(Clients);
{'DOWN', _Ref, process, Pid, _Reason} ->
loop(maps:remove(Pid, Clients))
end.Tracking Users with a Process Registry
The map inside the room process doubles as the user registry: on join it stores {Socket, MonitorRef} — and typically a chosen username — keyed by Pid, and on leave it removes that entry. This is preferable to Erlang's built-in register/2 for per-client bookkeeping, since register/2 only binds a single fixed atom to one process at a time and every atom created is permanent for the life of the VM, which is fine for a name like chat_room but unworkable for hundreds of short-lived, dynamically named clients. For servers expecting heavy concurrent reads of the client list, an ETS table, created with ets:new/2 using the public or protected access modes, can replace the map to avoid funneling every lookup through the room process's single mailbox.
Cricket analogy: Maintaining a map from Pid to username in the room process is like a scorer's book that tracks every player on the field by name, so an update such as a boundary struck by Ben Stokes gets attributed to the right batsman instantly.
Handling Disconnects and Supervision
The room process calls erlang:monitor(process, Pid) when a client joins, which asks the runtime to send a {'DOWN', Ref, process, Pid, Reason} message to the room process if that client process ever terminates — normally, by a crash, or because its TCP connection dropped and its recv loop returned {error, closed}. Handling that message by removing Pid from the client map, and optionally broadcasting a 'user left' notice, lets the server clean up state without any of the surviving clients noticing a delay. The whole application — listener, room, and supervisor — should be started as an OTP application module implementing the application behaviour's start/2 callback, with a top-level supervisor using a one_for_one restart strategy so that if the room process crashes, only it is restarted, with a fresh, empty client map, rather than tearing down the entire node.
Cricket analogy: erlang:monitor/2 is like an umpire keeping an eye on a batsman such as Steve Smith's fitness during a rain-delayed Test match — if the batsman retires hurt, the umpire is notified immediately and can update the scoreboard accordingly.
Don't reach for erlang:link/1 as a shortcut for erlang:monitor/2 here: a plain link is bidirectional, so when a client process crashes or its socket dies, the link will crash the room process too unless the room process calls process_flag(trap_exit, true) — and even then you receive {'EXIT', Pid, Reason} instead of {'DOWN', Ref, process, Pid, Reason}, with no monitor reference to match up. erlang:monitor/2 is unidirectional and exactly what a broadcast hub needs: notification of a client's death without any risk of the room itself going down alongside it.
- gen_tcp:listen/2 opens the listening socket and gen_tcp:accept/1 blocks until a client connects; spawn the next acceptor immediately so connections aren't serialized.
- gen_tcp:controlling_process/2 must transfer socket ownership to the new client process, or {active, true} messages and gen_tcp:recv/2 calls will fail with {error, not_owner}.
- One Erlang process per connected client keeps read loops, parsing bugs, and crashes fully isolated from every other client.
- A central room process holding a map of Pid to {Socket, MonitorRef} is the simplest way to broadcast messages to every connected client; wrap it in a gen_server for production use.
- Prefer a map or ETS table over register/2 for tracking dynamic clients, since register/2 only supports fixed, permanent atom names.
- erlang:monitor/2 delivers a {'DOWN', Ref, process, Pid, Reason} message on client disconnect, letting the room process clean up state without risking its own crash — unlike a plain link without trap_exit.
- Structure the whole server as an OTP application with a one_for_one supervisor so a crashed room or acceptor process restarts independently, without taking the entire node down.
Practice what you learned
1. Which gen_tcp:listen/2 option makes the socket require an explicit gen_tcp:recv/2 call to retrieve incoming data, rather than delivering it as unsolicited messages?
2. Why does the acceptor process call gen_tcp:controlling_process/2 after gen_tcp:accept/1 returns a new socket?
3. Why is a map (Pid to client info) generally preferred over register/2 for tracking connected chat clients?
4. What message does the room process receive after calling erlang:monitor(process, Pid) if that client process terminates?
5. In a supervisor using the one_for_one restart strategy, what happens when the chat room's gen_server child process crashes?
Was this page helpful?
You May Also Like
Erlang vs Elixir: Comparing the Two BEAM Languages
A practical comparison of Erlang and Elixir — how they share the BEAM VM and OTP, where their syntax and tooling diverge, and how to choose between them.
Erlang Best Practices: Supervision, OTP, and Fault Tolerance
A practical guide to writing production-grade Erlang: let-it-crash supervision design, correct gen_server callback usage, ETS-backed shared state, precise error handling, and OTP release hygiene.
Erlang Interview Questions
A guided walkthrough of the Erlang concepts interviewers probe most — the actor-model concurrency system, OTP fault tolerance, pattern matching, and distribution — with the reasoning behind each question.
Erlang Quick Reference
A cheat-sheet tour of Erlang's core data types, common built-in functions, the shell/module workflow, OTP gen_server callbacks, and the pattern-matching idioms you'll reach for every day.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics