Practical Project 3: RoomPulse — Real-Time Group Chat & Live Presence
Difficulty: Intermediate
Estimated Effort: 2–3 weekends
New Concepts Introduced: WebSockets vs. HTTP, authenticating live socket connections, rooms & scoped broadcasting, online presence & typing indicators, reconnection without duplicate messages, rate limiting, inspecting WebSocket frames in Chrome DevTools, and deploying wss:// on a persistent server.
Overview
In this walkthrough, you will build RoomPulse, a lightweight real-time group chat app (like a tiny Slack or Discord). Users log in, join or create named chat rooms (like #study-group or #weekend-trip), see who is currently online, and send messages that appear instantly on everyone else's screen without refreshing the browser—while still saving message history in PostgreSQL so nothing disappears when you reload or come back tomorrow.
How this levels up from Projects 1 & 2:
- Project 1 introduced single-user CRUD and local SQLite.
- Project 2 introduced multi-user accounts, PostgreSQL, and per-user data isolation over normal HTTP requests (
fetch). - Project 3 moves beyond "request -> response -> hang up" HTTP into live, two-way real-time communication (WebSockets) combined with persistent database history and multi-user rooms.
Phase 1: Idea & Product Thinking
The Everyday Scenario
A small study group or project team coordinates daily in messy personal WhatsApp threads where everything gets mixed into one stream—or builds a simple team hub where normal HTTP pages require manually hitting "Refresh" to see new replies. They want clean topic rooms where messages pop in live, you can tell who is currently around, and past messages are still there when someone logs in later.
Problem Statement
Small study groups and hobby teams need focused, topic-based chat rooms where messages and online presence update live without refreshing, because standard single-thread messaging mixes topics together and polling/refreshing feels sluggish.
Challenging AI Assumptions
- AI initially suggested: "Build voice/video calling, file uploads, emoji reaction pickers, threaded replies, read receipts, and end-to-end encryption!"
- Your engineering decision: Voice/video (WebRTC) and custom E2E cryptography are massive projects on their own. For MVP, focus strictly on text rooms, real-time messages, online presence, typing indicator, and saved message history—that already teaches every core real-time architecture pattern cleanly.
MVP Scope
- Essential (In Scope for v1):
- Sign up, log in, and log out securely.
- View/create public rooms (e.g.,
#general,#study-group) and join one active room at a time. - Send and receive text messages in real time via WebSockets, saved in PostgreSQL.
- See a live "Online in this room" user list and a subtle "Alex is typing..." indicator.
- Load the last 50 saved messages automatically when opening or refreshing a room.
- Out of Scope (Later): Direct 1-on-1 DMs, file/image uploads, voice/video calls, threaded replies, push notifications, message editing.
Phase 2: Requirements & Planning
Key User Stories & Acceptance Criteria
- Story 1 (Authenticated Socket Connection): As a logged-in user, I want my identity verified before joining live chat so nobody can impersonate another user.
- Opening a WebSocket connection without a valid login session is rejected by the server.
- Every broadcasted message displays the server-verified sender name (never a username forged by the browser).
- Story 2 (Live Room Messaging + History): As a member in
#study-group, I want messages I send to appear instantly for everyone in that room and stay saved after a refresh.- Sending a valid message (
1–1,000chars) saves it to PostgreSQL first, then broadcasts it immediately to all users currently in that room. - Users in other rooms (
#random) do not receive#study-groupmessages. - Refreshing the browser reloads recent saved history in chronological order without losing messages.
- Sending a valid message (
- Story 3 (Online Presence & Reconnect): As a room member, I want to see who is currently online and recover smoothly if my Wi-Fi drops.
- When User B opens the room, User A sees User B appear in the Online list without refreshing; when User B closes the tab, they disappear within a few seconds.
- Sending messages faster than the rate limit (e.g., > 5 messages in 5 seconds) shows a friendly slow-down warning instead of flooding everyone.
Phase 3: UI/UX & Design
Screen Inventory (2 Screens)
/login&/signup: Simple centered auth card (reusing the clean login pattern from Project 2)./(Chat Workspace): Left sidebar (Rooms list + Online users in current room + Log out) and main panel (Room header + Connection status badgeConnected / Reconnecting...+ Scrollable message feed + Message input bar + subtle typing indicator).
Text Wireframe (/ Chat Workspace)
+-----------------------------------------------------------------------+
| RoomPulse #study-group ● Connected [Sam] [Log out] |
+--------------------+--------------------------------------------------+
| ROOMS | Alex (10:14): Anyone finished Lesson 5.3 yet? |
| > #study-group | Sam (10:15): Just got Postgres tables running! |
| #general | |
| #random | |
| [+ New Room] | |
|--------------------| |
| ONLINE NOW (2) | _Alex is typing..._ |
| ● Alex |--------------------------------------------------|
| ● Sam | [ Type a message... ] [ Send ] |
+--------------------+--------------------------------------------------+
Design Direction Rules
- Tone: Clean, readable chat workspace (
#F8FAFCsidebar,#FFFFFFmessage panel,#0F172Atext,#0D9488teal accent for connection/active room). - Important Real-Time UX Details: Always show a clear connection status indicator (
Connectedvs.Reconnecting...) so users know right away if their internet dropped, and auto-scroll cleanly only when already near the bottom of the chat.
Phase 4: System Design & Architecture
How WebSockets Differ From HTTP (The Core Mental Model)
- Normal HTTP (
fetch): Like mailing a letter—browser asks, server answers, connection closes. The server cannot contact the browser unprompted. - WebSockets (
ws://locally,wss://in production): Like keeping an open phone call between browser and server. Either side can send small JSON events anytime (message:new,presence:update,typing:start).
Chosen Stack
- Server: Persistent backend server supporting both HTTP routes and WebSockets in one app (for example, Node.js + Express +
wsor Socket.IO, OR Python + FastAPI WebSockets). - Why one persistent server matters: Short-lived serverless functions spin down between requests and drop live WebSocket connections; a single long-running server handles both HTTP auth/history and persistent WebSockets cleanly.
- Database: PostgreSQL (persists users, rooms, and messages—live memory tracks only who is currently connected).
Relational Data Model
users:id,email(unique),display_name,password_hash,created_atrooms:id,name(unique slug, e.g.,study-group),created_by(FK ->users.id),created_atmessages:id,room_id(FK ->rooms.id),user_id(FK ->users.id),body(text, not null),created_at(timestamp)
Critical Ordering Rule (Save First, Broadcast Second)
When the server receives a chat message over the WebSocket:
- Validate length (
1–1,000chars) and check per-user rate limit. - Insert the message into PostgreSQL (
messagestable) and get its realidandcreated_at. - Only after the database save succeeds, broadcast
{ id, roomId, senderName, body, createdAt }to everyone subscribed to that room. (If the DB fails, send an error event back to the sender—never broadcast messages that weren't actually saved!)
Phase 5: Project Setup
(See Lesson 5.3: Setting Up Your Database if you need a refresher on Postgres setup.)
- Initialize repo
roompulse, set up.gitignoreand.env.example(PORT,DATABASE_URL,SESSION_SECRET). - Provision PostgreSQL (local or free cloud dev DB) and run initial migrations creating
users,rooms(seed one default#generalroom), andmessages. - Verify
GET /api/healthconfirms PostgreSQL connectivity AND your WebSocket server starts cleanly alongside HTTP on the same port. - Commit clean skeleton to
main.
Phase 6: AI-Assisted Implementation (Vertical Slices)
Build strictly one slice at a time on separate feature branches:
- Branch 1 (
feat/auth-and-rooms-http):- Reuse Project 2's HTTP-only session auth (
signup,login,logout,me) + HTTP endpointsGET /api/rooms,POST /api/rooms, andGET /api/rooms/:id/messages(returns latest 50 saved messages). - Verify HTTP endpoints work before adding WebSockets!
- Reuse Project 2's HTTP-only session auth (
- Branch 2 (
feat/websocket-live-chat):- Add WebSocket server sharing the same session verification so unauthenticated sockets are rejected immediately.
- Implement
room:join,message:send(rate-limit -> DB insert -> broadcast to room), andmessage:newon the frontend. - Verify with two browsers: Open Chrome Normal as User A and Incognito as User B, join
#general, send a message from User A, and confirm it pops up instantly in User B—then refresh User B and confirm it loads from PostgreSQL.
- Branch 3 (
feat/presence-typing-reconnect):- Track active users per room in server memory (
Map<roomId, Set<user>>) and broadcastpresence:updateon join/disconnect. - Add throttled
typing:start/typing:stopevents (auto-clear after ~3 seconds of inactivity). - Add automatic reconnect logic on the frontend (
Reconnecting...banner -> rejoin current room -> re-fetch missed messages from HTTP/messagesso nothing is lost during brief Wi-Fi drops).
- Track active users per room in server memory (
Phase 7: Debugging, Security & Quality
How to Debug WebSockets in Chrome DevTools
Normal API debugging uses Network -> Fetch/XHR, which won't show live socket messages! Instead:
- Open Chrome DevTools -> Network tab -> click the WS (WebSockets) filter.
- Refresh the page and click the active WebSocket connection -> open the Messages sub-tab.
- Watch live incoming (red/down) and outgoing (green/up) JSON frames in real time—if a message didn't appear on screen, check here first to see whether the server never sent it or the UI failed to render it!
Crucial Security Checks (Verify Every Single One!)
- Unauthenticated Socket Rejection: Try opening a WebSocket connection while logged out -> confirm the server closes/rejects it before any
room:joinormessage:newevents can run. - XSS Prevention in Chat: Send
<script>alert('xss')</script>or<img src=x onerror=alert(1)>as a chat message. Verify it renders harmlessly as plain text on every connected browser (never use unsafe raw HTML rendering likeinnerHTMLordangerouslySetInnerHTML). - Sender Impersonation Check: Confirm the server ignores any
senderNameoruserIdsent in the client's socket JSON and always attaches identity from the verified session. - Rate Limiting Check: Rapidly send 10 messages in 2 seconds -> confirm the server blocks excess messages cleanly without crashing the socket or freezing other users.
Automated Integration Tests
- Unauthenticated WebSocket connection fails handshake.
- User A sending a message in
#generalsaves to PostgreSQL and pushesmessage:newto User B in#general, while User C in#randomreceives nothing. - Disconnecting User B removes User B from
#general's online presence list.
Phase 8: Git & Collaboration
- Keep each slice on its own branch (
feat/auth-and-rooms-http,feat/websocket-live-chat,feat/presence-typing-reconnect). - Inspect
git diffcarefully to ensure no leftover debug socket logs or weak secrets remain, review each PR on GitHub, and merge tomain.
Phase 9: Deployment & Verification
- Choose a WebSocket-Friendly Host (Critical Decision!):
- Deploy to a persistent server host that supports long-lived WebSocket (
wss://) connections (do not deploy a raw WebSocket server to short-lived serverless functions that terminate idle connections).
- Deploy to a persistent server host that supports long-lived WebSocket (
- Provision a managed PostgreSQL database, set
DATABASE_URLand a strongSESSION_SECRET, and run your schema migrations. - Verify
wss://over HTTPS: Browsers block unencryptedws://connections fromhttps://pages (Mixed Content Error). Confirm your frontend automatically useswss://in production. - Two-Device Live Smoke Test:
- Log in as User A on your laptop (
https://...) and User B on your phone over mobile data. - Confirm both show
Connectedand appear inONLINE NOW (2). - Send messages back and forth -> confirm instant delivery.
- Toggle Airplane Mode on your phone for 5 seconds, turn it back off -> confirm the UI reconnects cleanly and loads any messages missed while offline.
- Log in as User A on your laptop (
Return to: Practical Projects Index | Curriculum Index