---
id: UC0020
title: "Chain data streaming"
url: https://carbium.sh/library/usecase/chain-data-streaming
collection: Use cases
category: Developer platforms and infrastructure
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Chain data streaming

Chain data reaches an app by polled reads, WebSocket subscriptions or the gRPC stream. A script stores program logs from one WebSocket and fills the gap after a drop, and the limits of a stream are spelled out.

## Three ways to get live data

An app that follows the chain has three inputs on Carbium, all under one key on [one domain, services.carbium.sh](https://carbium.sh/docs#endpoints). It can poll an RPC read on a timer, hold a WebSocket open so the node pushes, or open the gRPC stream.

| Input | Where and how the key travels | Plans |
|---|---|---|
| Polled RPC read | https://services.carbium.sh, x-api-key header | All |
| WebSocket subscription | wss://services.carbium.sh, ?api-key= in the URL | All, with a socket cap per plan |
| gRPC stream | https://services.carbium.sh:9443, x-token header | Dev, Business, Pro |

Polling fits a value that changes slowly or matters only when a user looks at it. A [cached read](https://carbium.sh/docs#rpc) such as `getSlot` costs 1 cell, at 5, 30, 100 and 500 req/s on Free, Dev, Business and Pro. Polling a transaction list is the costly shape: `getSignaturesForAddress` costs 50 cells, and on Free its rate is 0.24 req/s, about one call every four seconds.

Push suits what you would otherwise poll for: new slots, the logs of a program, the confirmation of one transaction.

## WebSocket subscriptions and their cost

The socket is `wss://services.carbium.sh` with [the key as `?api-key=`](https://carbium.sh/docs#auth) in the URL. The key can also travel as the subprotocol `api-key.<YOUR_KEY>` when you want it out of the URL. Four [WebSocket methods](https://carbium.sh/docs#websocket) matter for streaming:

- `slotSubscribe`: a notification per slot, about one every 200 ms.
- `logsSubscribe`: transaction logs, all or by mention of an address.
- `signatureSubscribe`: one confirmation, then the subscription ends.
- `accountSubscribe`: account state on change for streamed accounts, and nothing for a plain SOL wallet.

Opening a subscription costs 5, 25 or 200 credits by filter weight. Slot, root and signature subscriptions weigh 5. Account, logs by mention and slot updates weigh 25. Program, all logs, blocks and a transaction firehose weigh 200. After that the stream costs [20 credits per MiB](https://carbium.sh/docs#limits) sent. A refused subscription is free, and an `accountSubscribe` that never notified is refunded at close.

Your plan caps sockets and subscriptions per account, and the account's keys share that budget. Free carries 5 sockets. An all-logs feed at weight 200 needs a budget you have measured before it goes near production.

## A watcher in one file

Run it with a program address and, optionally, how many events to store (20 by default). It prints the current slot over RPC, opens one socket and subscribes to the program's logs by mention and to slots, which costs 30 credits to open. Each signature goes into `stream.db`. It stops after the count or after 20 seconds, and prints how much the socket sent. Delete the timer line to run it as a service. It reads `CARBIUM_KEY`, exits with a message when it is unset, and signs and sends nothing.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts <program-address> 20`)

```ts
// UC0020 · Chain data streaming
// https://carbium.sh/library/usecase/chain-data-streaming
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: streams a program's transaction logs over one WebSocket into SQLite and fills the gap after a reconnect.
import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 program: string = process.argv[2] ?? "";
if (!program) { console.error("Usage: node main.ts <program-address> [events-to-store]"); process.exit(1); }
const limit = Number(process.argv[3] ?? 20);
const rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }));

// The signature is the primary key, so a live event and a backfilled one collapse into one row.
const db = new DatabaseSync("stream.db");
db.exec("CREATE TABLE IF NOT EXISTS events (signature TEXT PRIMARY KEY, slot INTEGER, failed INTEGER, via TEXT)");
const insert = db.prepare("INSERT OR IGNORE INTO events VALUES (?, ?, ?, ?)");
let stored = 0;
let bytes = 0;

function finish() {
  console.log(`stored ${stored} new events in stream.db, received ${(bytes / 1048576).toFixed(3)} MiB`);
  process.exit(0);
}

function save(sig: string, slot: number | bigint, failed: boolean, via: string) {
  if (Number(insert.run(sig, Number(slot), failed ? 1 : 0, via).changes) === 0) return;
  console.log(`${via.padEnd(8)} slot ${slot} ${failed ? "failed" : "ok"} ${sig.slice(0, 16)}...`);
  if (++stored >= limit) finish();
}

// After a connect, fetch what happened while the socket was away: everything newer than the newest stored signature.
async function backfill() {
  const row = db.prepare("SELECT signature FROM events ORDER BY slot DESC LIMIT 1").get() as { signature: string } | undefined;
  if (!row) return;
  const page = await rpc
    .getSignaturesForAddress(address(program), { until: signature(row.signature), limit: 1000, commitment: "confirmed" })
    .send();
  for (const s of page) save(s.signature, s.slot, s.err !== null, "backfill");
}

function connect() {
  const ws = new WebSocket(`${wsUrl}?api-key=${encodeURIComponent(key)}`);
  let lastSlotAt = Date.now();
  // Slots arrive about every 200 ms: five quiet seconds mean a dead socket, even when the program is quiet.
  const watchdog = setInterval(() => { if (Date.now() - lastSlotAt > 5000) ws.close(); }, 1000);
  ws.onopen = () => {
    const sub = (id: number, method: string, params: unknown[]) =>
      ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
    sub(1, "logsSubscribe", [{ mentions: [program] }, { commitment: "confirmed" }]);
    sub(2, "slotSubscribe", []);
    backfill().catch((e) => console.error("backfill failed:", e instanceof Error ? e.message : e));
  };
  ws.onmessage = (ev) => {
    bytes += String(ev.data).length;
    const msg = JSON.parse(String(ev.data));
    if (msg.error) console.error(`subscribe ${msg.id} refused: ${msg.error.message}`);
    else if (msg.method === "slotNotification") lastSlotAt = Date.now();
    else if (msg.method === "logsNotification") {
      const { context, value } = msg.params.result;
      save(value.signature, context.slot, value.err !== null, "live");
    }
  };
  ws.onerror = () => console.error("socket error");
  ws.onclose = () => {
    clearInterval(watchdog);
    console.log("socket closed, reconnecting in 1 s");
    setTimeout(connect, 1000);
  };
}

try { console.log("current slot", await rpc.getSlot({ commitment: "confirmed" }).send()); }
catch (e) { console.error("getSlot failed:", e instanceof Error ? e.message : e); }
connect();
setTimeout(finish, 20_000);
```

The signature is the primary key, so an event that arrives live and again from the backfill is stored once. The slot subscription is a heartbeat: five quiet seconds close the socket even when the program itself is quiet. The reconnect runs from `onclose` alone, so the old socket is gone before the next one opens and one watcher never holds two sockets of your plan's cap.

## After a drop: gap fill and commitment

A dropped socket loses what happened while it was away, because nothing is replayed. On every connect the script subscribes first and then calls `getSignaturesForAddress` with `until` set to its newest stored signature. Subscribing first closes the window where a transaction lands between the backfill and the subscription, and the primary key absorbs the overlap.

The backfill is one call of up to 1000 signatures at 50 cells. A longer outage needs pages with `before` until you reach the stored signature. The [address index](https://carbium.sh/docs#migrate) keeps 30 days at most, so an older gap cannot be filled, and an empty page past 30 days marks the index's age limit while the address may have older transactions. A flapping connection on a small plan can hit its rate limit through the backfill, so wait the hinted time before the next connect.

The subscription asks for `confirmed` in its params, and the read passes `confirmed` too. @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, while the JSON-RPC server's own default is finalized, so name the commitment in every call and use one value across the pipeline. A store that must never keep a transaction from a dropped fork can ask for `finalized` instead.

A slot whose leader produced nothing sends no `slotNotification`, and a slot notified at processed can still end up skipped when its fork is dropped. Treat a gap in slot numbers as normal.

## Where the gRPC stream fits

The carbon [gRPC stream](https://carbium.sh/docs#stream) lives at `https://services.carbium.sh:9443` and takes the key in the `x-token` header. It opens on Dev, Business and Pro, and Free is off. It is a server-filtered bidirectional stream, and a `grpcurl` call that imports `geyser.proto` opens one.

Node's built-ins have no gRPC client, which is why the script stays on the WebSocket. Stream work is metered like socket work: the same 5, 25 and 200 credits to open by filter weight, 20 credits per MiB sent, and nothing for a stream that sent no data. Move to gRPC when one socket per program stops fitting, or when you want the server to cut a larger feed down before it reaches your process. The store and the gap fill stay as they are.

## Where it ends

- Logs are not transactions: a log notification holds the signature, the error status and the log lines. For accounts and instructions call `getTransaction`, which costs 50 cells and takes `maxSupportedTransactionVersion: 1` with an encoding, since absent or 0 it answers -32015 for a v1 transaction. It can answer null for an older signature that the backfill lists, because the address index reaches below the validator's ledger floor.
- One address per mentions filter: covering many addresses means one subscription each, at 25 credits to open. [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) works through that case.
- Plain SOL wallets: `accountSubscribe` stays silent for them. Subscribe to logs with the wallet in mentions and read `getBalance` on each event.
- Order and duplicates: live and backfilled rows interleave, so sort by slot when you read, and expect an event twice until the primary key has dropped it.
- Cost grows with volume: 20 credits per MiB sent applies to every log line of a busy program. Run the script for a minute and read its received total before you scale up.
- Nothing replays beyond 30 days, so keep your own rows.
- Without a process to keep alive, [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) push to an HTTP endpoint instead.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The process sits silent after the network drops. | Keep a heartbeat. The script subscribes to slots and closes the socket after 5 s without one, then reconnects from onclose. |
| Rows are duplicated after a reconnect. | Make the signature the primary key and insert with OR IGNORE, so a live event and a backfilled one collapse into one row. |
| A transaction is missing after an outage. | Backfill on every connect with getSignaturesForAddress and until set to the newest stored signature. Page with before when the gap holds more than 1000 signatures, and accept that 30 days is the limit. |
| The reconnect loop gets 429 on the backfill. | Wait the retry-after value before the next connect. The call costs 50 cells, and Free allows 0.24 req/s of that class. |
| A subscribe call comes back with an error. | Read the message in the reply. A refused subscription costs nothing. Check how many sockets the account holds, since Free carries 5 and every key of the account shares them. |
| A SOL wallet watcher built on accountSubscribe stays silent. | Subscribe to logs with the wallet in mentions and read getBalance on each event. |

## Questions

### WebSocket or the gRPC stream?

Start with the WebSocket: it opens on every plan and the script above runs on it. Move to the gRPC stream on Dev or above when one socket per program stops fitting, or when you want the server to filter a larger feed before it reaches you.

### Which commitment should the subscription use?

Name one in the subscribe params and use it everywhere. The script uses confirmed, which is also what kit fills in when a call leaves it out. Use finalized when a dropped fork must never reach your store.

### How do I get the full transaction after a log event?

Call getTransaction with the signature, maxSupportedTransactionVersion set to 1 and an encoding. It costs 50 cells and can answer null for an older signature. Without the version option a v1 transaction answers -32015.

### Can I replay what I missed last month?

Only 30 days of signatures come back, from Carbium's own address index for the address. A gap longer than that cannot be filled, so store as you go and keep the database.

### How do I watch a plain SOL wallet?

accountSubscribe sends nothing for a plain SOL wallet. Subscribe to logs with the wallet in mentions and call getBalance when one arrives.

## Related

- [Address transaction webhooks](https://carbium.sh/library/howsolana/address-transaction-webhooks) (How to use Solana, HS0018)
- [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) (Blockchain ideas, BI0006)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
