Skip to content

Commit 13390ca

Browse files
committed
Disconnect the WebSocket after an idle period
After deploying the WebSocket reconnection logic, our total connection count slowly grew until nginx stopped being able to handle new connections, leading to a severely degraded experience. Closing the WebSocket for idle consumers should reduce the concurrent connection count. Eventually we will need to handle re-starting the connection anyway (and potentially only starting it on demand).
1 parent f48d928 commit 13390ca

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

ui/frontend/websocketMiddleware.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,35 @@ const openWebSocket = (currentLocation: Location) => {
4444
// https://exponentialbackoffcalculator.com
4545
const backoffMs = (n: number) => Math.min(100 * Math.pow(2, n), 10000);
4646

47+
const idleTimeoutMs = 60 * 60 * 1000;
48+
4749
export const websocketMiddleware =
4850
(window: Window): Middleware =>
4951
(store) => {
5052
let socket: WebSocket | null = null;
5153
let wasConnected = false;
5254
let reconnectAttempt = 0;
5355

56+
let timeout: number | null = null;
57+
const resetTimeout = () => {
58+
if (timeout) {
59+
window.clearTimeout(timeout);
60+
}
61+
62+
timeout = window.setTimeout(() => {
63+
if (!socket) {
64+
return;
65+
}
66+
67+
socket.close();
68+
}, idleTimeoutMs);
69+
};
70+
5471
const connect = () => {
5572
socket = openWebSocket(window.location);
56-
5773
if (socket) {
74+
resetTimeout();
75+
5876
socket.addEventListener('open', () => {
5977
store.dispatch(websocketConnected());
6078

@@ -85,6 +103,7 @@ export const websocketMiddleware =
85103
const rawMessage = JSON.parse(event.data);
86104
const message = WSMessageResponse.parse(rawMessage);
87105
store.dispatch(message);
106+
resetTimeout();
88107
} catch (e) {
89108
console.log('Unable to parse WebSocket message', event.data, e);
90109
}
@@ -110,6 +129,7 @@ export const websocketMiddleware =
110129
if (socket && socket.readyState == socket.OPEN && sendActionOnWebsocket(action)) {
111130
const message = JSON.stringify(action);
112131
socket.send(message);
132+
resetTimeout();
113133
}
114134

115135
next(action);

0 commit comments

Comments
 (0)