---
id: HS0115
title: "Subscription ID tracking"
url: https://carbium.sh/library/howsolana/subscription-id-tracking
collection: How to use Solana
category: WebSocket
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Subscription ID tracking

One TypeScript file opens three subscriptions on Carbium, keeps the node's subscription id from each reply apart from the request id, counts notifications by that id, then unsubscribes each one and prints the answer.

## Which number is which

A subscribe call comes back with a reply shaped like `{"jsonrpc":"2.0","result":23784,"id":1}`. Two numbers sit in it. The `id` is the request id you picked, and its only job is to pair the reply with the message you sent. The `result` is the subscription id the node assigned. Every notification that follows carries that number as `params.subscription`, and the unsubscribe call takes it as its single parameter. Code that stores `id` and sends it to `accountUnsubscribe` is asking the node to cancel a subscription that does not exist, and the node answers `false` or an `Invalid subscription id.` error.

- Request id: chosen by you, one per message, used to match a reply to its request.
- Subscription id: chosen by the node. It arrives in `result` of the subscribe reply, in `params.subscription` of every notification, and goes back in `params` of the unsubscribe.
- Client listener id: handed out by a library. The number web3.js 1.x returns from `onAccountChange` is a local counter, and it belongs to `removeAccountChangeListener`, never to the wire.

The third one causes most of the confusion. The library keeps its own table from its number to the node's subscription id and hides the second one from you. If you log the number `onAccountChange` returned and paste it into a raw `accountUnsubscribe`, it works only when the two counters happen to agree. With @solana/kit 8.6.0 there is no id to track at all: `createSolanaRpcSubscriptions` hands you an async iterable, and you end it by calling `abort()` on the `AbortController` whose signal you passed in.

> On a freshly started test validator both counters start near zero and count up, so the two numbers often match and hide the bug. The file starts its request ids at 100 so the two numbers differ on screen.

## The code

The file needs no install. Export `CARBIUM_KEY` and run it with Node 24, which strips the types on load. The arguments are account addresses. With none, it watches the wrapped SOL mint and the USDC mint, and it always adds a slot subscription so something ticks while it runs.

`main.ts` (run: `node main.ts [account ...]`)

```ts
// HS0115 · Subscription ID tracking
// https://carbium.sh/library/howsolana/subscription-id-tracking
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

const apiKey = process.env.CARBIUM_KEY;
if (!apiKey) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const endpoint = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
endpoint.searchParams.set("api-key", apiKey);
const watched = process.argv.slice(2);
if (watched.length === 0) {
  watched.push(
    "So11111111111111111111111111111111111111112",
    "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
  );
}

type Pending = { op: "open" | "cancel"; method: string; name: string; subId?: number };
type Running = { method: string; name: string; seen: number };

const pending = new Map<number, Pending>(); // request id -> open or cancel in flight
const subs = new Map<number, Running>(); // node subscription id -> running subscription
let requestId = 100; // high on purpose, so it never looks like a subscription id

const socket = new WebSocket(endpoint);

function send(entry: Pending, params: unknown[]): void {
  const id = requestId++;
  pending.set(id, entry);
  const wire = entry.op === "open" ? entry.method : entry.method.replace("Subscribe", "Unsubscribe");
  socket.send(JSON.stringify({ jsonrpc: "2.0", id, method: wire, params }));
}

socket.onopen = () => {
  send({ op: "open", method: "slotSubscribe", name: "slots" }, []);
  for (const addr of watched) {
    const opts = { encoding: "base64", commitment: "confirmed" };
    send({ op: "open", method: "accountSubscribe", name: `account ${addr.slice(0, 8)}` }, [addr, opts]);
  }
  setTimeout(() => {
    for (const [subId, run] of subs) send({ op: "cancel", method: run.method, name: run.name, subId }, [subId]);
    if (pending.size === 0) process.exit(0);
  }, 6000);
  setTimeout(() => {
    console.error("no unsubscribe replies in time; closing");
    process.exit(0);
  }, 15000);
};

socket.onmessage = (ev) => {
  const msg = JSON.parse(String(ev.data));
  if (msg.method) {
    // a notification has no id field, only the subscription id
    const run = subs.get(msg.params.subscription);
    if (run) run.seen++;
    return;
  }
  const entry = pending.get(msg.id);
  if (!entry) return;
  pending.delete(msg.id);
  if (entry.op === "open") {
    if (msg.error) return console.error(`${entry.name}: subscribe refused: ${msg.error.message}`);
    subs.set(msg.result, { method: entry.method, name: entry.name, seen: 0 }); // result is the subscription id
    console.log(`${entry.name}: request id ${msg.id}, subscription id ${msg.result}`);
  } else {
    const run = subs.get(entry.subId!);
    const answer = msg.error ? `error ${msg.error.message}` : msg.result;
    console.log(`${entry.name}: unsubscribed=${answer} after ${run?.seen ?? 0} notifications`);
    subs.delete(entry.subId!);
    if (pending.size === 0) process.exit(0);
  }
};

socket.onclose = () => process.exit(0);
socket.onerror = () => {
  console.error("socket error; check CARBIUM_KEY and the endpoint");
  process.exit(1);
};
```

Two maps carry the whole idea. `pending` holds every request still waiting for its reply, keyed by request id and marked as an open or a cancel. `subs` holds what is running, keyed by the node's subscription id, with a notification count beside each entry. A subscribe reply moves an entry from the first map to the second, and an unsubscribe reply finds its subscription through the cancel mark.

A notification is matched by `params.subscription`, never by an `id`, because notifications have no `id` field. The file counts them per subscription, which gives you a number to compare against what you expect when you stop.

## Reading the output

Each subscribe prints a line that sets the two numbers side by side, such as `slots: request id 100, subscription id 4812`. The first is yours and the second is the one to keep. After six seconds the file sends one unsubscribe per live subscription and prints the node's reply together with the count of notifications that arrived under that id.

| Line | What it means |
|---|---|
| unsubscribed=true | The node knew the id and has dropped the subscription. |
| unsubscribed=false or unsubscribed=error | The id was not a live subscription on this socket: a request id, a client listener id, or an id from an earlier connection. |
| subscribe refused | The node rejected the subscribe, so there is no id to track. The message is printed. |
| 0 notifications on an account | The account did not change during the run. A slot subscription ticks about five times a second, since a slot is about 200 ms, so it shows dozens. |

Run it twice and the subscription ids differ between runs. They belong to one connection and mean nothing on the next, so they are never worth writing to disk.

## On Carbium

The WebSocket endpoint is `wss://services.carbium.sh`, and the file puts the key in the URL as [`?api-key=`](https://carbium.sh/docs/auth). The subscribe and unsubscribe methods are the standard Solana ones, so the id handling above is the same here as anywhere.

[`accountSubscribe`](https://carbium.sh/docs/websocket) sends account state on change for streamed accounts, and a plain SOL wallet sends nothing. To watch a wallet, subscribe with `logsSubscribe` using a mention and read the balance with `getBalance` when a log arrives. A silent `accountSubscribe` on a wallet looks like a lost id, and it is only an account that never notifies.

Opening a subscription costs 5, 25 or 200 credits by filter weight, then [20 credits per MiB sent](https://carbium.sh/docs/limits). A refused subscription costs nothing, and an `accountSubscribe` that never notified is refunded when it closes. Your plan caps connections and subscriptions per account, and Free carries 5 sockets. Limits belong to the account, so every key on it shares them. A subscription you no longer need but never cancelled keeps sending, and every MiB it sends is billed until its socket closes, which is the practical reason to hold the id.

## Where it ends

The file tracks ids for one socket. Closing a socket drops every subscription on it, so an unsubscribe matters when you want to stop one feed and keep the connection for the others. After a reconnect every old id is void, and the new subscribe replies hand out fresh ones. Clear the maps on close and subscribe again from your own list of what you want, which is the pattern in [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect).

`signatureSubscribe` sends one confirmation and then ends by itself, so it needs no unsubscribe after the notification. If you cancel it before the notification arrives, the unsubscribe works as it does for any other subscription.

The unsubscribe reply is a message like any other. On a dead link it never arrives, and the file stops waiting after a fixed time and exits. A long-running service should treat a missing reply as a reason to retire the socket, which also drops the subscription. For a service that alerts on a silent feed, see [Subscription dead-man alert](https://carbium.sh/library/integrate/subscription-dead-man-alert).

The file prints counts and does nothing with the account data. Decoding it, and ordering notifications against reads, are separate jobs.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| accountUnsubscribe answers false or an Invalid subscription id. error. | You sent the request id or a library's listener id. Send the number from `result` in the subscribe reply, on the same socket that opened the subscription. |
| removeAccountChangeListener in web3.js 1.x seems to do nothing after you passed it a raw id. | Pass the number `onAccountChange` returned. The library maps it to the node's subscription id itself, and a raw id from another source points at the wrong entry or none. |
| Notifications arrive under an id the file has no label for. | They belong to a subscription whose reply was not stored yet, or one you already cancelled. Look the id up in the live map and ignore a miss instead of throwing. |
| After a reconnect the old ids no longer unsubscribe anything. | Subscription ids last as long as one connection. Clear the map on close, subscribe again and store the new ids. |
| accountSubscribe on a wallet never notifies, so the id seems unused. | A plain SOL wallet sends nothing on Carbium. Use `logsSubscribe` with a mention and read `getBalance` after each log. |
| The socket closes with an error at the handshake and no subscribe reply arrives. | An unknown key gets 401 and the WebSocket error event carries no status. Check that CARBIUM_KEY holds the whole key. |

## Questions

### Why does the subscribe reply have both id and result?

The `id` repeats the request id so you can match the reply. The `result` is the subscription id. Keep `result` and discard `id` once the reply is matched.

### Do I have to unsubscribe before closing the socket?

No. Closing the socket drops every subscription on it. Unsubscribe when you want one feed to stop while the connection keeps serving others.

### How do I stop a subscription in @solana/kit?

Call `abort()` on the `AbortController` whose signal you gave `subscribe`. The library sends the unsubscribe for you and there is no id in your code.

### Can I reuse a subscription id on a new socket?

No. An id is valid only on the connection that created it. A new socket needs a new subscribe call and gets a new id.

## Related

- [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) (How to use Solana, HS0036)
- [Subscription dead-man alert](https://carbium.sh/library/integrate/subscription-dead-man-alert) (Integrations, I0068)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
