WebSocket Reconnect

A new WebSocket connection starts with no subscriptions. Store your desired subscriptions and send them again after every reconnect.

Reconnect flow

  1. Detect the close event.
  2. Wait with exponential backoff and jitter.
  3. Open a new authenticated connection.
  4. send each subscription request again.
  5. Replace old subscription IDs with new IDs.
  6. 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.