I build a system that runs agents on remote machines, and a phone app talks to a machine over a WebSocket through a relay. At one point, after the credentials were renewed on the other side, the app stopped receiving replies. No error, no log, no crash. Reopening the screen fixed it.
The cause was that cleanup lived in the socket’s close event. When the credentials were renewed, the app closed the socket itself, waited for close, and only then told each stream’s owner that the stream had ended. In the React Native environment in question, a socket closed by the app itself did not deliver that event. Nobody was told, nothing resubscribed, and the connection object and stream registrations just stayed there.
What I took from it: a WebSocket’s close event and its readyState only tell you what the socket last reported. Whether the connection is alive is something the app decides and checks for itself. There are three places where that matters.
1. When you decide to close, clean up right there
An event is the right place to learn what happened to you: the peer closed, the network dropped. It is not the place to record a decision you made. Even by the spec, the close for a connection you closed arrives after the closing handshake completes or the connection is torn down (WHATWG spec), and that can take a long time if the peer is gone. That the event never came in our environment is observed behavior, not a documented guarantee. The conclusion is the same either way.
Put cleanup in one idempotent function, and call it both from the events and from end(), the method used whenever we close the socket ourselves.
// Settle what rode the socket the moment we decide to close it.
// The socket's close event is a report we may or may not get.
export class Connection {
pending = new Map(); // request id -> { reject }
streams = new Map(); // stream id -> onFrame
#settled = false;
constructor(socket) {
this.socket = socket;
// Still the path for closes we did not start: peer, network, server.
socket.addEventListener("close", this.#settle);
socket.addEventListener("error", this.#settle);
}
// Idempotent: every path may call it, only the first does anything.
#settle = () => {
if (this.#settled) return;
this.#settled = true;
const pending = [...this.pending.values()];
const streams = [...this.streams.values()];
this.pending.clear(); // empty the tables before anyone is told
this.streams.clear();
for (const p of pending) guard(() => p.reject(new Error("connection closed")));
for (const onFrame of streams) guard(() => onFrame({ closed: true }));
};
// Every way of ending the connection goes through here.
end(code, reason) {
try {
this.socket.close(code, reason);
} finally {
this.#settle();
}
}
}
function guard(fn) {
try { fn(); } catch (e) { console.error(e); } // one bad listener must not silence the rest
}
Three points:
- Make it idempotent. In environments that do deliver the event, it arrives after
end()as well. The second call does nothing. - Call it from
finally.close()can throw, for example on an invalid code. Cleanup placed after it would be skipped on exactly that path. - Empty the tables before notifying. An owner may react by opening a new connection, and a half-cleaned table would break it.
The tests use a stand-in socket that never fires close after close(). The original bug is kept as a test too, asserting the wrong behavior on purpose.
test("the old code: close the socket and wait for the event", async () => {
const sock = new FakeSocket(false);
const frames = subscribe(new Connection(sock));
sock.close();
await tick();
assert.deepEqual(frames, []); // nobody was told, so nobody resubscribes
});
test("end() settles even if close never fires", () => {
const conn = new Connection(new FakeSocket(false));
const frames = subscribe(conn);
conn.end(1000, "renew");
assert.deepEqual(frames, [{ closed: true }]);
});
The fix was not just adding end(). It was routing every way of ending the connection through end(): renewal, expiry, heartbeat timeout, malformed frames. One raw socket.close() left anywhere brings the silent stop back for that cause.
2. Probe only a quiet connection, with an application-level ping
A TCP connection whose peer vanished without a word looks open until a write fails or a timer fires. How long the kernel stays unaware is measured in the experiment on dead TCP peers: a side that only reads waits forever. The app needs its own timer.
The WebSocket in browsers and React Native has no API for sending a protocol ping and waiting for the pong. React Native’s source (0.87.1) has a ping() method, but I found no event for receiving a pong. So the liveness check is a message the peer’s application answers. It is a real message, and on a relay that bills incoming messages it costs money.
So every received frame counts as proof of life. A probe goes out only after nothing has arrived for a while, and its deadline is measured from when it was sent.
// Called from a fixed-interval tick. Any frame from the peer counts as proof
// of life, so only a quiet connection is probed, and a probe's deadline is
// fixed at the moment it was sent.
export function heartbeatAction(lastReceivedAt, pendingPingAt, now, intervalMs, timeoutMs) {
if (pendingPingAt !== null) {
return now - pendingPingAt >= timeoutMs ? "close" : "wait"; // never extended
}
return now - lastReceivedAt >= intervalMs ? "ping" : "wait";
}
It is a function of timestamps only, so it can be tested without fake timers. Every received frame updates lastReceivedAt and resets pendingPingAt to null. A connection that receives something every few seconds never gets a probe.
With a tick at the same period as the interval, the worst-case detection time is two intervals plus the timeout. Take a 10-second interval and a 25-second timeout (illustration values), with a frame arriving 1 ms after a tick. At the next tick the connection has been quiet for 9.999 s, so nothing is sent. The tick after that (20 s) sends the probe, and the connection closes at 45 s. To shorten this, tick faster than the interval.
test("traffic just after a tick delays the ping, not the deadline", () => {
const received = 1; // a frame arrived 1 ms after the tick at 0
assert.equal(act(received, null, 10_000, I, T), "wait"); // only 9.999 s quiet
assert.equal(act(received, null, 20_000, I, T), "ping");
const pingAt = 20_000;
for (const now of [30_000, 40_000, 44_999]) assert.equal(act(received, pingAt, now, I, T), "wait");
assert.equal(act(received, pingAt, 45_000, I, T), "close"); // 2 intervals + timeout after the last frame
});
The full tests (connection.test.mjs, heartbeat.test.mjs), run with `node --test`
import { test } from "node:test";
import assert from "node:assert/strict";
import { Connection } from "./connection.mjs";
// A socket that can be told never to fire "close" after close().
class FakeSocket {
listeners = {};
constructor(emitsClose) { this.emitsClose = emitsClose; }
addEventListener(type, l) { (this.listeners[type] ??= []).push(l); }
close() { if (this.emitsClose) queueMicrotask(() => this.listeners.close?.forEach((l) => l())); }
}
const subscribe = (conn) => { const frames = []; conn.streams.set("s1", (f) => frames.push(f)); return frames; };
const tick = () => new Promise((r) => setTimeout(r, 10));
test("the old code: close the socket and wait for the event", async () => {
const sock = new FakeSocket(false);
const frames = subscribe(new Connection(sock));
sock.close();
await tick();
assert.deepEqual(frames, []); // nobody was told, so nobody resubscribes
});
test("end() settles even if close never fires", () => {
const conn = new Connection(new FakeSocket(false));
const frames = subscribe(conn);
conn.end(1000, "renew");
assert.deepEqual(frames, [{ closed: true }]);
});
test("a late close event does not notify twice", async () => {
const conn = new Connection(new FakeSocket(true));
const frames = subscribe(conn);
conn.end(1000, "renew");
await tick();
assert.equal(frames.length, 1);
});
test("settles even when close() throws", () => {
const sock = new FakeSocket(false);
sock.close = () => { throw new SyntaxError("bad code"); };
const conn = new Connection(sock);
const frames = subscribe(conn);
assert.throws(() => conn.end(999, "x"), SyntaxError);
assert.deepEqual(frames, [{ closed: true }]);
});
import { test } from "node:test";
import assert from "node:assert/strict";
import { heartbeatAction as act } from "./heartbeat.mjs";
const I = 10_000, T = 25_000; // illustration values, not a recommendation
test("traffic just after a tick delays the ping, not the deadline", () => {
const received = 1; // a frame arrived 1 ms after the tick at 0
assert.equal(act(received, null, 10_000, I, T), "wait"); // only 9.999 s quiet
assert.equal(act(received, null, 20_000, I, T), "ping");
const pingAt = 20_000;
for (const now of [30_000, 40_000, 44_999]) assert.equal(act(received, pingAt, now, I, T), "wait");
assert.equal(act(received, pingAt, 45_000, I, T), "close"); // 2 intervals + timeout after the last frame
});
test("a busy connection is never probed", () => {
for (let now = 0; now < 120_000; now += 1_000) assert.equal(act(now - 3_000, null, now, I, T), "wait");
});
Use a monotonic clock such as performance.now() for now, not the wall clock. Timers do not run while the app is suspended, so the first tick after resuming may find a probe sent long ago. Then the connection closes right away. A connection that spanned a suspension is more likely dead than alive.
3. Back in the foreground: check, rebuild, catch up
Apple’s archived networking guide says an app “may be suspended when it goes into the background, which means that it can no longer handle network traffic. In some cases, existing connections may even close while your app is suspended.” (Apple). Android’s Doze “suspends network access” (Android). Neither says after how many seconds.
While the app is stopped, its code does not run. The only moment the app reliably gets to act is when it comes back to the foreground. A readyState === 1 (OPEN) at that point is a memory from the last event it processed.
On Linux I froze a client process with SIGSTOP and watched what the server sees. It stands in for the OS suspending an app and is not the same thing: the kernel and TCP stay alive, only the code stops. The server sends a message and a ping every 500 ms and drops a client after 3 s without a pong.
[ 1.1s] server: sent=2 handed-to-kernel=1 bufferedAmount=0 quiet-for=496 ms readyState=1
[ 2.0s] >>> SIGSTOP the client process
[ 2.1s] server: sent=4 handed-to-kernel=3 bufferedAmount=0 quiet-for=499 ms readyState=1
[ 3.1s] server: sent=6 handed-to-kernel=5 bufferedAmount=0 quiet-for=1501 ms readyState=1
[ 4.1s] server: sent=8 handed-to-kernel=7 bufferedAmount=0 quiet-for=2502 ms readyState=1
[ 4.6s] server: no pong for 3002 ms -> declare the client gone, terminate()
[ 4.7s] server: close event
[ 9.0s] >>> SIGCONT the client process
client: close event, code 1006, messages seen: 9
While the client was frozen, the server’s send() kept succeeding and bufferedAmount stayed at 0. The only sign of trouble was the missing pong. After resuming, the client processed the 9 messages the kernel had held, and only then learned, as code 1006, that the connection had been closed. Until then, its socket would have looked OPEN.
freeze_lab.mjs (the freeze experiment)
// What does a server see when the client process is frozen (SIGSTOP) but its kernel and network are fine?
// Linux stand-in for "the OS suspended the app". Run: node freeze_lab.mjs
import { WebSocketServer } from "ws";
import { spawn } from "node:child_process";
const t0 = Date.now(); const at = () => `[${((Date.now() - t0) / 1000).toFixed(1).padStart(4)}s]`;
const wss = new WebSocketServer({ port: 0 });
await new Promise((r) => wss.on("listening", r));
const port = wss.address().port;
const client = spawn(process.execPath, ["-e", `
const WebSocket = require("ws"); let n = 0;
const ws = new WebSocket("ws://127.0.0.1:${port}");
ws.on("message", () => n++);
ws.on("close", (c) => { console.log("client: close event, code " + c + ", messages seen: " + n); process.exit(0); });
ws.on("error", (e) => console.log("client: error " + e.code));
`], { stdio: "inherit", cwd: process.cwd() });
wss.on("connection", (ws) => {
let seq = 0, lastPong = Date.now(), sent = 0, acked = 0;
ws.on("pong", () => { lastPong = Date.now(); });
const tick = setInterval(() => {
ws.send(`m${++seq}`, () => acked++); // callback = handed to the kernel
sent++;
ws.ping();
const quiet = Date.now() - lastPong;
if (seq % 2 === 0) console.log(`${at()} server: sent=${sent} handed-to-kernel=${acked} bufferedAmount=${ws.bufferedAmount} quiet-for=${quiet} ms readyState=${ws.readyState}`);
if (quiet > 3000) {
console.log(`${at()} server: no pong for ${quiet} ms -> declare the client gone, terminate()`);
clearInterval(tick); ws.terminate();
}
}, 500);
ws.on("close", () => console.log(`${at()} server: close event`));
});
setTimeout(() => { console.log(`${at()} >>> SIGSTOP the client process`); client.kill("SIGSTOP"); }, 2000);
setTimeout(() => { console.log(`${at()} >>> SIGCONT the client process`); client.kill("SIGCONT"); }, 9000);
setTimeout(() => process.exit(0), 11000);
So every time the app becomes active, it sends an application-level ping with a deadline. Without an answer, it closes, reconnects, and catches up on what happened while it was away. Reconnecting alone silently loses the messages from that gap.
// On "active": do not trust readyState. Prove the socket is alive, otherwise rebuild it and catch up.
export function keepFresh({ lifecycle, connect, catchUp, probeMs = 2000, log = () => {} }) {
let socket = null, busy = null;
const probe = (ws) => new Promise((resolve) => { // a round trip that the peer *application* must answer
if (!ws || ws.readyState !== 1) return resolve(false);
const done = (ok) => { clearTimeout(timer); ws.removeEventListener("message", onMessage); resolve(ok); };
const onMessage = (e) => { if (e.data === "pong") done(true); };
const timer = setTimeout(() => done(false), probeMs);
ws.addEventListener("message", onMessage);
try { ws.send("ping"); } catch { done(false); }
});
async function ensure(reason) {
if (busy) return busy; // "active" can fire repeatedly
return (busy = (async () => {
if (await probe(socket)) { log(`${reason}: socket proved alive, nothing to do`); return; }
log(`${reason}: socket is ${socket ? "readyState " + socket.readyState : "missing"} or silent -> rebuild`);
try { socket?.close(); } catch {}
socket = await connect();
await catchUp(); // whatever was missed while we were away
})().finally(() => { busy = null; }));
}
lifecycle.addEventListener("change", (state) => { if (state === "active") ensure("foreground"); });
return { start: () => ensure("start"), get socket() { return socket; } };
}
lifecycle takes anything shaped like React Native’s AppState. busy folds back-to-back active events into one check. The probe returns false for a socket that is not OPEN as well, so “dead” and “silent” take the same path.
I ran four cases with a fake AppState and a real ws server (probe deadline 500 ms):
[ 516 ms] --- case 2: the connection silently died while we were away (server stops reading, so no pong)
[ 517 ms] client still thinks: readyState=1 (1 = OPEN)
[ 1017 ms] foreground: socket is readyState 1 or silent -> rebuild
[ 1418 ms] connects=2 catchUps=2
[ 1418 ms] --- case 3: the server closed it while we were away
[ 1520 ms] foreground: socket is readyState 3 or silent -> rebuild
[ 1820 ms] connects=3 catchUps=3
[ 1821 ms] --- case 4: three 'active' events in a row
[ 1822 ms] foreground: socket proved alive, nothing to do
[ 2121 ms] connects=3 catchUps=3
In case 2, the client kept saying readyState=1, but the probe expired, and the routine rebuilt and caught up. A check that only reads readyState misses this. In case 4, three active events became one probe. In case 1 (a healthy connection), the probe passed and nothing happened.
test.mjs (the four cases)
import { WebSocketServer, WebSocket } from "ws";
import { EventEmitter } from "node:events";
import { keepFresh } from "./keep_fresh.mjs";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const wss = new WebSocketServer({ port: 0 }); await new Promise((r) => wss.on("listening", r));
const serverSide = [];
wss.on("connection", (ws) => { serverSide.push(ws); ws.on("message", (m) => { if (m.toString() === "ping") ws.send("pong"); }); });
const url = `ws://127.0.0.1:${wss.address().port}`;
class FakeAppState extends EventEmitter { addEventListener(t, f) { this.on(t, f); } } // same shape as React Native's AppState.addEventListener
const lifecycle = new FakeAppState();
let catchUps = 0, connects = 0;
const t0 = Date.now(); const log = (m) => console.log(`[${String(Date.now() - t0).padStart(5)} ms] ${m}`);
const app = keepFresh({
lifecycle, log, probeMs: 500,
connect: async () => { connects++; const c = new WebSocket(url); await new Promise((r) => c.on("open", r)); c.on("error", () => {}); return c; },
catchUp: async () => { catchUps++; },
});
await app.start(); await sleep(100);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 1: app goes background and comes back; connection is fine");
lifecycle.emit("change", "background"); await sleep(100); lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 2: the connection silently died while we were away (server stops reading, so no pong)");
serverSide.at(-1)._socket.pause();
log(`client still thinks: readyState=${app.socket.readyState} (1 = OPEN)`);
lifecycle.emit("change", "active"); await sleep(900);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 3: the server closed it while we were away");
serverSide.at(-1).terminate(); await sleep(100);
lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 4: three 'active' events in a row");
lifecycle.emit("change", "active"); lifecycle.emit("change", "active"); lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
process.exit(0);
The server also needs a deadline to give up on a frozen client. A frozen client is not a closed client. A short deadline also evicts clients that merely have a bad network. A long one keeps state for dead clients.
Common mistakes
- Cleaning up in the
closeevent after closing the socket yourself. Where the event does not come, the app stops without an error. - Running cleanup twice. Owners are notified twice and resubscribe twice.
- Pinging a busy connection on a fixed schedule. Data frames are proof of life too.
- Extending the probe deadline on every tick. A dead connection never closes.
- Trusting
readyStateafter resuming. The UI says “connected” and nothing arrives. - Reconnecting without catching up. No error, but the messages from the gap are missing. Catching up needs a server API that can read from the last position you saw (resumable streams).
When not to use this
- If both ends are servers that can use protocol ping/pong, use that. Application-level checks exist because browser scripts cannot send pings.
- Connections that last a few seconds do not need a liveness mechanism.
- If you also need to know about events while the app is in the background, notify with push and run this routine when the app comes back.
A socket’s state is the last thing it told you
A socket’s state is the last thing you heard from it. When you decide to close, clean up yourself. When it goes quiet, ask. When you come back, check before you use it.