Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 50 ยท Projects

Project: A chat app with WebSockets

Build a multi-room chat server with FastAPI WebSockets: connection manager, rooms, usernames, join and leave messages, message validation, and a browser client.

In this project you build the classic WebSocket application: a chat with rooms and usernames. Anyone who connects to a room sees what the others write, instantly. It exercises everything from Streaming, SSE and WebSockets: accepting connections, a receive loop, broadcasting, disconnect handling, and the awkward details that make the difference between a demo and something that works (bad input, duplicate names, a dead connection in the middle of a broadcast).

You will work in three stages. First the server, tested live in your browser with a tiny WebSocket test client written for the occasion. Then a read-only HTML client to open in a real browser. Finally the production notes for scaling beyond one process.

What we are building

The chat features

Rooms /ws/{room}, created on first join.
Usernames ?name=ada, unique per room.
Broadcast Everyone in the room hears you.
Join and leave Announcements and a user list.
1 / 2

The protocol between browser and server is JSON in both directions. The client sends {"text": "hello"}. The server replies to everyone with {"type": "message", "user": "ada", "text": "hello"}, and uses {"type": "system", ...} for announcements and {"type": "users", ...} for the member list.

The server

The heart is a Room object that knows its members, and a ChatHub that creates rooms on demand. Both are plain Python, which keeps them easy to test.

Key design decisions:

  • connect validates before accepting. Usernames must be 1-20 simple characters and unique within the room. A bad request is closed with code 1008 (policy violation) before the handshake completes.
  • broadcast tolerates dead connections. If sending to one socket fails, that member is removed and the others still get the message.
  • Incoming JSON is validated with Pydantic: a malformed or oversized message gets an error reply to that user only, and the connection stays open.
  • Empty rooms are deleted, so the dictionary does not grow forever.

The program below contains the full server plus a minimal ASGI WebSocket test client. It talks to the app by sending the same events a real server like uvicorn would, so it runs in your browser with no network and no threads. Read the client as a helper: the interesting part is the server above it.

Python A chat server with rooms and usernames

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 input()), it gets the next line from this box.

Study the output in order. Ada gets her own join announcement and a user list. When Linus joins, both see the announcement and the new list. Ada's message reaches both. A second room (rust) is separate: Ada and Linus never hear Ferris. A duplicate name and a name with illegal characters are refused with close code 1008 before the connection is accepted. Linus's malformed message gets a private error and the connection stays open. When everybody leaves, empty rooms disappear.

Real browsers cannot read the close reason when the handshake is refused, so for friendlier errors many apps accept first, send an error message and then close. Refusing before accept() is simpler and rejects abusive clients cheaply.

The browser client

Save this as a static file (see Jinja2 templates and static files), or serve it from an endpoint, and open it in two tabs. It is read-only here because the lesson runner has no network server.

HTML
<!doctype html>
<meta charset="utf-8">
<title>Chat</title>
<input id="name" placeholder="your name" value="guest1">
<input id="room" placeholder="room" value="lobby">
<button id="join">Join</button>
<ul id="log"></ul>
<form id="form"><input id="text" autocomplete="off" disabled><button disabled>Send</button></form>

<script>
let socket;
const log = document.getElementById("log");
const add = (text) => {
  const li = document.createElement("li");
  li.textContent = text;                 // textContent, never innerHTML: users control this text
  log.append(li);
};

document.getElementById("join").onclick = () => {
  const name = encodeURIComponent(document.getElementById("name").value);
  const room = encodeURIComponent(document.getElementById("room").value);
  const scheme = location.protocol === "https:" ? "wss" : "ws";
  socket = new WebSocket(`${scheme}://${location.host}/ws/${room}?name=${name}`);

  socket.onopen = () => document.querySelectorAll("#form *").forEach((el) => (el.disabled = false));
  socket.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === "message") add(`[${data.at}] ${data.user}: ${data.text}`);
    else if (data.type === "system") add(`* ${data.text}`);
    else if (data.type === "users") add(`(online: ${data.users.join(", ")})`);
  };
  socket.onclose = (event) => add(`* disconnected (${event.code})`);
};

document.getElementById("form").onsubmit = (event) => {
  event.preventDefault();
  const input = document.getElementById("text");
  socket.send(JSON.stringify({ text: input.value }));
  input.value = "";
};
</script>

Two things deserve attention. The client builds the URL with wss:// on HTTPS pages (browsers block plain ws:// from secure pages). And it uses textContent, not innerHTML, because chat text comes from other users: inserting it as HTML would let anyone run scripts in everyone else's browser (cross-site scripting).

Taking it further

Try these extensions as exercises:

  • Authentication. Browsers cannot set custom headers on a WebSocket, so pass a short-lived token in the query string or read a session cookie, and verify it before accept(). Use the signed token from OAuth2 and JWT and take the username from the token instead of the URL. Never trust a name= parameter on a real site.
  • History. Keep the last 50 messages per room in a collections.deque and send them to a new member, or store messages in a database.
  • Typing indicators and private messages. Extend the protocol with a type field on incoming messages.
  • Rate limiting. Count messages per user per second and warn or disconnect spammers.
  • Heartbeats. Send a ping every 30 seconds so proxies do not close idle connections and you notice dead clients.
  • Tests. Real FastAPI tests use TestClient(app).websocket_connect("/ws/room?name=ada") as a context manager, as shown in Testing FastAPI.

Production notes

  • One process only. ChatHub lives in memory, so two uvicorn workers would be two separate chats. To scale out, publish every message to a shared pub/sub channel (Redis, NATS, PostgreSQL LISTEN/NOTIFY) that each worker subscribes to, and have each worker broadcast to its own local sockets.
  • Proxies must allow upgrades. For nginx, pass Upgrade and Connection headers and raise proxy_read_timeout; see Deployment.
  • Back-pressure. A slow client can make send wait. For large rooms, give each member an outgoing queue and a writer task, and drop members whose queue grows too long.
  • Limits. Cap message size, messages per second, connections per IP and members per room.
  • Origin checks. Browsers send an Origin header with WebSocket handshakes; reject origins you do not expect to stop other sites from opening sockets with your visitors' cookies (cross-site WebSocket hijacking).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the server validate the username before calling accept()?

    Refusing early (close code 1008) avoids registering an invalid member and spends no resources on abusive clients.
  2. 2. What should broadcast do when sending to one member raises an exception?

    A dead socket must not prevent the rest of the room from receiving the message.
  3. 3. Why does the browser client use textContent rather than innerHTML for messages?

    Untrusted text must never be interpreted as HTML.
  4. 4. What goes wrong if you run this chat server with four uvicorn workers?

    In-memory state is per process. A shared pub/sub layer such as Redis connects the workers.
  5. 5. Where should a real chat take the user's identity from?

    Anything the client simply claims can be forged. Verify a token or session cookie during the handshake.

Summary

  • A WebSocket chat needs a connection manager: rooms holding members, connect/leave, and a broadcast that survives dead connections.
  • Validate early: usernames before accept(), messages with Pydantic inside the loop; reply with an error and keep the connection open when the input is merely bad.
  • Use a small JSON protocol (message, system, users) so clients and servers can grow independently.
  • The browser client uses new WebSocket(...), wss:// on HTTPS, and textContent for untrusted text.
  • To scale beyond one process add pub/sub, proxy upgrade support, limits, heartbeats and origin checks; to secure it, authenticate with a token during the handshake.

Back to the other projects with the production service, or review the whole course with the cheat sheet.