npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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.

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.

CI npm TypeScript Dependencies

npm install resilient-ws-client

The 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 30000ms

Tune 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 acknowledged

The 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/send level if your server needs it.

Licence

MIT. See LICENSE.