API-73Required
Limit the connections and messages of each client
Limit how many connections each account may hold open, how large one message may be and how many messages it may send per minute. Close or refuse the rest.
How to do it
One script can open thousands of sockets or send one huge message, and every open socket holds memory. Start with 10 connections per account, 64 KB per message and 100 messages a minute. Count by address only when nobody is signed in. Set the size cap in the WebSocket library, so it stops reading before the message is built in memory. Refuse an extra connection with 429 during the handshake, and close a socket that sends too much with code 1008 or 1009. Caps on ordinary requests are in cap the size of every request and answer. Request rates are in limit requests per client.
Examples
JavaScript example
import { WebSocketServer } from 'ws';
const MAX_MESSAGE_BYTES = 64 * 1024;
const MAX_CONNECTIONS_PER_ACCOUNT = 10;
const server = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
httpServer.on('upgrade', (request, socket, head) => {
const account = accountFrom(request);
if (openCount(account) >= MAX_CONNECTIONS_PER_ACCOUNT) {
socket.end('HTTP/1.1 429 Too Many Requests\r\nRetry-After: 30\r\n\r\n');
return;
}
server.handleUpgrade(request, socket, head, ws => server.emit('connection', ws, request));
});
Python example
import websockets
MAX_MESSAGE_BYTES = 64 * 1024
async def main():
async with websockets.serve(handle_socket, "0.0.0.0", 8080, max_size=MAX_MESSAGE_BYTES) as server:
await server.serve_forever()
How to check
From one test account, open 11 connections, send a 65 KB message and send 101 messages in a minute. The 11th connection gets 429, and the large message and the 101st message close the socket.
Sources
Related rules
- Cap the size of every request and answer in Security testing
- Limit requests per client in Security testing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/live-connections/connection-limits">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.