BLIX
0% trading fees on every trade · every account, no code ›

AI-powered memecoin terminal

Solana WebSocket tutorial: live data in thirty lines

Polling an RPC every second is slow and burns your allowance. A WebSocket subscription tells you the moment something changes. This tutorial covers every subscription Solana offers, then builds one complete example that was run against mainnet while this page was written: it follows a busy program and prints its trades live, with the reconnect and gap handling that tutorials usually skip.

The BLIX memecoin trading terminalExplore the BLIX terminal ↗

By BLIX · Updated · Solana fundamentals and on-chain data

On this page
  1. How Solana subscriptions work
  2. A complete example: live trades from one program
  3. Reading the bytes
  4. Reconnecting properly
  5. Filling the gap you missed
  6. Limits to plan for
  7. If you want the decoded stream, not the plumbing
  8. More on Solana and on-chain data
Runs on
Node 22 or newer, no packages
Endpoint
wss:// plus your RPC host
Tested
Against mainnet on November 17, 2026
Volume seen
About 470 messages a second for one busy program
Skill needed
Basic JavaScript
Cost
Free on the public endpoint, for testing

How Solana subscriptions work

Open a WebSocket to your RPC host (the same URL as HTTP, with wss://). Send a JSON-RPC message naming a subscription. The node replies once with a subscription id, then pushes a notification each time the thing you subscribed to changes. One connection can carry many subscriptions. The methods are listed in the Solana WebSocket reference.

SubscriptionFires whenTypical use
accountSubscribeOne account's data or balance changesA wallet balance, one pool's reserves, one bonding curve
programSubscribeAny account owned by a program changesEvery pool of one exchange; filter hard or it floods you
logsSubscribeA transaction mentioning an address is processedLive trades of a program; activity of one wallet
signatureSubscribeOne transaction reaches a commitment levelKnowing your own transaction landed; fires once, then ends
slotSubscribeA new slot startsA clock; measuring how far behind you are
rootSubscribeA slot is finalizedTracking finality
blockSubscribeA whole block is confirmedUnstable and switched off on many endpoints, including the public one

A complete example: live trades from one program

logsSubscribe with mentions is the most useful subscription for trading data: you name one address and receive the logs of every transaction that touches it. Programs written with Anchor emit their events as base64 on lines that start with Program data:. Each event begins with an 8-byte tag that identifies its type, followed by its fields in order.

The example follows the pump.fun program and decodes its trade event. Save it as trades.mjs and run node trades.mjs.

// Node 22 or newer: WebSocket is built in, nothing to install.
const PROGRAM = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"; // pump.fun
const TRADE = "bddb7fd34ee661ee";                              // its trade event

function connect() {
  const ws = new WebSocket("wss://api.mainnet-beta.solana.com");
  let last = Date.now();
  // No message for 30 s means the socket is dead even if it looks open.
  const watchdog = setInterval(() => { if (Date.now() - last > 30_000) ws.close(); }, 5_000);

  ws.onopen = () => ws.send(JSON.stringify({
    jsonrpc: "2.0", id: 1, method: "logsSubscribe",
    params: [{ mentions: [PROGRAM] }, { commitment: "confirmed" }],
  }));

  ws.onmessage = (m) => {
    last = Date.now();
    const v = JSON.parse(m.data).params?.result?.value;
    if (!v || v.err) return;                       // subscription reply, or a failed transaction
    for (const line of v.logs) {
      if (!line.startsWith("Program data: ")) continue;
      const b = Buffer.from(line.slice(14), "base64");
      if (b.length < 57 || b.subarray(0, 8).toString("hex") !== TRADE) continue;
      const sol = Number(b.readBigUInt64LE(40)) / 1e9;      // lamports to SOL
      const tokens = Number(b.readBigUInt64LE(48)) / 1e6;   // 6 decimals
      console.log(v.signature.slice(0, 8), b[56] ? "buy " : "sell",
        sol.toFixed(3), "SOL for", Math.round(tokens), "tokens");
    }
  };

  ws.onclose = () => { clearInterval(watchdog); setTimeout(connect, 1_000); };
}
connect();

Real output from the run on November 17, 2026:

4qRwuAGs sell 0.019 SOL for 7420524 tokens
5miVSekK sell 0.546 SOL for 13795714 tokens
3fEcVTh8 buy  0.099 SOL for 2525955 tokens
TYHdf4Md buy  0.085 SOL for 2161618 tokens

In eight seconds the public endpoint delivered 3,759 messages, 418 of them trades. That is one program. This is why the next three sections matter.

Reading the bytes

The layout of that trade event, as the example reads it:

BytesFieldType
0 to 7Event tag8 bytes, identifies the event type
8 to 39Token mint32-byte public key
40 to 47SOL amountu64, lamports, little-endian
48 to 55Token amountu64, in the token's smallest unit
56Is buy1 for a buy, 0 for a sell
57 to 88Trader32-byte public key
89 to 96Timestampi64, seconds

To print the mint or the trader as an address, base58-encode those 32 bytes. Two warnings. Event layouts belong to the program's authors and can change with a program upgrade, usually by adding fields at the end, so check lengths before reading and never trust an offset you have not tested this week. And a program can emit several events in one transaction, which is why the example loops over every log line.

Reconnecting properly

  • Sockets die silently. A connection can stop delivering without ever firing a close event. The watchdog in the example closes the socket when nothing has arrived for 30 seconds; on a quiet subscription, add a slotSubscribe so there is always a heartbeat to measure.
  • Subscriptions do not survive a reconnect. A new connection starts empty: send every subscribe message again in onopen.
  • Back off. Reconnecting in a tight loop against a rate-limited endpoint gets your IP refused. Wait a second, then longer.
  • Expect duplicates. At processed commitment the same transaction can arrive more than once across forks. Keep a short set of recent signatures and skip repeats.

Filling the gap you missed

While you were disconnected, transactions kept happening. A WebSocket never replays them. To recover, remember the last signature you processed, and after reconnecting call getSignaturesForAddress over HTTP with until set to that signature. It returns what you missed, newest first, up to 1,000 per call. Fetch each with getTransaction and run it through the same decoder. Without this step every reconnect leaves a hole in your data that nobody notices until a number is wrong.

Limits to plan for

  • Volume. A busy program is hundreds of messages a second. Decode on arrival and keep only what you need; do not store raw logs.
  • The public endpoint is for testing. It allows 40 concurrent connections per IP and drops heavy subscribers. Use a provider key for anything that runs for more than an afternoon; the free RPC comparison covers which plans include WebSockets.
  • Failed transactions arrive too. Check err before treating a log as a trade.
  • Logs can be truncated. Very long transactions have their logs cut, which can drop the event line. Anything that must be complete should be confirmed with getTransaction.

If you want the decoded stream, not the plumbing

Decoding one event from one program is thirty lines. Following every launchpad and every pool a coin moves to, with names, holders and prices attached, is a system. BLIX runs that system, and an account can read the result as one live event stream: launches, trades and signals already decoded. The realtime API page documents it. It is server-sent events over HTTPS, not a WebSocket, which matters only in that you read it with fetch or EventSource instead.

More on Solana and on-chain data

This page is education about how the technology works. It is not financial advice, and nothing here recommends buying or selling anything.

Frequently asked questions

Does Solana have a WebSocket API?

Yes. Every RPC node serves JSON-RPC subscriptions over WebSocket at the same host as its HTTP endpoint: accountSubscribe, programSubscribe, logsSubscribe, signatureSubscribe, slotSubscribe and rootSubscribe.

What is the Solana WebSocket URL?

The public mainnet one is wss://api.mainnet-beta.solana.com. With a provider, replace https:// with wss:// in your RPC URL.

How do I get real-time Solana transactions?

Subscribe with logsSubscribe and a mentions filter naming the program or wallet you care about. Each notification carries the transaction signature and its logs; call getTransaction for the full detail.

Why does my Solana WebSocket keep disconnecting?

Idle timeouts, rate limits, and node restarts. Treat disconnects as normal: detect silence with a watchdog, reconnect with a delay, resubscribe, and backfill what you missed over HTTP.

Is logsSubscribe or programSubscribe better for trades?

logsSubscribe for events such as trades, because it delivers what happened. programSubscribe delivers account state after the change, which suits watching a pool's reserves.

Your next move starts here.

Create your BLIX account to access the trading terminal. Join the Discord community to stay connected.