Video in progress

How do you protect a public WebSocket endpoint from abuse and DDoS?

Protection works at several levels: L3/L4 and the edge (connection count, per-IP rate), the handshake (auth, origin, connection quota), and inside the connection, limits on message rate, size and number of subscriptions. For those who exceed them, an explicit policy: slow down, reject or disconnect.

📖 Answer

WebSocket gets around HTTP rate limits: one handshake counts as one "request", and then a million messages an hour can flow over a single connection. Typical API gateway limits don't see this.

The layers:

Edge (CDN, L4 balancer). New connection rate per IP, and the number of open connections from one IP. SYN floods and simple bots stop here. Don't forget corporate users behind NAT (thousands of people on one IP): if the limit is tight, you block a whole office.

Handshake. The check happens after TLS and the upgrade, but before business logic. Invalid token: reject immediately, without touching the DB. A per-user quota: one account may have at most N connections at once (say 10). Beyond that, the oldest is closed.

Inside the connection.

  • a token bucket per session: for example 20 messages per second, with a burst of up to 50;
  • a message size limit (messageSizeLimit);
  • a limit on the number of subscriptions: a client subscribed to 10,000 topics slows down the broker;
  • a separate, stricter limit for expensive operations (search, loading history).

In Spring STOMP you can do this in an inbound interceptor:

public Message<?> preSend(Message<?> m, MessageChannel ch) {
    var acc = StompHeaderAccessor.wrap(m);
    if (StompCommand.SEND.equals(acc.getCommand())
            && !buckets.get(acc.getSessionId()).tryConsume(1)) {
        return null; // the message is dropped
    }
    return m;
}

Policy: a one-time excess, drop silently. A persistent excess, disconnect with 1008 and a temporary ban for the user. Every decision is recorded in metrics, otherwise you won't see the false positives.

Keep one thing in mind: in a multi-node system the limits are local. If one user opens 10 connections on 10 nodes, each node counts them separately. If you need a global per-account limit, use a counter in Redis, but sync it once a second rather than on every message.