Skip to main content
Reading progress: 0%

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):
    1. Sign up, log in, and log out securely.
    2. View/create public rooms (e.g., #general, #study-group) and join one active room at a time.
    3. Send and receive text messages in real time via WebSockets, saved in PostgreSQL.
    4. See a live "Online in this room" user list and a subtle "Alex is typing..." indicator.
    5. 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,000 chars) 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-group messages.
    • Refreshing the browser reloads recent saved history in chronological order without losing messages.
  • 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)​

  1. /login & /signup: Simple centered auth card (reusing the clean login pattern from Project 2).
  2. / (Chat Workspace): Left sidebar (Rooms list + Online users in current room + Log out) and main panel (Room header + Connection status badge Connected / 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 (#F8FAFC sidebar, #FFFFFF message panel, #0F172A text, #0D9488 teal accent for connection/active room).
  • Important Real-Time UX Details: Always show a clear connection status indicator (Connected vs. 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 + ws or 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_at
  • rooms: id, name (unique slug, e.g., study-group), created_by (FK -> users.id), created_at
  • messages: 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:

  1. Validate length (1–1,000 chars) and check per-user rate limit.
  2. Insert the message into PostgreSQL (messages table) and get its real id and created_at.
  3. 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.)

  1. Initialize repo roompulse, set up .gitignore and .env.example (PORT, DATABASE_URL, SESSION_SECRET).
  2. Provision PostgreSQL (local or free cloud dev DB) and run initial migrations creating users, rooms (seed one default #general room), and messages.
  3. Verify GET /api/health confirms PostgreSQL connectivity AND your WebSocket server starts cleanly alongside HTTP on the same port.
  4. Commit clean skeleton to main.

Phase 6: AI-Assisted Implementation (Vertical Slices)​

Build strictly one slice at a time on separate feature branches:

  1. Branch 1 (feat/auth-and-rooms-http):
    • Reuse Project 2's HTTP-only session auth (signup, login, logout, me) + HTTP endpoints GET /api/rooms, POST /api/rooms, and GET /api/rooms/:id/messages (returns latest 50 saved messages).
    • Verify HTTP endpoints work before adding WebSockets!
  2. 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), and message:new on 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.
  3. Branch 3 (feat/presence-typing-reconnect):
    • Track active users per room in server memory (Map<roomId, Set<user>>) and broadcast presence:update on join/disconnect.
    • Add throttled typing:start / typing:stop events (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 /messages so nothing is lost during brief Wi-Fi drops).

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:

  1. Open Chrome DevTools -> Network tab -> click the WS (WebSockets) filter.
  2. Refresh the page and click the active WebSocket connection -> open the Messages sub-tab.
  3. 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!)​

  1. Unauthenticated Socket Rejection: Try opening a WebSocket connection while logged out -> confirm the server closes/rejects it before any room:join or message:new events can run.
  2. 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 like innerHTML or dangerouslySetInnerHTML).
  3. Sender Impersonation Check: Confirm the server ignores any senderName or userId sent in the client's socket JSON and always attaches identity from the verified session.
  4. 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 #general saves to PostgreSQL and pushes message:new to User B in #general, while User C in #random receives nothing.
  • Disconnecting User B removes User B from #general's online presence list.

Phase 8: Git & Collaboration​

  1. Keep each slice on its own branch (feat/auth-and-rooms-http, feat/websocket-live-chat, feat/presence-typing-reconnect).
  2. Inspect git diff carefully to ensure no leftover debug socket logs or weak secrets remain, review each PR on GitHub, and merge to main.

Phase 9: Deployment & Verification​

  1. 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).
  2. Provision a managed PostgreSQL database, set DATABASE_URL and a strong SESSION_SECRET, and run your schema migrations.
  3. Verify wss:// over HTTPS: Browsers block unencrypted ws:// connections from https:// pages (Mixed Content Error). Confirm your frontend automatically uses wss:// in production.
  4. 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 Connected and appear in ONLINE 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.

Return to: Practical Projects Index | Curriculum Index