Video in progress
All traffic goes through an API gateway (for example Spring Cloud Gateway). What do you watch for when routing WebSocket through the same gateway?
The gateway holds two connections per client (client side and backend side), so its memory, file descriptors and idle timeouts must be sized for the number of connections. Auth happens only at the handshake, and a gateway deploy cuts every WebSocket.
📖 Answer
Technically, wiring it up is simple. In Spring Cloud Gateway the route URI is given with ws:// or lb:ws://, and the gateway passes the upgrade through to the backend:
spring:
cloud:
gateway:
routes:
- id: realtime
uri: lb:ws://realtime-service
predicates:
- Path=/ws/**
The problems come later.
Double the resources. With REST the gateway holds a connection for milliseconds. With WebSocket, for hours: one inbound and one backend connection per client. With 100,000 clients, that's 200,000 sockets on the gateway. If the gateway was sized for REST traffic, WebSockets slowly eat its memory and REST latency gets worse too.
Deploy coupling. Every restart of the gateway cuts all WebSockets, even if nobody touched the real-time service. The gateway is usually a component that changes often (new routes, filters).
Auth and filters. The JWT filter on the gateway sees only the handshake request. It doesn't check the frames inside the connection, and rate limits don't apply to frames either. The gateway and the service must understand the same way how the token is obtained in the handshake (cookie, query ticket). If you leave the token in the query, mask it in the gateway access logs.
Chain of timeouts. Client → LB → gateway → service: every hop has an idle timeout, and the smallest wins. The heartbeat interval must be smaller than that smallest one.
My usual choice: for a large audience, a separate path for WebSocket: on the load balancer the /ws path bypasses the gateway and goes straight to the real-time service (or to its own edge layer). The service does the auth itself. In a small system, routing through the gateway is convenient, you just need to plan its resources and deploy schedule with WebSocket in mind.
Sign up to mark studied questions and save your progress.