Why your Solana WebSocket stops receiving messages, and how to keep it alive
Your bot ran fine for two hours and then stopped seeing anything. No error, no close event, the socket still says it is open. This is the most common failure with Solana WebSockets, and reconnecting on close does not fix it.
What is happening
A WebSocket can die without telling you. A provider restarts a node, a load balancer drops an idle connection, or the subscription is discarded on the server while the TCP connection stays up. Your onclose never fires. From your side the feed just goes quiet.
The fix is to watch for silence
- Set a silence timer. Every message resets it. If nothing arrives for, say, 30 seconds, treat the socket as dead: close it and open a new one.
- Give the handshake a deadline. A connection that never opens also fires no event on some networks.
- Back off with jitter. Wait 0.5 s, 1 s, 2 s, up to 30 s between attempts, randomised, so a fleet of clients cut off together does not return together.
- Resubscribe everything. Subscriptions belong to the connection. A new socket has none, and the subscription ids change.
The quiet-subscription problem
Silence only means something if messages are expected. An accountSubscribe on a wallet that trades once an hour is silent for an hour while perfectly healthy. Two options:
- set the silence limit longer than the longest normal gap, which means a dead feed goes unnoticed for that long; or
- add a heartbeat: a
slotSubscribeon the same socket. Slots arrive about every 0.4 seconds, so a few seconds of silence is proof the connection is gone.
What you still lose
Whatever happened while the socket was down is not replayed. If you need every transaction, backfill after reconnecting: call getSignaturesForAddress over HTTP for the gap.
Working code
solana-ws-keepalive does the silence timer, handshake deadline, backoff, resubscribe and heartbeat, with no dependencies:
import { createStream } from "solana-ws-keepalive";
const stream = createStream({
url: "wss://your-rpc.example/?api-key=...",
silentMs: 30_000,
heartbeat: true,
onState: (state, info) => console.log(state, info.why ?? ""),
});
stream.subscribe("logsSubscribe",
[{ mentions: ["<program or wallet>"] }, { commitment: "confirmed" }],
(result) => console.log(result.value.signature));
npx github:blixvip/solana-ws-keepalive logs <address>
Several subscriptions share one socket and all come back after a reconnect. Node 22 or newer has WebSocket built in; on older versions pass the ws package.