WebSocket Reconnect
Restore Solana subscriptions after a WebSocket disconnect.
A new WebSocket connection starts with no subscriptions. Store your desired subscriptions and send them again after every reconnect.
Reconnect flow
- Detect the close event.
- Wait with exponential backoff and jitter.
- Open a new authenticated connection.
- send each subscription request again.
- Replace old subscription IDs with new IDs.
- Resume downstream processing.
Node.js example
import WebSocket from "ws" const desired = [ { key: "slots", method: "slotSubscribe", params: [], },] let attempt = 0let stopped = false function connect() { const socket = new WebSocket("wss://ws.nln.clr3.org", { headers: { "x-api-key": process.env.NLN_API_KEY }, }) socket.on("open", () => { attempt = 0 for (const [index, sub] of desired.entries()) { socket.send(JSON.stringify({ jsonrpc: "2.0", id: `${sub.key}:${index}`, method: sub.method, params: sub.params, })) } }) socket.on("message", (raw) => { const message = JSON.parse(raw.toString()) console.log(message) }) socket.on("close", () => { if (stopped) return const base = Math.min(30_000, 500 * 2 ** attempt) const delay = base + Math.floor(Math.random() * 250) attempt += 1 setTimeout(connect, delay) })} connect() process.on("SIGTERM", () => { stopped = true})Handle gaps
WebSocket subscriptions do not replay missed notifications.
- Store the latest processed slot.
- Read missed state through JSON-RPC after reconnect.
- Use Yellowstone replay when slot replay fits your plan.
- Make downstream writes idempotent.