services
Get a key

library / How to use Solana / WebSocket / HS0116

Snapshot plus subscription sync

One TypeScript file opens an accountSubscribe, reads the account once with getAccountInfo, and replays the buffered notifications in slot order. It keeps only updates newer than the snapshot and prints each one it keeps or skips.

By Carbium · WebSocket · HS0116 · updated 2026-11-23

01

Why the callback looks historical

onAccountChange in @solana/web3.js wraps accountSubscribe. Its callback receives the account and a context, and context.slot is the slot in which the account changed. That number is often lower than the slot your first read reported, so the data looks like history. Two channels are involved. A getAccountInfo call answers from the node's state at one slot, and the subscription pushes changes down a separate stream. Nothing orders a read against a push, so an update for slot 100 can reach your callback after a read that already reported slot 103.

The two ways to start both lose something:

OrderWhat goes wrong
Read first, subscribe secondA change that lands between the two is never seen, and the store stays old until the next change.
Subscribe first, read second, write every messageChanges from before the read arrive after it and overwrite the newer snapshot with older state.

A subscription also sends nothing when it opens. The first message is the next change, so a quiet account looks empty until it moves. After a socket drops and reconnects, whatever changed during the gap never arrives, and the state you hold is out of date until you read again.

02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24. It takes one optional argument, the account to follow. With none it follows an Orca SOL/USDC pool account, which changes every few slots. The WebSocket URL carries the key as ?api-key=, and the getAccountInfo call goes to the RPC endpoint with the key in a header. Both read at confirmed.

main.ts
// HS0116 · Snapshot plus subscription sync// https://carbium.sh/library/howsolana/snapshot-plus-subscription-sync// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", key);// Default: an Orca SOL/USDC pool account that changes every few slots.const target = process.argv[2] ?? "7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }),);const config = { commitment: "confirmed", encoding: "base64" } as const;type Update = { slot: number; lamports: number };type Msg = {  method?: string;  params?: { result: { context: { slot: number }; value: { lamports: number } } };  error?: { message: string };};let held = -1; // slot of the state we holdlet ready = false; // true once the snapshot is appliedconst buffer: Update[] = [];function apply(u: Update, source: string) {  if (u.slot <= held) {    console.log(`skip ${source} slot ${u.slot}: already holding slot ${held}`);    return;  }  held = u.slot;  console.log(`keep ${source} slot ${u.slot}: ${u.lamports} lamports`);}const ws = new WebSocket(wsUrl);ws.onopen = async () => {  const params = [target, config];  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "accountSubscribe", params }));  try {    const { context, value } = await rpc.getAccountInfo(address(target), config).send();    if (value) apply({ slot: Number(context.slot), lamports: Number(value.lamports) }, "snapshot");    else console.log(`account is missing at slot ${context.slot}`);  } catch (e) {    console.error(`snapshot failed: ${e}`);  }  ready = true;  buffer.sort((a, b) => a.slot - b.slot).forEach((u) => apply(u, "buffered"));};ws.onmessage = (ev) => {  const msg = JSON.parse(String(ev.data)) as Msg;  if (msg.error) console.error(`subscription error: ${msg.error.message}`);  if (msg.method !== "accountNotification" || !msg.params) return;  const { context, value } = msg.params.result;  const u = { slot: context.slot, lamports: value.lamports };  if (ready) apply(u, "live");  else buffer.push(u);};ws.onerror = () => console.error("websocket error");ws.onclose = () => console.log(`closed holding slot ${held}`);setTimeout(() => ws.close(), 20_000);

run: node main.ts

The file sends the accountSubscribe request first and reads the snapshot straight after. Any notification that arrives before the snapshot is done goes into a buffer. When the snapshot is applied, the buffer is sorted by slot and replayed through the same check every live message passes: keep an update only when its slot is above the slot already held. Each line says whether an update was kept or skipped, so a stale one shows up as a skip line when it comes. After 20 seconds the socket closes and the last line names the slot the file ended on. On the default pool the lamports often stay the same from line to line: a swap rewrites the account's data bytes, and the rising slot is what shows the change.

03

The ordering rule

The rule holds for any account and any decoder you put behind it.

  • Open the subscription before the read, and buffer what it sends until the read returns.
  • Take the slot from the read's context.slot and treat it as the slot of the state you hold.
  • Apply a notification only when its context.slot is above the held slot, and move the held slot up each time one is applied.
  • Drop the rest. A notification at or below the held slot describes a state your snapshot already includes.

The last point is the one that surprises people. A notification slot names the slot where the account changed, and a read at a later slot already contains that change. An update for slot 100 against a snapshot at slot 103 adds nothing, and applying it would take the store back three slots.

$Use the same commitment on the subscription and on the read. Mixing processed on one side and confirmed on the other brings back the out-of-order updates this rule removes.
04

On Carbium

The WebSocket endpoint is wss://services.carbium.sh with the key in the api-key query parameter, and a plan caps sockets and subscriptions per account; Free carries 5 sockets. Several subscriptions can share one socket, so open one and send each accountSubscribe over it.

Opening an accountSubscribe costs 25 credits, then 20 credits per MiB sent. A subscription that is refused costs nothing, and an accountSubscribe that never got a notification is refunded when it closes. The snapshot is one getAccountInfo call, which counts 10 cells against the plan's rate limit. Free allows 0.5 account reads a second, so one read after each reconnect fits inside it.

accountSubscribe sends account state on change for streamed accounts, and a plain SOL wallet sends nothing. For a wallet, subscribe with logsSubscribe using a mention filter and read the balance with getBalance when a log arrives. The ordering rule carries over: getBalance returns a context.slot too, and a log older than that slot adds nothing.

After a reconnect, run the whole sequence again: new subscription, new snapshot, the same check. The reconnect side is covered in WebSocket keepalive and reconnect, and the same snapshot-then-stream handoff against a database is in Postgres backfill-to-live handoff.

05

Where it ends

The file keeps the lamports of one account and stops after 20 seconds. It does not reconnect, decode the account data or write anywhere. For a token account or a pool, decode the bytes first and compare the decoded fields.

A slot check cannot tell a change you missed from a quiet account. If the socket dies silently, the held slot stays put and nothing looks wrong, so pair the rule with a timer that reads the account again at a slow interval and compares its slot with the held one.

Slot numbers order updates on one fork only. Subscribe at processed and a notification can come from a fork the cluster later abandons, so its slot is skipped and the state it carried never lands. At confirmed that is rare. At processed, keep the state from before each update so you can step back when its slot drops out.

A busy account sends a message for every slot in which it changes, and every MiB sent costs 20 credits. Follow only the accounts you act on, and close a subscription once you stop reading it.

06

When it goes wrong

what goes wrongwhat to do
The callback delivers a slot lower than the slot of the snapshot.Skip it. Keep an update only when its slot is above the slot you hold, as the file does, and move the held slot up when you keep one.
The store goes stale after a reconnect, with no error.A new subscription sends nothing until the next change. Subscribe again, read a fresh snapshot, then replay the buffer through the same slot check.
Nothing arrives for a wallet address.A plain SOL wallet sends no account notifications. Subscribe with logsSubscribe using a mention filter, and read getBalance when a log arrives.
The socket is refused or the subscription fails to open.The account may be over its socket or subscription cap; Free carries 5 sockets. Send every subscription over one socket and close the ones you no longer use.
The snapshot comes back with no value.The account does not exist at that slot. The file reports the slot and keeps listening, so the first notification creates the state.
The file stops with Set CARBIUM_KEY to your Carbium API key.Export CARBIUM_KEY in the shell that runs node main.ts. The file reads it from the environment and never prints it.
07

Questions

Does onAccountChange replay old updates?

No. The subscription sends changes as they happen, and the old-looking slot is the slot in which the account changed. It looks old next to a read made at a later slot, so compare the two slots before you write.

Why do notifications arrive with slots below my snapshot?

The read and the subscription are separate channels, and the read can be answered from a later slot than the update still in flight. The update is already part of the snapshot, so dropping it loses nothing.

Should I subscribe before or after reading the account?

Subscribe first and buffer. Reading first leaves a window in which a change goes unseen, and the buffer plus the slot check closes it.

Do I need the snapshot again after a reconnect?

Yes. A new subscription starts empty and says nothing about changes made during the gap. One getAccountInfo call refreshes the state, and the same slot check applies to what follows.