100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Building a Chat Server in Erlang

A hands-on walkthrough of building a TCP-based multi-user chat server in Erlang, covering gen_tcp sockets, one process per client, a broadcasting room process, disconnect handling with monitors, and OTP supervision.

PracticeIntermediate10 min readJul 10, 2026
Analogies

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.

erlang
-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.

erlang
-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

Was this page helpful?

Topics covered

#Programming#ErlangStudyNotes#BuildingAChatServerInErlang#Building#Chat#Server#Erlang#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse