services
Get a key

library / How to use Solana / HS0036

WebSocket keepalive and reconnect

One TypeScript file holds a slot subscription open on Carbium. A silence watchdog spots a dead link, a jittered backoff reconnects, the subscription is sent again, and the slots missed while offline are counted.

By Carbium · WebSocket · HS0036 · updated 2026-11-22

01

What keeps a socket alive

A WebSocket to a Solana node can die without telling you. A load balancer recycles it, a laptop changes network, a NAT drops an idle mapping, or the process on the far side restarts. When the link is cut quietly, no close event fires and your code waits for notifications that never come.

  • A watchdog timer that you reset on every incoming message. If it fires, the socket counts as dead.
  • A reconnect loop with exponential backoff and jitter, so a thousand clients that lose a link together do not all come back in the same instant.
  • A fresh subscribe on every new socket, because a subscription lives and dies with its connection.

The WebSocket protocol has ping and pong frames, and a server can use them to check a client. The global WebSocket in Node 24 and in browsers answers a server ping on its own and gives your code no way to send one. The heartbeat that you control therefore lives in your application, and the simplest one is the watchdog above.

A watchdog needs a feed that is never quiet. Slot notifications arrive about five times a second, because a slot is about 200 ms, so ten seconds without one means the link is gone. A feed that is quiet by nature, such as one signature or one wallet's logs, cannot tell silence from a dead link. Open slotSubscribe beside it and use the slot ticks as the heartbeat.

02

The code

The file needs no install and uses only Node built-ins. Export CARBIUM_KEY and run it with Node 24, which strips the types on its own. The optional argument is a number of seconds after which the file closes its own first socket, so you can watch a reconnect happen on demand.

main.ts
// HS0036 · WebSocket keepalive and reconnect// https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");url.searchParams.set("api-key", key);const dropAfter = Number(process.argv[2] ?? 0); // seconds; closes the first socket on purposeconst SILENCE_MS = 10_000; // slots tick about 5 times a second, so 10 s of quiet is a dead linklet attempt = 0;let lastSlot = 0;let first = true;function connect(): void {  const ws = new WebSocket(url);  let dead = false;  let fresh = true; // true until the first slot on this socket  let watchdog: ReturnType<typeof setTimeout> | undefined;  const retire = (why: string) => {    if (dead) return; // close, error and watchdog may all fire: reconnect once    dead = true;    clearTimeout(watchdog);    ws.close();    const wait = Math.min(1000 * 2 ** attempt++, 30_000) * (0.5 + Math.random() / 2);    console.error(`${why}; reconnecting in ${Math.round(wait)} ms`);    setTimeout(connect, wait);  };  const arm = () => {    clearTimeout(watchdog);    watchdog = setTimeout(() => retire(`silent for ${SILENCE_MS / 1000} s`), SILENCE_MS);  };  ws.addEventListener("open", () => {    arm();    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" }));    if (first && dropAfter > 0) setTimeout(() => retire("forced drop"), dropAfter * 1000);    first = false;  });  ws.addEventListener("message", (ev) => {    if (dead) return;    arm();    const msg = JSON.parse(String(ev.data));    if (msg.error) {      console.error(`subscribe refused: ${msg.error.message}`);      return;    }    if (msg.method !== "slotNotification") return;    const slot: number = msg.params.result.slot;    if (fresh) {      fresh = false;      attempt = 0; // data arrived, so the link is real: reset the backoff      if (lastSlot) console.log(`gap: ${slot - lastSlot - 1} slots missed while offline`);    }    if (slot % 10 === 0) console.log(`slot ${slot}`);    lastSlot = slot;  });  ws.addEventListener("close", () => retire("socket closed"));  ws.addEventListener("error", () => retire("socket error"));}connect();

run: node main.ts [seconds-before-forced-drop]

Each call to connect builds one socket and owns its own state: a dead flag, a watchdog timer and a fresh flag. The retire function is the only way out. The close event, the error event and the watchdog all call it, and the flag makes the second and third call do nothing. That is what stops one failure from scheduling two reconnects and doubling your sockets.

Messages from a retired socket are ignored, even if a late one arrives. The first slot on a new socket resets the backoff counter, so a socket that opens and is dropped at once keeps backing off instead of hammering the endpoint. The first slot also reports the gap against the last slot seen before the drop.

03

Reading the output

Without an argument the file prints every tenth slot number and keeps running. Run it as node main.ts 8 and the first socket is retired after eight seconds. You then see the line forced drop; reconnecting in 700 ms, followed by a gap: line and the slot numbers again.

A new subscription starts at the current slot. Nothing that happened while you were offline is replayed, so the gap line counts the slots that passed, and a long outage shows a long one. The wait before a reconnect is the base delay times a random factor between one half and one, which is why two runs print different numbers.

$A slot its leader never produced sends no slotNotification. A jump of one or two in the slot numbers between two ticks is not a lost message.
04

Choosing the numbers

SettingValue in the fileWhy
Silence limit10 secondsAt about five slots a second this is dozens of missed ticks. A shorter limit risks a false alarm during a short stall on your own network.
First backoff1 secondMost drops are a single recycled connection and one retry fixes them.
Backoff cap30 secondsA long outage should poll slowly instead of piling up attempts.
Jitterhalf to full delaySpreads clients that lost the link at the same moment.
Reset pointfirst slot on a new socketAn open socket that is cut at once must keep backing off.

These are starting values. If your process sits behind a proxy that closes idle sockets on a short timer, the silence limit does not need to change, because the slot feed is never idle. If the proxy closes every socket after a fixed lifetime, expect a reconnect on that schedule and let the loop handle it like any other drop.

05

On Carbium

The WebSocket endpoint is wss://services.carbium.sh. The file puts the key in the URL as `?api-key=`. A socket can also carry the key as the subprotocol api-key.<YOUR_KEY> in the handshake, which keeps it out of the URL. The second argument of new WebSocket(url, protocols) sets it.

TLS sessions resume on Carbium, so a reconnect costs little, and your loop should still expect drops. Opening slotSubscribe costs 5 credits, the lightest class, then 20 credits per MiB sent. A refused subscription costs nothing. A reconnect storm therefore costs 5 credits per subscription the server accepts.

Sockets and subscriptions are capped per account by plan, and Free carries 5 sockets. Limits belong to the account, so every key on it shares them. Retire the old socket before you open the next one, as the file does, or a reconnect loop can sit at the cap and get refused by its own leftovers. After a silent dead link the client's close may never reach the server, so the old socket can still count against the cap for a while, and the backoff is what absorbs that.

A quiet feed has its own rules on Carbium. signatureSubscribe sends one confirmation and then the subscription ends, so there is nothing left to keep alive afterwards. `logsSubscribe` streams transaction logs, all or by mention, and a wallet that rarely transacts will be silent for long stretches. Pair it with the slot heartbeat.

For a watcher that fills the gap after a reconnect, see Watch many wallets and backfill what a drop missed. For the same job over a list of deposit addresses, see Multi-address deposit monitor.

06

Where it ends

The file detects a dead link and restores the subscription. It does not restore what you missed. The gap line tells you that slots passed while you were offline and nothing else. If you need every transaction for an address, record the newest signature you have seen and ask getSignaturesForAddress for everything after it once you are back.

That call costs 50 cells, and on Carbium its pages come from our own address index, which keeps up to 30 days. An empty page past that is the index's age limit and says nothing about the address having older transactions. A gap longer than 30 days cannot be filled from this call.

The watchdog only sees messages. A server that sends slot ticks but drops your other subscription looks alive. If you rely on a second feed, track a timestamp for it as well and retire the socket when it goes stale for longer than its own expected quiet period.

The file holds one socket and one subscription. A program with many sockets needs a retire path per socket and a shared cap on how many reconnects run at once, so a mass drop does not turn into a burst of handshakes.

07

When it goes wrong

what goes wrongwhat to do
The file prints socket error; reconnecting again and again with growing delays.An unknown key gets 401 at the handshake and the WebSocket error event carries no status. Check that CARBIUM_KEY holds the whole key. The delay stops growing at 30 seconds, so a wrong key keeps retrying until you stop it.
Two sockets run at once after a drop and the extra socket and its subscription count against the plan's socket and subscription caps.Close the old socket in the same function that schedules the new one and guard it with a flag, as retire does. Closing in only one of the close, error and watchdog paths leaves a leftover socket in the others.
The watchdog fires every few seconds on a healthy link.The silence limit is shorter than the quiet period of the feed it watches. Heartbeat on slotSubscribe, which ticks about five times a second, and keep the limit well above the gap between ticks.
After a reconnect the stream resumes but records are missing.A new subscription starts at the current slot and replays nothing. Keep the newest signature seen per address and backfill with getSignaturesForAddress after each reconnect.
The subscribe reply is an error and no slots arrive.A refused subscription is not charged. Read the message in the reply, which the file prints, and check the plan's cap on sockets and subscriptions for the account.
08

Questions

Can I send a ping frame from Node or a browser?

No. The global WebSocket answers a server's ping for you and has no method to send one. Use an application heartbeat, such as a watchdog on a feed that never goes quiet.

Should I reconnect on a timer even when the socket looks fine?

Only if you know the path closes sockets at a fixed lifetime. The watchdog and the close event already cover real drops, and a timed recycle adds a gap you would have to backfill.

Why reset the backoff on the first slot and not on open?

A socket that opens and is cut at once would reset the counter every time and retry at the shortest delay forever. Waiting for a first notification proves the link carries data.

Does Carbium resend what I missed after a reconnect?

No. A new subscription starts from the current slot. Fill the gap with getSignaturesForAddress from the last signature you stored, within its 30 day index.