---
id: HS0040
title: "Live gRPC filter updates"
url: https://carbium.sh/library/howsolana/live-grpc-filter-updates
collection: How to use Solana
category: Yellowstone gRPC
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Live gRPC filter updates

One TypeScript file adds and drops watched addresses on a live Carbium socket with no reconnect, and prints a per-address tally every two seconds. The same diff-the-set idea drives a gRPC stream. It only reads.

## A new request replaces the set

A Yellowstone `Subscribe` call is one bidirectional gRPC stream. The first message you send on it is a `SubscribeRequest`, which holds named filter maps for accounts, transactions, slots, blocks and the other update kinds. You change what arrives by sending another `SubscribeRequest` on the same open stream. There is no second connection and no new handshake.

The new request replaces the old one whole. It does not merge. A request that names only a new account drops every account filter the previous request held, so each update has to carry the full set you want from that moment on. Keep the wanted set in your own state, edit it there, and send the result.

| You want | The update must carry |
|---|---|
| To keep a filter | The filter again, unchanged |
| To add an address | The new address inside the same map, beside the old ones |
| To stop watching one address | The map without it |
| To stop one kind of update | That map left out or empty |

The [Carbon stream](https://carbium.sh/docs#stream) is a gRPC endpoint at `https://services.carbium.sh:9443`, and it takes the key in the `x-token` header. It opens on the Dev, Business and Pro plans, and Free is off.

## The code

The file below runs the same bookkeeping over a WebSocket, because that needs no generated protobuf client. Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run it with Node 24, which strips the types on load. Pass two addresses that see regular traffic.

`main.ts` (run: `node main.ts <address-a> <address-b>`)

```ts
// HS0040 · Live gRPC filter updates
// https://carbium.sh/library/howsolana/live-grpc-filter-updates
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createInterface } from "node:readline";
import { address } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
const start = process.argv.slice(2).map((a) => address(a));
if (!key || start.length < 2) {
  console.error("Set CARBIUM_KEY and pass two addresses to watch.");
  process.exit(1);
}
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
const ws = new WebSocket(wsUrl);

const subs = new Map<string, number>(); // address -> subscription id
const owner = new Map<number, string>(); // subscription id -> address
const opening = new Set<string>(); // subscribe sent, reply pending
const replies = new Map<number, (m: any) => void>();
const tally = new Map<string, number>();
let want: string[] = [];
let nextId = 1;
const tag = (a: string) => a.slice(0, 8);

function call(method: string, params: unknown[], done: (m: any) => void) {
  const id = nextId++;
  replies.set(id, done);
  ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
}

function drop(a: string, id: number) {
  subs.delete(a);
  owner.delete(id); // a late notification now finds no owner and is ignored
  call("logsUnsubscribe", [id], (m) => console.log(`dropped ${tag(a)} ${m.error ? m.error.message : "ok"}`));
}

function apply(next: string[]) {
  want = next;
  for (const [a, id] of subs) if (!want.includes(a)) drop(a, id);
  for (const a of want) {
    if (subs.has(a) || opening.has(a)) continue;
    opening.add(a);
    call("logsSubscribe", [{ mentions: [a] }, { commitment: "confirmed" }], (m) => {
      opening.delete(a);
      if (m.error) return console.error(`refused ${tag(a)}: ${m.error.message}`);
      subs.set(a, m.result);
      owner.set(m.result, a);
      console.log(`added ${tag(a)}`);
      if (!want.includes(a)) drop(a, m.result); // removed while the reply was in flight
    });
  }
}

ws.addEventListener("open", () => {
  console.log("socket open");
  apply([start[0]]);
  setTimeout(() => apply(start.slice(0, 2)), 5000);
  setTimeout(() => apply(start.slice(1, 2)), 10000);
  setInterval(() => {
    console.log(`tally ${[...subs.keys()].map((a) => `${tag(a)}=${tally.get(a) ?? 0}`).join(" ") || "(none)"}`);
    tally.clear();
  }, 2000);
});
ws.addEventListener("message", (ev) => {
  const msg = JSON.parse(String(ev.data));
  if (msg.id !== undefined) {
    replies.get(msg.id)?.(msg);
    replies.delete(msg.id);
  } else if (msg.method === "logsNotification") {
    const a = owner.get(msg.params.subscription);
    if (a) tally.set(a, (tally.get(a) ?? 0) + 1);
  }
});
ws.addEventListener("error", () => console.error("socket error"));
ws.addEventListener("close", () => {
  console.error("socket closed");
  process.exit(1);
});

createInterface({ input: process.stdin }).on("line", (line) => {
  if (ws.readyState !== WebSocket.OPEN) return;
  try {
    apply(line.trim().split(/\s+/).filter(Boolean).map((a) => address(a)));
  } catch (e) {
    console.error(`bad line: ${String(e)}`);
  }
});
```

The file keeps `want`, the set you asked for, and `subs`, the subscriptions that are live. `apply` compares the two. An address in `subs` but missing from `want` gets a `logsUnsubscribe`. An address in `want` with no subscription and no pending reply gets a `logsSubscribe`. An address in both is left alone, so it keeps receiving through the change.

On the socket a change is one message per address, where a gRPC update is one message for the whole set. The diff is what lets the two look alike: you edit `want`, call `apply`, and the transport work follows from the difference.

The timeline is fixed so one run shows every case. The first address is watched at once. After 5 s the second joins it. After 10 s the first is dropped. Every 2 s the file prints how many notifications each live address produced, then resets the count. Each line you type on stdin replaces the whole set with the addresses on it, separated by spaces.

## Order of operations

Three timing cases decide whether an update behaves. The file handles each one in a single line of state.

- A notification for an address you just dropped can still arrive. `owner` loses the subscription id the moment the drop is sent, so the late message finds no address and is ignored.
- A second `apply` can land before the first subscribe has an answer. `opening` records the pending address so it is never subscribed twice.
- The wanted set can change again while a subscribe is pending. When the reply comes, the handler checks `want` and drops the new subscription at once if the address was removed in the meantime.

The same three cases exist on a gRPC stream. Messages already in flight when the server applies your update can still carry the old filters, so check each arriving update against your own `want` before acting on it.

The socket asks for `confirmed` explicitly on every subscribe.

## On Carbium

The WebSocket takes [the key](https://carbium.sh/docs#auth) as `?api-key=` in the URL, and the file builds that URL in memory and never prints it.

`logsSubscribe` streams transaction logs, all of them or only those that mention an address. A subscription with a `mentions` filter costs 25 credits to open, then 20 credits per MiB sent. A refused subscription costs nothing. An address kept across an update pays nothing again, and an address added pays the open price. Adding 40 addresses over a run costs 1,000 credits in opens, plus the traffic they send.

[Your plan caps](https://carbium.sh/docs#limits) connections and subscriptions per account, and Free carries 5 sockets. An account's keys share one budget, so a second key does not raise the cap.

## Where it ends

The file does not reconnect. Subscriptions belong to the socket that opened them, so a closed socket loses every one, and the file exits. To survive drops, reopen the socket and call `apply(want)` on open. [Multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) shows the reconnect and the backfill for the gap.

A `mentions` filter takes one address, so the socket needs one subscription per address and every change is a message per address. A gRPC account filter holds a list of addresses in one map entry, so a large set changes in a single request.

Nothing is replayed. A newly added address reports from the moment its subscription is live, and anything that happened before is not delivered. To see earlier activity for an address, read it from `getSignaturesForAddress`, which reaches back 30 days at most.

The code runs against the WebSocket, and the gRPC description above is how the Yellowstone protocol behaves. A gRPC run needs a client generated from the Yellowstone protobuf files, which this file does not include.

The file has no rate limit on updates. Typing fast on stdin sends every change, and each added address pays its open price. Collect changes and call `apply` once per interval.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| An update drops filters you meant to keep. | A new request replaces the old one whole. Build the complete wanted set in your own state, change it, and send all of it each time. |
| An added address never reports. | Look for a `refused` line first. Subscription counts are capped per account by plan. If nothing was refused, the address may be quiet in the window, so check its recent signatures. |
| Lines still arrive for an address you removed. | Messages in flight when the update is applied can still carry the old filter. Look up the sender in your own wanted set and ignore the rest, as the file does with `owner`. |
| The same address is subscribed twice and bills twice. | Key the state by address and record a pending subscribe before it is sent. The file's `opening` set does this. |
| The gRPC stream refuses the connection on a Free key. | The stream opens on Dev, Business and Pro. Upgrade the plan, or use the WebSocket for the same job. |
| The socket closes and the watched set is gone. | Subscriptions belong to the socket. Reconnect with backoff and call `apply(want)` on open, so the new socket receives the full set. |

## Questions

### Do I have to reconnect to change filters?

No. A new `SubscribeRequest` on the open gRPC stream replaces the filters in place. On the WebSocket you send `logsSubscribe` and `logsUnsubscribe` on the same connection.

### Do I miss events while the filters change?

A filter you keep in the new request keeps matching through the change. A filter you add starts from the moment the server applies it, and nothing earlier is replayed. For the earlier history, read it with `getSignaturesForAddress`, up to 30 days back.

### Can I merge a new filter into the old set with a small request?

Not on the stream. The request replaces the set, so a small request leaves you with a small set. Keep the full set in your own state and send it each time.

### Can I run this file against the gRPC stream?

Not as written. Generate a client from the Yellowstone protobuf files, replace each `call` with one request holding `want`, and send the key in the `x-token` header to `https://services.carbium.sh:9443` on a Dev or higher plan. The diff and the three timing checks stay the same.

## Related

- [Multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) (How to use Solana, HS0011)
- [Chain data streaming](https://carbium.sh/library/usecase/chain-data-streaming) (Use cases, UC0020)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [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)
