Keep Your Solana WebSocket Alive: Permanent Stream Tokens & Reconnect Loops

MadeOnSol stream tokens no longer expire on a timer. Learn the current WebSocket lifecycle: fetch the stable stream token, authenticate the socket, subscribe, detect liveness, reconnect with backoff, and rotate only when you explicitly need to.

MadeOnSol··Updated · 8 min read
Keep Your Solana WebSocket Alive: Permanent Stream Tokens & Reconnect Loops

Updated September 2026: MadeOnSol stream tokens have been permanent since August 27. The old 24-hour expiry and automatic in-band rotation model is retired. expires_at and next_refresh_at remain in the response for compatibility, but they are null.

A WebSocket client still needs a reconnect loop. The reason is no longer token age: networks fail, servers restart, subscriptions lapse, connection limits can be hit, and slow consumers can be disconnected. The robust pattern is therefore simpler than it used to be: obtain your stream token, connect, subscribe, track liveness, and reconnect with bounded backoff when the socket actually dies.

The current lifecycle

1. POST /api/v1/stream/token with your msk_ API key
      ↓
2. Receive the user's stable stream token
   expires_at: null
   next_refresh_at: null
      ↓
3. Connect to wss://madeonsol.com/ws/v1/stream
   using the STREAM token, not the msk_ API key
      ↓
4. Send a subscribe frame
      ↓
5. Process events + heartbeats
      ↓
6. If the socket closes:
   - 4001: fetch the token again, then reconnect
   - 4002: connection limit; back off hard
   - 4003: fatal auth/backend condition; stop and investigate
   - 4008: slow consumer; reconnect and resume
   - network/restart: reconnect with exponential backoff

There is no scheduled refresh timer in that loop.

Step 1: get the stream token

curl -X POST https://madeonsol.com/api/v1/stream/token \
  -H "Authorization: Bearer msk_your_api_key"

A current response includes fields like:

{
  "token": "7se3_SNGtSm9hgI8gxEGg7vfyTi4g6RI4E70i6zpohQ",
  "expires_at": null,
  "next_refresh_at": null,
  "rotated": false,
  "lifetime": "This token does not expire...",
  "ws_url": "wss://madeonsol.com/ws/v1/stream"
}

ULTRA-class accounts also receive dex_ws_url for the separate DEX firehose. The same stream token authenticates both sockets.

Calling the token endpoint again normally returns the same token. That is deliberate: two processes belonging to the same account can restart independently without invalidating each other.

What actually invalidates a token?

A stream token stops being usable when:

  • the subscription no longer entitles the account to streaming;
  • the token row is removed as part of a downgrade; or
  • you explicitly rotate the token.

It does not expire merely because 24 hours passed.

Step 2: authenticate the WebSocket correctly

The WebSocket handshake needs the stream token. Do not put the long-lived msk_ API key into the WebSocket handshake.

For server-side Node clients, prefer an Authorization header:

import WebSocket from "ws";

const ws = new WebSocket("wss://madeonsol.com/ws/v1/stream", {
  headers: {
    Authorization: `Bearer ${streamToken}`,
  },
});

Clients that cannot set headers on the upgrade request can still use the query-string form:

const ws = new WebSocket(
  `wss://madeonsol.com/ws/v1/stream?token=${encodeURIComponent(streamToken)}`
);

MadeOnSol accepts either form. Query-string token values are masked in MadeOnSol's nginx access logging, but a header is still the cleaner option for server-side clients.

Step 3: subscribe after the connection opens

Opening the socket does not subscribe you to every feed. Send a subscribe message after the connection is ready:

ws.on("open", () => {
  ws.send(JSON.stringify({
    type: "subscribe",
    channels: ["kol:trades", "deployer:alerts"],
  }));
});

Check the server's subscribed acknowledgement rather than assuming every requested channel was accepted. Channel access depends on the account tier, and some newer streams require scoped filters. The token endpoint advertises the current channel registry so clients do not need to maintain a stale hard-coded list.

Step 4: treat heartbeats as liveness, not business events

The main stream emits heartbeats on a 15-second cadence. Record when you last received any valid frame and use a reasonable timeout to detect a half-open socket.

let lastFrameAt = Date.now();

ws.on("message", (raw) => {
  lastFrameAt = Date.now();

  const msg = JSON.parse(raw.toString());

  if (msg.type === "heartbeat") return;
  if (msg.channel) {
    handleEvent(msg);
  }
});

const watchdog = setInterval(() => {
  if (Date.now() - lastFrameAt > 45_000) {
    ws.terminate();
  }
}, 15_000);

The DEX firehose has its own heartbeat cadence, so do not copy a main-stream watchdog threshold blindly into every socket.

Building a product on Solana or Robinhood Chain data?

Skip the Geyser pipeline — embed KOL flow, deployer reputation, and the all-DEX firehose over REST, WebSocket, or webhooks. The Business tier (€400/mo) is the self-serve embed license at 500k calls/day — Enterprise adds white-label & redistribution.

See Business pricing

Step 5: reconnect with bounded backoff

A reconnect loop should obtain the current stream token on every connection attempt. Because token fetches normally return the same permanent value, this is cheap operationally and also handles the cases where the account was renewed or the token was explicitly rotated.

import WebSocket from "ws";

const API = "https://madeonsol.com";
const API_KEY = process.env.MADEONSOL_API_KEY!;

async function fetchStreamToken() {
  const res = await fetch(`${API}/api/v1/stream/token`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
  });

  if (!res.ok) {
    throw new Error(`stream token: HTTP ${res.status}`);
  }

  return res.json() as Promise<{
    token: string;
    ws_url: string;
    expires_at: null;
    next_refresh_at: null;
  }>;
}

async function connect() {
  let backoffMs = 2_000;

  for (;;) {
    try {
      const info = await fetchStreamToken();

      await new Promise<void>((resolve, reject) => {
        const ws = new WebSocket(info.ws_url, {
          headers: { Authorization: `Bearer ${info.token}` },
        });

        let subscribed = false;

        ws.on("open", () => {
          ws.send(JSON.stringify({
            type: "subscribe",
            channels: ["kol:trades"],
          }));
        });

        ws.on("message", (raw) => {
          const msg = JSON.parse(raw.toString());

          if (msg.type === "subscribed") {
            subscribed = true;
            backoffMs = 2_000; // reset only after the subscription is accepted
            return;
          }

          if (msg.type === "heartbeat") return;
          if (msg.channel) handleEvent(msg);
        });

        ws.on("close", (code, reason) => {
          const text = reason.toString();
          const err = Object.assign(
            new Error(`WS closed ${code}: ${text}`),
            { code }
          );
          reject(err);
        });

        ws.on("error", reject);
      });
    } catch (err: any) {
      const code = Number(err?.code);

      if (code === 4003) {
        throw err; // fatal: stop rather than spin
      }

      if (code === 4002) {
        backoffMs = Math.max(backoffMs, 60_000);
      } else {
        backoffMs = Math.min(Math.round(backoffMs * 1.5), 60_000);
      }

      await new Promise((r) => setTimeout(r, backoffMs));
    }
  }
}

A production client should also add jitter so many workers do not reconnect in lockstep after a restart.

What close codes mean

The stream exposes close codes so clients can respond differently instead of hammering the server with the same failed reconnect:

CodeMeaning for the clientRecommended action
4001Stream token no longer authenticatesCall POST /stream/token again, then reconnect with bounded retries
4002Connection limit reachedBack off for at least ~60s; check/close stale sessions
4003Fatal auth/backend conditionStop the reconnect loop and surface an error
4008Client could not consume fast enoughReconnect and resume; fix the slow consumer
1006 / network errorTransport disappearedReconnect with exponential backoff
1011Server-side restart/errorReconnect with backoff

The important distinction is that a 4001 is not a timer-expiry signal anymore. It tells you the credential is no longer accepted because entitlement changed, the token was rotated/revoked, or the row disappeared.

Explicit rotation: only when you need it

If you believe a stream token was exposed, rotate it deliberately:

curl -X POST https://madeonsol.com/api/v1/stream/token \
  -H "Authorization: Bearer msk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"rotate":true}'

The response returns a new token with rotated: true. The previous value keeps working for 60 seconds so an in-flight reconnect or sibling process is not cut off mid-swap.

An explicit rotation can produce an in-band token_refresh for a live socket. That is the exception, not a periodic lifecycle event. Clients may handle it defensively, but they should not schedule themselves around it.

if (msg.type === "token_refresh" && msg.token) {
  streamToken = msg.token;
  return;
}

Permanent does not mean "hard-code it forever"

A permanent token removes the artificial 24-hour refresh dance. It does not mean you should paste the token into source code, commit it, or assume the socket itself lives forever.

Keep the API key and stream token in secret storage, let your client fetch the current token when it starts, and reconnect from state rather than from a token copied into code months earlier.

Main stream versus DEX firehose

MadeOnSol exposes two WebSocket surfaces:

  • /ws/v1/stream — the subscription-based signal stream for KOL, deployer, copy-trade, price/risk and other channels. PRO+ can obtain a stream token; individual channels may have stricter gates.
  • /ws/v1/dex-stream — the raw parsed Solana DEX firehose, available to ULTRA and BUSINESS-class accounts, with separate connection caps and filter/replay semantics.

Both use the same stream token, but their subscription protocols and heartbeat/replay behavior are not identical. See the DEX WebSocket guide for the firehose-specific flow.

The reliability rule that matters

Do not build a long-running WebSocket process around the assumption that "connected once" means "connected forever."

Build around these invariants instead:

  1. The stream token itself has no scheduled expiry.
  2. A socket can still disappear at any time.
  3. Authentication and subscription are separate steps.
  4. Backoff depends on why the socket closed.
  5. Liveness comes from heartbeats/events, not from the fact that the TCP connection object still exists.
  6. On reconnect, re-establish the subscription and resume state before declaring the client healthy.

That design survives the ordinary failures that actually happen without reintroducing the retired 24-hour token-rotation machinery.

Resources

Tools mentioned

Compare features and read reviews.

Live health scores, average ratings, and direct links on MadeOnSol.

Get this data via API

Stream real-time KOL trades, PnL rankings, and coordination signals programmatically.

Start free
import { MadeOnSol } from "madeonsol";

const client = new MadeOnSol({ apiKey: "msk_your_key" });

// Real-time KOL trades
const { trades } = await client.kol.feed({ limit: 10, action: "buy" });

// KOL convergence signals
const { tokens } = await client.kol.coordination({ min_kols: 3 });
npm install madeonsolFull API docs

Building a product on Solana or Robinhood Chain data?

MadeOnSol isn't an RPC or another generic token API — it's Solana & Robinhood Chain memecoin intelligence that's painful to build in-house, pulled from dual-region gRPC shred streams and our own Robinhood Chain node, pushed to your app as events land.

Signals you'd otherwise build

KOL & smart-money flow from 2,000+ labeled wallets, deployer reputation, coordination clusters, linked-wallet entity resolution, and an all-DEX firehose.

Embed it in your product

The Business tier (€400/mo, self-serve) licenses you to display MadeOnSol data inside your own product — 500k calls/day, 15 WS + 6 firehose connections. Enterprise above adds white-label & redistribution rights and custom endpoints.

Evaluate first, commit later

Test everything on a free ULTRA key — no commitment. If it fits, we scope volume or white-label pricing.

Keep reading

More from the blog.

All API Guides
How to Stream New Solana Token Launches over WebSocket: Deploys, Graduations, Surges (2026)

Guides

How to Stream New Solana Token Launches over WebSocket: Deploys, Graduations, Surges (2026)

One socket, three channels: sniper:deploys pushes every pump.fun launch a few hundred milliseconds before the chain confirms it, token:graduations pushes every bonding-curve completion, token:surges pushes young tokens running 3×, 6× or 8× against their launch cap. Handshake, real frames, filters, and what each channel does not tell you.

10 minSeptember 5, 2026
Finding Solana KOL Clusters: Pair Affinity & Co-Trading with `/v1/kol/pairs`

API Guides

Finding Solana KOL Clusters: Pair Affinity & Co-Trading with `/v1/kol/pairs`

Which pairs of Solana KOLs buy the same tokens at nearly the same time? The `/kol/pairs` endpoint returns the affinity matrix — shared token count plus agreement rate — so you can spot coordinated clusters, bot groups, and genuinely independent alpha.

7 minApril 23, 2026
Solana gRPC Alternatives: How DEX Firehose Compares to Helius and Bitquery (2026)

Comparisons

Solana gRPC Alternatives: How DEX Firehose Compares to Helius and Bitquery (2026)

An honest comparison of the three main Solana real-time trade data options — Helius LaserStream, Bitquery, and the MadeOnSol DEX Firehose — by price, DEX coverage, latency, and what you actually get for the money.

9 minApril 16, 2026
Inside the Live Terminal Demo: REST Snapshots Plus WebSocket Updates for Solana and Robinhood Chain

API Guides

Inside the Live Terminal Demo: REST Snapshots Plus WebSocket Updates for Solana and Robinhood Chain

A tour of the MadeOnSol live terminal demo: which panels stream, which refresh and which load on request, how one REST snapshot and one WebSocket subscription feed each screen, and how to build the same thing in your own terminal.

9 minNovember 12, 2026
Build a Realtime Solana Token Intelligence Dashboard Without Polling

API Guides

Build a Realtime Solana Token Intelligence Dashboard Without Polling

Load a Solana token's risk, locks, flow and holder count with one include-scoped REST read, then keep the panel current from WebSocket events instead of polling. Runnable Node and browser code with watchTokenIntelligence() from madeonsol-x402 4.3.0.

9 minOctober 10, 2026
Robinhood Chain Trading Terminal Architecture: REST Snapshots Plus WebSocket Updates

API Guides

Robinhood Chain Trading Terminal Architecture: REST Snapshots Plus WebSocket Updates

How to structure a Robinhood Chain (chain id 4663) trading terminal: one include-scoped REST snapshot per token, then price, risk, lock and candle events over one WebSocket. Runnable code with watchTokenIntelligence() from robinhood-chain-x402 0.21.0, plus the Ultra firehose trade-off.

10 minOctober 10, 2026

Enjoyed this article?

Explore the live data.

Real-time KOL trades, Pump.fun deployer intel, and 1,200+ ranked Solana & Robinhood Chain tools — free to explore.

Open the KOL Tracker