# Recover a WebSocket feed after a disconnect

Resume MadeOnSol streams from processed events and verify what each subscription recovered before resuming normal operation.

Access: Pro and above

[Compare plans and subscribe](https://madeonsol.com/pricing#pricing)

## Integration choice

Process frames in order. Track recovery per named subscription and separate state updates from historical events. A gap between sequence numbers alone is insufficient evidence of missing trades.

## Implementation steps

1. Run the Node example on your backend. It exchanges your API key for a stream token and subscribes to KOL trades. A subscribed acknowledgement confirms the subscription even when there are no new trades.
2. Replace handle() with your event handler. Advance the resume cursor only after processing succeeds. Persist the cursor and event identities if you need recovery across restarts of your own process.
3. The example keeps its cursor in memory. In production, inspect replay_end for your subscription and affected channels. Refresh affected state if recovery is incomplete. A refreshed snapshot restores current state but cannot reconstruct a missing trade history.

## Node.js stream client

~~~javascript
// npm i ws   ·   MADEONSOL_API_KEY=msk_... node stream.mjs
import WebSocket from "ws";

const SUBSCRIBE = {
  "type": "subscribe",
  "sub_id": "kol",
  "channels": [
    "kol:trades"
  ]
};
const BACKOFF_START_MS = 1000;
const SEEN_MAX = 100_000;

// Frames are processed ONE AT A TIME, in arrival order, across reconnects:
// an async "message" listener is not awaited by the socket, so without this
// queue frame 2 could finish before frame 1 and move the cursor past it.
let queue = Promise.resolve();
// {instance, seq, ts} of the last frame whose handler SUCCEEDED, in order.
// It is what a reconnect resumes from, so a failed frame is replayed.
let cursor = null;
// Delivery is at-least-once: dedupe by (sub_id, id), marked only after success.
const seen = new Set();
// Every connect bumps this. Callbacks of an older socket see a stale
// generation and never touch the current connection's state.
let generation = 0;
let backoffMs = BACKOFF_START_MS;

async function streamToken() {
  // The socket takes a stream token, never the msk_ API key.
  const r = await fetch("https://madeonsol.com/api/v1/stream/token", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.MADEONSOL_API_KEY}` },
  });
  if (!r.ok) throw new Error(`stream token: HTTP ${r.status}`);
  return (await r.json()).token;
}

async function handle(frame) {
  // Your code. Return (or resolve) only when the frame is fully processed;
  // throw (or reject) to have it replayed after a reconnect.
  console.log(frame.channel, frame.event, frame.id);
}

function remember(key) {
  seen.add(key);
  if (seen.size > SEEN_MAX) seen.delete(seen.values().next().value);
}

async function connect() {
  const gen = ++generation;
  let instance = null; // server instance of THIS connection (connected / subscribed frames)
  let failed = false;  // a handler failed on this connection: process nothing more from it
  let closed = false;
  const live = () => gen === generation && !failed;

  let ws;
  try {
    const token = await streamToken();
    if (gen !== generation) return;
    ws = new WebSocket("wss://madeonsol.com/ws/v1/stream", { headers: { Authorization: `Bearer ${token}` } });
  } catch (err) {
    console.error(err.message);
    return retry(gen);
  }

  async function processFrame(msg) {
    if (!live()) return;
    if (msg.type) {
      // Control frame: connected, subscribed, heartbeat, replay_start, replay_end, warning, ...
      if (msg.instance) instance = msg.instance;
      if (msg.type === "warning") console.warn("warning", msg.code, msg);
      return;
    }
    const key = msg.id != null ? `${msg.sub_id ?? ""}|${msg.id}` : null;
    if (key && seen.has(key)) return;
    await handle(msg); // throws → caught below; nothing is marked, the cursor stays put
    if (key) remember(key);
    // A frame finished after its socket was replaced must not move the
    // new connection's cursor (the new socket resumed from the old one).
    if (live() && msg.seq != null && instance) cursor = { instance, seq: msg.seq, ts: msg.ts };
  }

  ws.on("open", () => {
    if (gen !== generation) return ws.terminate();
    backoffMs = BACKOFF_START_MS;
    ws.send(JSON.stringify(cursor ? { ...SUBSCRIBE, resume: cursor } : SUBSCRIBE));
  });
  ws.on("message", (raw) => {
    let msg;
    try { msg = JSON.parse(raw); } catch { return; }
    queue = queue.then(() => processFrame(msg)).catch((err) => {
      if (failed || gen !== generation) return;
      failed = true;
      console.error("handler failed, reconnecting to replay from the last processed frame:", err?.message ?? err);
      ws.terminate(); // "close" follows → reconnect with resume: cursor
    });
  });
  ws.on("close", (code, reason) => {
    if (closed) return;
    closed = true;
    console.warn("closed", code, String(reason));
    retry(gen);
  });
  ws.on("error", () => {}); // "close" follows
}

function retry(gen) {
  if (gen !== generation) return; // an older connection's close: a newer one already runs
  setTimeout(connect, backoffMs);
  backoffMs = Math.min(backoffMs * 2, 30_000);
}

connect();
~~~

## Verify your integration

Disconnect during traffic, then reconnect with the last processed cursor. Count unique applied event IDs and inspect replay_end. Confirm that incomplete recovery schedules a bounded repair for the affected channel.

## Related reference

- [Stream subscription builder](https://madeonsol.com/api-docs#stream-config)
- [Streaming reference](https://madeonsol.com/streaming)

[Canonical guide](https://madeonsol.com/docs/websocket)
