Vibe Coding: build real apps with AI · Episode 17. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5, from the run's init line) in print mode (claude -p), on the night of 11 to 12 November 2026 (India time), in /home/ravi/projects/family-chat (a Git repository). Node.js v22.23.4, ws 8.22.2. The AI wrote "express": "^4.21.2"; npm view express version said 5.3.0 that day. Browser results come from Chromium driven by Playwright against the real server, with the browser's time zone set to Asia/Kolkata. The polling measurements used the run-1 code on a separate port. The polling-cost and rate-limit demos run in the SyntaxPilot online compiler (Python), the time-zone demo in JavaScript. Replies are quoted exactly, shortened where marked .... No keys or secrets are used.
The problem: one chat for the whole family
Diwali is coming and Ravi's family wants one place for the plans. A chat app has one hard requirement: when Mom sends a message, everyone should see it now, without pressing anything.
The obvious way: polling (agent run 1)
claude -p "Make a simple family chat web app in this folder with Node.js and Express. One page: type your name once, then send messages; everyone sees all messages with the sender's name and the time. Keep the messages in memory for now. The page should check the server for new messages every 2 seconds. Plain JavaScript, no frameworks." --output-format stream-json --verbose --allowedTools Read Write Edit Glob "Bash(npm:*)" "Bash(node:*)" "Bash(ls:*)"
What the agent did (real log, shortened):
Write package.json ("express": "^4.21.2")
Write server.js, public/index.html, .gitignore
Bash npm install → found 0 vulnerabilities
Bash PORT=3123 node server.js & curl ... → "requires approval"
Bash node --check server.js → OK
Reply: "I haven't run it: starting the server and sending test
requests needed approval ... Every 2 seconds the page asks the
server for new messages."
Catch: Express 4 was written from memory; the latest that day was 5.3.0 (the same kind of mistake as episodes 12 and 15). Always check versions with npm view <package> version.
The server keeps messages in an array and answers "everything after id N":
// GET /api/messages?since=<id> returns messages with id greater than `since`.
app.get('/api/messages', (req, res) => {
const since = Number(req.query.since) || 0;
res.json(messages.filter((m) => m.id > since));
});
The page asks again and again. Asking repeatedly like this is called polling (a child in the back seat: "are we there yet?").
async function fetchMessages() {
const res = await fetch('/api/messages?since=' + lastId);
const newMessages = await res.json();
newMessages.forEach(addMessage);
}
fetchMessages();
setInterval(fetchMessages, 2000); // ask again every 2 seconds
Measured (real, Playwright, two browsers, one minute)
# Every 10 s Mom sends a message. When does Ravi see it?
message 1 855 ms message 4 820 ms
message 2 842 ms message 5 820 ms
message 3 843 ms message 6 823 ms
average 834 ms
Ravi's page asked "anything new?" 32 times
answers that were [] (nothing new) 26 of 32
At family scale (run in the compiler)
family = 10 # people with the chat open
every = 2 # seconds between "any new messages?" checks
messages_per_day = 200 # what the family really sends
checks = family * (24 * 60 * 60 // every)
print(f"Checks per day: {checks:,}")
print(f"Messages per day: {messages_per_day:,}")
useful = messages_per_day * family # at best, one useful answer per message per person
print(f"Empty answers: at least {1 - useful / checks:.2%}")
print(f"Average wait: {every / 2} s (worst: {every} s)")
for every in [1, 2, 5, 30]:
n = family * 86400 // every
print(f" every {every:>2} s -> {n:>9,} checks/day, wait up to {every} s")
Output:
Checks per day: 432,000
Messages per day: 200
Empty answers: at least 99.54%
Average wait: 1.0 s (worst: 2 s)
every 1 s -> 864,000 checks/day, wait up to 1 s
every 2 s -> 432,000 checks/day, wait up to 2 s
every 5 s -> 172,800 checks/day, wait up to 5 s
every 30 s -> 28,800 checks/day, wait up to 30 s
Polling forces a bad choice: check often (wasteful) or rarely (slow).
Why: HTTP is ask-then-answer
In HTTP (episode 14) every exchange starts with the browser's request; the server only responds. The server can't speak first, even when it has Mom's new message ready. So the browser has to keep asking.
WebSockets (a call left open on speaker)
| Talking to Mom | Browser and server |
|---|---|
| call "any news?", hang up, call again every 2 minutes | polling: a new HTTP request each time, mostly "no news" |
| one call, left open on speaker | WebSocket: one connection, kept open |
| either side talks any time | two-way messages: the server can send first |
MDN (WebSocket API, last modified 22 Oct 2026): "The WebSocket API makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive responses without having to poll the server for a reply."
The handshake (real, curl against our finished server)
A WebSocket starts as one ordinary HTTP request asking to upgrade. The server answers 101 Switching Protocols; from then on the same connection carries WebSocket messages in both directions. That first exchange is the handshake.
$ curl -i -H "Connection: Upgrade" -H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
-H "Origin: http://localhost:3000" localhost:3000/
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
WebSocket addresses start with ws:// (plain) or wss:// (encrypted, like https://). OWASP: "Never use unencrypted ws:// connections in production."
The AI builds it (agent run 2)
claude -p "Switch this chat from polling to WebSockets, using the ws library, so new messages arrive instantly and the page stops asking every 2 seconds. Add rooms: \"family\" and \"cousins\". You pick a room, you only see and send messages in that room, and when you join you get the last 50 messages of that room. Keep the name, the time on each message and the plain JavaScript page."
Bash npm install ws@^8 → "ws": "^8.22.2", 0 vulnerabilities
Write server.js one port: the page AND the WebSocket
Edit public/index.html x6 room buttons, new WebSocket(...), reconnect
Bash PORT=3456 node server.js & ... → "requires approval"
Bash node test.js (the script starts the server itself)
→ b got 55 family msgs; has cousins msg? false
Reply: "I did not test the page itself in a browser: starting a
server here needed your approval."
Sending and receiving on the server (server.js, shortened)
const server = http.createServer(app); // the page and the socket share port 3000
const wss = new WebSocketServer({ server, maxPayload: 16 * 1024 });
wss.on('connection', (ws) => {
ws.room = null;
ws.on('message', (raw) => {
const data = JSON.parse(raw); // (inside try/catch in the file)
if (data.type === 'join') {
ws.room = data.room;
send(ws, { type: 'history', room: ws.room,
messages: messagesByRoom[ws.room].slice(-50) });
}
if (data.type === 'message') {
const message = { id: nextId++, room: ws.room, name, text,
time: new Date().toISOString() };
messagesByRoom[ws.room].push(message);
for (const client of wss.clients) {
if (client.room === message.room) send(client, { type: 'message', message });
}
}
});
});
- Every message on the line is a small JSON object with a
type(join,history,message,error). - Sending =
ws.send(JSON.stringify(...)); receiving = themessageevent. maxPayload: 16 * 1024rejects any single message over 16 KB. Thewsdefault is 104857600 bytes (100 MiB); OWASP suggests "typically 64KB or less".
Sending and receiving in the browser (public/index.html, shortened)
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(protocol + '//' + location.host);
socket.addEventListener('open', () => joinRoom(currentRoom));
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
if (data.type === 'message' && data.message.room === currentRoom) {
const nearBottom = messagesEl.scrollHeight - messagesEl.scrollTop
- messagesEl.clientHeight < 60;
addMessage(data.message);
if (nearBottom || data.message.name === myName)
messagesEl.scrollTop = messagesEl.scrollHeight;
}
});
socket.addEventListener('close', () => {
setTimeout(connect, reconnectDelay); // 1 s, 2 s, 4 s ... up to 15 s
reconnectDelay = Math.min(reconnectDelay * 2, 15000);
});
Reconnecting with a growing wait (1, 2, 4 ... 15 s) is called backoff: after a server restart, thousands of phones don't all hammer it at once.
Rooms (halls at a wedding venue)
| A wedding venue | Our chat |
|---|---|
| the sangeet hall: the mic is heard only there | room family: messages go only to its members |
| the cricket room next door | room cousins: a separate conversation |
| walk into a hall and catch up | join: you get the room's last 50 messages |
On the server a room is just a label on each connection (ws.room), and the send loop only sends to matching labels.
Tested (real, three browser profiles)
"Diwali lunch at our place, 1 pm?" Mom → Ravi 75 ms
"Yes! I'll bring the gulab jamun" Ravi → Mom 62 ms
"Asha is bringing the diyas" Mom → Ravi 43 ms
Neha, cousins room: "a surprise gift for Asha?"
on Mom's screen (family room)? false
(The times include Playwright typing and clicking.) Polling averaged 834 ms.
Timestamps: store UTC, show local
A timestamp is the exact moment something happened. The server stores new Date().toISOString(), e.g. 2026-11-11T21:19:13.213Z. The Z means UTC, the world's reference clock; India (IST) is UTC + 5:30.
// The server stores every message time like this (UTC: the "Z" means zero offset)
const sent = new Date("2026-11-11T21:19:13.213Z");
console.log("Stored: ", sent.toISOString());
// The obvious way: the SERVER formats the time once, in its own zone (UTC)
const serverText = sent.toLocaleTimeString("en-IN",
{ timeZone: "UTC", hour: "2-digit", minute: "2-digit" });
console.log("Server text:", serverText, " <- what Mom would see");
// The fix: send UTC, let each reader's device show it in THEIR time zone
for (const [who, zone] of [["Mom (Lucknow)", "Asia/Kolkata"],
["Neha (Dubai)", "Asia/Dubai"],
["Asha (Toronto)", "America/Toronto"]]) {
const local = sent.toLocaleString("en-IN", { timeZone: zone, day: "numeric",
month: "short", hour: "2-digit", minute: "2-digit" });
console.log(who.padEnd(15), local);
}
Output:
Stored: 2026-11-11T21:19:13.213Z
Server text: 09:19 pm <- what Mom would see
Mom (Lucknow) 12 Nov, 02:49 am
Neha (Dubai) 12 Nov, 01:19 am
Asha (Toronto) 11 Nov, 04:19 pm
The AI did this right: toISOString() on the server, toLocaleTimeString() in the browser.
Scrolling
Always jumping to the newest message yanks a reader who scrolled up to read something old. The AI's nearBottom check scrolls only if you were within 60 px of the bottom, or you sent the message. Real test: Neha scrolled to the top (scrollTop 0), Ravi sent a message, and her scrollTop stayed 0.
Attacking our own chat
Attack 1: spam (real)
// spam.js: one WebSocket connection, 1000 messages, as fast as possible
for (let i = 1; i <= 1000; i++)
spam.send(JSON.stringify({ type: 'message', name: 'Spammer', text: 'BUY NOW ' + i }));
1000 spam messages on Mom's screen after 1547 ms
messages on Mom's screen: 1003
Attack 2: another website reads the family room (real)
A page served from http://localhost:8417 (a different origin):
<!-- a page on http://localhost:8417 : some other website -->
<script>
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => ws.send(JSON.stringify({ type: 'join', room: 'family' }));
ws.onmessage = (e) => { /* print every message on this page */ };
</script>
It printed:
Mom: Diwali lunch at our place, 1 pm?
Ravi: Yes! I'll bring the gulab jamun
Mom: Asha is bringing the diyas
No error. The CORS rules from episode 15 guard fetch; they don't cover WebSockets. The browser connects and sends the page's address in the Origin header; the server must check it. OWASP WebSocket Security Cheat Sheet: "Validate the Origin header on every handshake. Always use an explicit allowlist of trusted origins." It also notes that "Browsers include cookies in WebSocket handshake requests", which is how Cross-Site WebSocket Hijacking (CSWSH) rides on a logged-in user.
Rate limiting (a ration shop)
| A ration shop | Our chat server |
|---|---|
| 5 kg per card per month | rate limit: 5 messages per 10 s per connection |
| "come back next month" | "Slow down: wait a few seconds", not delivered |
| a limit per household too | per-IP limit: all connections from one address |
A sliding window (run in the compiler)
WINDOW, LIMIT = 10, 5 # 5 messages per 10 seconds, per connection
sent = [] # times of this person's recent messages
def allow(now):
global sent
sent = [t for t in sent if now - t < WINDOW] # forget old ones
if len(sent) >= LIMIT:
return False
sent.append(now)
return True
# Mom chats normally: one message every 4 seconds
print("Mom: ", " ".join("ok" if allow(t) else "BLOCKED" for t in [0, 4, 8, 12, 16]))
sent = [] # a spammer: 8 messages in 0.7 seconds, then one more at 11 s
times = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 11]
print("Spammer:", " ".join("ok" if allow(t) else "BLOCKED" for t in times))
Output:
Mom: ok ok ok ok ok
Spammer: ok ok ok ok ok BLOCKED BLOCKED BLOCKED ok
Prompt 3, and the AI's real mistake
claude -p "I tested the WebSocket chat and found two problems. 1) Spam: one script sent 1000 messages to the family room and all 1000 appeared on Mom's screen in 1.5 seconds. Add rate limiting per connection: at most 5 messages in 10 seconds; after that reply with an error "Slow down: wait a few seconds" and don't deliver the message; if a connection keeps going (20 blocked messages), close it. 2) Another website on http://localhost:8417 opened new WebSocket('ws://localhost:3000'), joined "family" and read all our messages. Only allow connections whose Origin header is in an allowlist (default http://localhost:3000, configurable with an ALLOWED_ORIGINS environment variable); reject others during the handshake. Also add basic moderation: a list of blocked words in blocked-words.txt (one per line); a message containing one is rejected with a polite error. And keep at most 500 messages per room in memory. Then test all of it."
Write blocked-words.txt, server.js, test/server.test.js
Edit public/index.html give the text back if the server refuses it
Bash npm test → tests 11, pass 11
Write smoke.js "Starts the real server on port 3000 ... and pokes it"
Bash node smoke.js → [server] Error: listen EADDRINUSE ... :3000
→ its client connected to OUR running server
Reply: "It posted two messages to your family room as "Kid":
"you are Stupid" and "hi mom". I didn't stop your process.
... I then redid the check on port 3999."
The mistake: the agent's by-hand check assumed port 3000 was free. Our real server was running there, so its own server failed to start (EADDRINUSE) and its test client posted two test messages into the live family room. The agent noticed and said so. An agent that runs commands can touch real systems; tell it where it may test (another port, a copy of the data). Prompt 4 does exactly that.
Check the Origin during the handshake (server.js, run 3)
const ALLOWED_ORIGINS = new Set(
(process.env.ALLOWED_ORIGINS || 'http://localhost:3000')
.split(',').map(normalizeOrigin).filter(Boolean));
const wss = new WebSocketServer({
server,
maxPayload: 16 * 1024,
verifyClient: ({ origin }, done) => {
if (ALLOWED_ORIGINS.has(normalizeOrigin(origin))) return done(true);
console.warn(`Rejected WebSocket connection from origin: ${origin || '(none)'}`);
done(false, 403, 'Forbidden origin');
},
});
The sliding window in the server (run 3)
function allowMessage(ws) {
const now = Date.now();
ws.sentTimes = ws.sentTimes.filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
if (ws.sentTimes.length >= RATE_LIMIT_COUNT) return false;
ws.sentTimes.push(now);
return true;
}
if (!allowMessage(ws)) {
ws.blockedCount++;
if (ws.blockedCount >= MAX_BLOCKED_MESSAGES) {
ws.close(1008, 'Too many messages');
return;
}
return send(ws, { type: 'error', code: 'rate_limited',
error: 'Slow down: wait a few seconds' });
}
Close code 1008 means "policy violation": the client broke the server's rules.
The AI's tests (real, npm test)
✔ accepts the default allowed origin
✔ rejects another website (http://localhost:8417) during the handshake
✔ rejects a connection with no Origin header
✔ rejects look-alike origins
✔ ALLOWED_ORIGINS env variable replaces the default list
✔ the 1000-message spam script: Mom sees only 5, spammer is warned then disconnected
✔ normal pace is fine, the 6th message within 10s is refused, and the limit resets after the window
✔ limits are per connection: one spammer does not block others
✔ a message with a blocked word is rejected politely and not delivered
✔ a blocked word in the name is rejected too
✔ keeps at most 500 messages per room, dropping the oldest
ℹ tests 11
ℹ pass 11
Our retest (real, server restarted)
# Chromium console, the page on http://localhost:8417
WebSocket connection to 'ws://localhost:3000/' failed: Error during
WebSocket handshake: Unexpected response code: 403
# the spam script again: 1000 messages on one connection
Mom sees: 5
spammer gets: 19 x "Slow down: wait a few seconds"
connection closed: 1008 Too many messages
Basic moderation
Moderation keeps a conversation safe and polite. The basic version is a blocked-words list:
$ cat blocked-words.txt (the AI's starter list)
# Matching ignores case and only matches whole words ("ass" does not block "class").
idiot
stupid
shut up
Ravi: "Bhaiya, shut up about the crackers" → refused, text put back
Ravi: "Also: st*pid traffic near the station" → delivered
The refusal Ravi sees: "Sorry, your message wasn't sent because it contains a word that isn't allowed here. Please rephrase it." The AI warned: "Spelling tricks like "st*pid" or "s t u p i d" get through". A word list is a speed bump; real apps add a report button and people who can delete messages and mute users.
Per-IP limits (prompt 4)
Real bypass: 20 connections from one script, 5 messages each → Mom sees 100. The AI had warned in run 3: "that limit is per connection, so a script can reconnect or open several connections to get around it. A per-IP limit would be the next step".
claude -p "Your warning was right. I opened 20 connections from one script, sent 5 messages on each, and Mom's screen got all 100. Add limits per IP address as well: at most 5 open connections from one IP (reject the 6th during the handshake), and at most 10 messages in 10 seconds from one IP across all its connections, with the same \"Slow down\" error. Keep the per-connection limit. Don't connect to the server running on port 3000; use another port for your tests."
Edit server.js 5 connections per IP → 6th: 429 "Too many connections"
10 messages / 10 s per IP, across its connections
Edit test/server.test.js → 15 tests pass
Bash attack.js on port 3917
→ attacker connections opened: 4 | refused: 16 with [ 429 ]
→ Mom's screen got: 10
Reply: "Nothing touched the server on port 3000. ... everyone on
your home Wi-Fi usually shares one public address ..."
Our retest on port 3000: opened 4 · refused 16 with HTTP 429 · Mom sees 10 · 10 x "Slow down", and the server log: Rejected WebSocket connection: 127.0.0.1 already has 5 open.
The cost (real): Mom and Ravi on the same address sent 12 quick messages; the 11th and 12th got "Slow down". Every limit has a cost: pick numbers that fit real use (OWASP: "100 messages per minute is a common starting point"), and once the app has logins (episode 16), limit per account.
f897b49 Per-IP limits: 5 connections, 10 messages / 10 s (AI)
383b7f6 Rate limit, origin allowlist, blocked words, 500-message cap (AI)
5fbdf49 WebSockets + rooms (AI)
2b0ebc3 Family chat with polling (AI)
Real-time databases (checked on their own sites, 11 Nov 2026)
A real-time database pushes every change to the connected apps by itself (a railway departure board that updates on its own).
| Service | What its docs say | Free plan limits |
|---|---|---|
| Firebase Realtime Database | "a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime"; "Data is stored as JSON and synchronized in realtime to every connected client" | Spark: 100 simultaneous connections, 1 GB stored, 10 GB/month downloaded |
| Cloud Firestore | suggested by Firebase "for modern applications requiring richer data models" | Spark: 1 GiB stored, 50K reads/day, 20K writes/day, 20K deletes/day |
| Supabase Realtime | "Send and receive messages to connected clients": Broadcast, Presence ("who's online"), Postgres Changes | Free: 200 simultaneous connections, 100 messages/s, 256 KB broadcast payload. Pro: 500 connections, 500 messages/s |
You still decide who may read which room, rate limits and moderation. Limits change; check the pages before you build.
Common mistakes (real)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
setInterval(fetchMessages, 2000) |
834 ms late, 26 of 32 answers [] |
HTTP: only the browser can ask | a WebSocket |
| No rate limit | 1000 messages on Mom's screen in 1547 ms | sending is free | sliding window per connection and per IP |
| No Origin check | a page on localhost:8417 read the family room |
CORS doesn't cover WebSockets | verifyClient + allowlist → 403 |
| Per-connection limit only | 20 connections × 5 = 100 messages | a spammer opens more connections | per-IP limit: 6th connection → 429 |
| Agent tests on the port you use | "Kid: you are Stupid" in the live chat; EADDRINUSE |
it assumed port 3000 was free | tell it where to test |
| Server formats the time | 09:19 pm for a message sent at 2:49 am IST |
the server's zone is UTC | store UTC, format in the browser |
| Word filter only | st*pid delivered |
spelling tricks | report button, human moderators |
Mini project
- Ask an AI for a WebSocket chat with two rooms (or extend this one with a third room).
- Open it in two browsers and measure: how long until a message appears?
- Write a 10-line spam script. Is there a limit? If not, ask for one with exact numbers.
- Serve a page from another port that opens your WebSocket. Does it connect? Ask for an Origin allowlist.
- Add "who's online" (presence): the server sends the list of names in the room when someone joins or leaves.
- Tell the agent which port it may use for tests. Commit after every AI change.
Practice questions
- Why can't an HTTP server simply send Mom's message to Ravi's browser as soon as it arrives?
Answer
HTTP is request-response: every exchange starts with a request from the browser. The server can only answer; it can't start a conversation. Hence polling, or a WebSocket.
- With 10 people polling every 5 seconds all day, how many checks does the server get?
Answer
10 × 86,400 / 5 = 172,800 checks a day, and each person waits up to 5 seconds for a new message.
- What does
101 Switching Protocolsmean?
Answer
The server accepted the upgrade request in the WebSocket handshake. The same TCP connection now carries WebSocket messages in both directions.
- Mom is in the family room and Neha in cousins. Which line in the server stops Neha's message reaching Mom?
Answer
if (client.room === message.room) send(client, ...): the message goes only to connections whose room label matches.
- Why store
2026-11-11T21:19:13.213Zinstead of"2:49 am"?
Answer
The UTC instant is the same for everyone; each reader's device turns it into their own local time (2:49 am in India, 4:19 pm in Toronto). A formatted string is only right for one time zone.
- Our page had CORS protection for fetch in episode 15. Why could another website still read the chat?
Answer
CORS doesn't apply to WebSockets. The browser opens the connection and sends the Origin header; it's up to the server to refuse origins it doesn't trust.
- In the sliding-window code, why is the message at 11 seconds allowed?
Answer
All earlier messages were sent before second 1, so at 11 s they are more than 10 seconds old and are dropped from the list. Fewer than 5 remain, so it's allowed.
- Why did the per-IP limit block Mom and Ravi?
Answer
They were on the same address, so they shared one budget of 10 messages per 10 seconds. With logins, limit per account instead.
Quiz
What stops another website from using your WebSocket?
- A) CORS headers on the server, like episode 15
- B) The browser's same-origin policy blocks it automatically
- C) The server checks the Origin header during the handshake
- D) Using wss:// instead of ws://
Answer
C. WebSockets aren't covered by CORS or the same-origin rules for fetch; the browser just sends the Origin header. wss:// encrypts the line but lets any origin connect. The server must check Origin.
Interview questions
- Polling vs long polling vs WebSockets? Polling asks on a timer (simple, wasteful, delayed). Long polling keeps each request open until there's news, then asks again. WebSockets keep one connection open for two-way messages with low delay.
- How does a WebSocket connection start? An HTTP request with
Upgrade: websocketand aSec-WebSocket-Key; the server answers101 Switching ProtocolswithSec-WebSocket-Accept. - How do you scale a WebSocket chat beyond one server? Connections are spread across servers, so a message must reach every server that has room members: a pub/sub system (e.g. Redis) or a managed real-time service.
- What security checks does a WebSocket server need? Origin allowlist (CSWSH), authentication on connect, authorization per room, input validation, message size limits, rate limits,
wss://in production. - How would you rate limit chat messages? A sliding window or token bucket per user/connection and per IP, a clear error, disconnect repeat offenders; choose numbers that don't hurt normal users.
- How should timestamps be stored and shown? Store UTC (ISO 8601 or epoch), format in the reader's time zone on their device.
- What happens when the connection drops? The client reconnects with backoff, rejoins its room and reloads recent history; messages typed while offline should not be silently lost.
Glossary
| Term | Meaning (plain words) | Example |
|---|---|---|
| Real-time | arrives as it happens, with no visible delay | Mom's message on Ravi's screen in 43 ms |
| Polling | asking the server again and again on a timer | setInterval(fetchMessages, 2000) |
| Request / response | HTTP's pattern: the browser asks, the server answers | GET /api/messages?since=5 |
| WebSocket | one connection kept open for two-way messages | new WebSocket('ws://localhost:3000') |
| Handshake | the first exchange that sets up the connection | 101 Switching Protocols |
| Upgrade | asking to switch an HTTP connection to another protocol | Upgrade: websocket |
ws:// / wss:// |
plain / encrypted WebSocket addresses | wss:// on an https page |
ws library |
a popular WebSocket library for Node.js | npm install ws (8.22.2) |
| Sending / receiving | socket.send(...) / the message event |
ws.send(JSON.stringify(msg)) |
| Message type | a field saying what a JSON message means | join, history, message, error |
| Broadcast | sending one message to many connections | the loop over wss.clients |
| Room | a named group; messages go only to its members | family, cousins |
| History on join | recent messages sent when you enter a room | the last 50 |
| Reconnect / backoff | trying again, waiting longer each time | 1 s, 2 s, 4 s ... 15 s |
| Payload | the content of one message | maxPayload: 16 * 1024 |
| Timestamp | the exact moment something happened | 2026-11-11T21:19:13.213Z |
| UTC | the world's reference clock; Z in a timestamp |
IST = UTC + 5:30 |
| Time zone | a region's local clock rule | Asia/Kolkata, America/Toronto |
| ISO 8601 string | a standard text format for dates and times | toISOString() |
Scroll position (scrollTop) |
how far a box is scrolled from its top | 0 = at the top |
| Spam | unwanted messages sent in bulk | BUY NOW 1 ... BUY NOW 1000 |
| Rate limiting | allowing only N actions per time window | 5 messages per 10 s |
| Sliding window | counting only actions in the last N seconds | forget times older than 10 s |
| Close code 1008 | "policy violation": closed for breaking rules | ws.close(1008, 'Too many messages') |
| Origin header | the page's scheme + host + port, sent by the browser | http://localhost:8417 |
| Allowlist | the list of things that are allowed; everything else is refused | ALLOWED_ORIGINS |
| CSWSH | Cross-Site WebSocket Hijacking: another site uses your WebSocket as you | the page on port 8417 |
verifyClient |
a ws option that accepts or refuses a handshake |
done(false, 403, 'Forbidden origin') |
| 403 Forbidden | the server refuses a known request | the other website's handshake |
| 429 Too Many Requests | over a limit | the 6th connection from one IP |
| IP address | the network address a connection comes from | 127.0.0.1 |
| Per-IP limit | a limit shared by all connections from one address | 5 connections, 10 messages / 10 s |
| Moderation | keeping a conversation safe and polite | blocked words, delete, mute |
| Blocked-words list | words that make a message refused | blocked-words.txt |
EADDRINUSE |
"address already in use": another program has that port | the AI's server on port 3000 |
| Smoke test | a quick by-hand check that the basics work | the AI's smoke.js |
| Real-time database | a database that pushes changes to connected apps | Firebase Realtime Database |
| Presence | knowing who's online | Supabase Presence |
| Environment variable | a setting given to a program from outside its code | ALLOWED_ORIGINS=https://chat.example.com |
Summary
- Polling is slow or wasteful: real numbers were 834 ms late and 26 of 32 answers empty; at family scale, 432,000 checks for 200 messages. HTTP only lets the browser ask.
- A WebSocket is one open, two-way line, set up by a handshake (
101 Switching Protocols). The server sends messages the moment they happen: 43-75 ms in our test. - Rooms are labels on connections; joining sends recent history. Store times in UTC and show them in each reader's time zone. Scroll only when the reader is near the bottom.
- Attack your own app: rate limit per connection and per IP (sliding window), check the Origin header (CORS doesn't cover WebSockets), and treat a blocked-words list as a speed bump.
- The AI's real mistake: its smoke test ran against our live server and posted test messages into the family room. Tell agents where they may test.
- Real-time databases (Firebase, Supabase) can run the pipe; you still own permissions, limits and moderation.
- Next: episode 18, a Telegram or Discord bot.