WebSocket Reconnect
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
javascript
import WebSocket from "ws"
const desired = [
{
key: "slots",
method: "slotSubscribe",
params: [],
},
]
let attempt = 0
let stopped = false
function connect() {
const socket = new WebSocket("wss://ws.sol.cubestech.online", {
headers: { "x-api-key": process.env.NODE_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.