Lesson 26 / 32
Validation, Size Limits and Rate Limits
Validate every incoming message, cap message size and rate per connection, and always use wss.
By Rahul Agarwal · 15 years in web development
Treat every message like an HTTP request body
Once a socket is open, developers often relax and trust whatever arrives. Do not. Every message is untrusted input, exactly like a POST body. Parse defensively: invalid JSON should not crash the handler or the process. Validate shape and type with a schema (Zod, JSON Schema, Pydantic) and route only known type values. Authorise the action against the connection's user: being in a socket does not mean being allowed to delete a room. Cap sizes: set maxPayload in ws so a 50 MB message is rejected with close code 1009 before it fills memory. Rate-limit per connection and per user, for example a token bucket allowing a few messages per second, because one open socket can fire thousands of messages with no HTTP overhead to slow it down. Escape user content when rendering to prevent XSS in chat. And use wss:// everywhere: it encrypts traffic and also passes through corporate proxies far more reliably than plain ws://.
Defensive message parsing
Unknown types and malformed payloads are rejected with a reason instead of throwing. In a server you would count rejections and close abusive sockets with 1008.
const handlers = {
join: (msg) => typeof msg.room === 'string' && msg.room.length <= 64,
chat: (msg) => typeof msg.text === 'string' && msg.text.length <= 2000,
};
function parseMessage(raw) {
let msg;
try {
msg = JSON.parse(raw);
} catch {
return { ok: false, error: 'not JSON' };
}
const check = handlers[msg?.type];
if (!check) return { ok: false, error: `unknown type ${msg?.type}` };
if (!check(msg)) return { ok: false, error: `bad ${msg.type} payload` };
return { ok: true, msg };
}
for (const raw of [
'{"type":"chat","text":"hi"}',
'{"type":"chat","text":42}',
'{"type":"admin","cmd":"drop"}',
'hello',
]) {
const r = parseMessage(raw);
console.log(r.ok ? `accepted ${r.msg.type}` : `rejected: ${r.error}`);
}
Output:
accepted chat rejected: bad chat payload rejected: unknown type admin rejected: not JSON
Rate limits need memory too
Store the per-connection token bucket on the socket object so it is freed when the socket closes. Add a per-user limit in Redis if one user can open many connections across servers.
Quick check: Which ws option protects the server from a client sending a single 200 MB message?
- `perMessageDeflate: true`
- `maxPayload` set to a sensible limit
- `clientTracking: false`
- `noServer: true`
Answer
`maxPayload` set to a sensible limit — `maxPayload` caps the size of an incoming message; larger ones close the connection with 1009 instead of being buffered.