Facebook Pixel

How do I load balance WebSocket connections?

Use ip_hash in the upstream block for sticky sessions. This ensures the same client always connects to the same Node.js instance. Without ip_hash, the HTTP upgrade and WebSocket frames might go to different instances, causing connection failures.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Adding WebSocket Support to Nginx Socket.io Proxy Configuration

Add proxy_http_version 1.1, proxy_set_header Upgrade $http_upgrade, and proxy_set_header Connection 'upgrade' to the location block. These headers tell Nginx to upgrade the HTTP connection to WebSocket and forward it to the backend. Without them, Socket.io won't work.

Missing the Upgrade and Connection headers. WebSockets start as HTTP and upgrade to WebSocket. Without proxy_set_header Upgrade and Connection 'upgrade', Nginx doesn't forward the upgrade request, and the WebSocket connection fails. Also, HTTP/1.0 (default) doesn't support upgrades use proxy_http_version 1.1.

Set proxy_read_timeout and proxy_send_timeout to 86400s (24 hours). WebSocket connections are long-lived. The default 60-second timeout causes Nginx to close the connection, breaking the WebSocket. Long timeouts keep connections alive.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0