WebSocket connection closing after 60 or 100 seconds
Recently I’ve had a strange problem occur after deploying one of my web projects. The WebSocket connection would close exactly after 60 seconds with the error code 1006.
If you are using NGINX as a reverse proxy, this is the default timeout, when there are no messages getting sent/received. To change that, edit your NGINX WebSocket proxy to allow longer timeouts:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 900s;
proxy_send_timeout 900s;
Here I’ve set the read and send timeouts to 900 seconds.
After doing this I’ve faced the same issue again but exactly after 100 seconds!
Well here’s the second reason: if you’re proxying your site through Cloudflare, their default WebSocket timeout is 100 seconds.
Cloudflare recommends implementing a keep-alive. However, after further research I’ve found that ASP.NET Core WebSockets already do that. So why is the connection closing?
Well, the default keep-alive interval is 2 minutes on ASP.NET Core. This is too slow for both NGINX and Cloudflare. Here’s how to change that:
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(50)
});
Change the interval to 50 seconds, which would include both NGINX and Cloudflare, thus the NGINX config mentioned previously can be ignored.
Now the connection is kept alive properly. 🥳