resilient-ws-client
v1.0.0
Published
A reconnecting WebSocket client: state machine, exponential backoff with jitter, and a send queue with acknowledgement-based redelivery. No dependencies.
Maintainers
Readme
resilient-ws-client
A reconnecting WebSocket client that doesn't lose messages. State machine, exponential backoff with jitter, and a send queue with acknowledgement-based redelivery. No dependencies, no DOM required.
npm install resilient-ws-clientThe problem it solves
A plain new WebSocket(url) gives you exactly one connection attempt. When
it drops — a phone switching from Wi-Fi to cellular, a server redeploying, a
proxy timing out an idle connection — the application is left to notice the
close event, decide whether and when to retry, and figure out which of the
messages it sent before the drop actually made it to the server.
Reconnecting badly is worse than not reconnecting: retrying immediately in a loop hammers a struggling server, and thousands of clients all retrying on the same fixed delay hit it in lockstep. Resending everything blindly duplicates whatever the server did receive; resending nothing silently loses whatever it didn't.
import { createClient } from "resilient-ws-client";
const client = createClient({
url: "wss://example.com/ws",
onState: (state) => console.log("state:", state),
onMessage: (data) => console.log("message:", data),
});
client.connect();
client.send({ type: "subscribe", channel: "orders" });
// Sent once connected. If the connection drops before the server
// acknowledges it, it is resent automatically on the next reconnect —
// and never sent again once the server does acknowledge it.State machine
disconnected -> connecting -> connected -> ready- disconnected – no connection (initial state, or after a connection loss)
- connecting – the WebSocket handshake is in progress
- connected – the WebSocket connection is open (transport level)
- ready – the first message from the server has arrived (application-level confirmation; a server that rejects the connection at the application layer and closes without sending anything never reaches this state)
Reconnection
Exponential backoff with jitter: baseMs * factor^attempt, capped at
capMs, with ±10% jitter so that many clients reconnecting after the same
outage don't all retry in the same instant. The attempt counter resets on
every successful connection.
import { computeBackoffMs } from "resilient-ws-client";
computeBackoffMs(0); // ~500ms (first retry)
computeBackoffMs(1); // ~1000ms
computeBackoffMs(2); // ~2000ms
computeBackoffMs(6); // capped at 30000msTune it with backoffBaseMs, backoffFactor, backoffCapMs on
createClient, or call computeBackoffMs directly — it's a pure function.
Send queue and redelivery
Every message passed to send() gets an auto-generated id and is added to
an in-memory queue before being sent (or before being held back, if not
currently connected). It is removed from the queue only when the server
sends back { type: "ack", id }. On every reconnect, everything still in the
queue is resent, in the order it was originally sent — so a drop between
sending a message and receiving its acknowledgement results in at most one
resend, never a silent loss.
const id = client.send({ type: "order", sku: "abc-123" });
client.pendingCount(); // messages sent but not yet acknowledgedThe server side of the contract is one line: respond to a received message
with { type: "ack", id: <same id> } once it's been durably handled.
API
createClient(options)
| Option | Default | |
| --- | --- | --- |
| url | required | the WebSocket URL |
| token | "" | sent as the WebSocket sub-protocol, the common way to pass a bearer token during the handshake |
| WebSocketImpl | globalThis.WebSocket | inject ws in Node, or a fake in tests |
| onState | no-op | called on every state transition |
| onMessage | no-op | called for every message other than an acknowledgement |
| onError | no-op | called on connection errors and failed connection attempts |
| backoffBaseMs / backoffFactor / backoffCapMs | 500 / 2 / 30000 | see above |
| getSocketOptions | null | called on every attempt to produce a third constructor argument (TLS options, extra headers) for WebSocketImpl — unused in a browser |
Returns { connect, send, close, state, pendingCount }.
computeBackoffMs(attempt, options?)
The backoff calculation on its own, exported because it's useful to test or reuse independently of the client.
Testing without a real network
Inject a fake WebSocketImpl that implements onopen / onmessage /
onerror / onclose and send() / close() / readyState / OPEN, and
drive it directly from a test — see src/index.test.ts for a complete fake
used to exercise reconnect and redelivery under Vitest's fake timers.
What it does not do
- No message framing beyond
JSON.stringify/JSON.parse— messages are plain objects. - No queue persistence: the send queue lives in memory and is lost if the process restarts.
- No heartbeat/ping-pong; add one at the
onMessage/sendlevel if your server needs it.
Licence
MIT. See LICENSE.
