---
id: I0030
title: "Kafka program account topic"
url: https://carbium.sh/library/integrate/kafka-program-account-topic
collection: Integrations
category: Queues and streams
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Kafka program account topic

A small Node bridge opens one `programSubscribe` on Carbium, batches each account write into records keyed by account address, and posts them to a Kafka topic through a REST proxy. Without a proxy URL it runs as a dry run.

## What the bridge does

Yes, a server can do this with one WebSocket subscription. The bridge opens `programSubscribe` for a program address, receives one notification per changed account per slot, and turns each notification into a Kafka record. Your consumers read the topic and never touch Solana.

Records are keyed by the account address. Kafka sends equal keys to the same partition, so the writes to one account stay in the order they arrived, and a consumer that only cares about one account sees a clean sequence. The value is a JSON object with the address, the slot, the lamports, the owner, the executable flag and the account data in base64.

| Setting | Meaning | Default |
|---|---|---|
| `CARBIUM_KEY` | Your Carbium key, required. | none |
| program address (first argument) | The program whose accounts you want. | none, required |
| `KAFKA_REST_URL` | Base URL of a Kafka REST proxy. Unset means a dry run that counts and shows records. | unset |
| `TOPIC` | The topic to produce to. | `solana.<program>.accounts` |
| `DATA_SIZE` | Keep only accounts of exactly this many bytes. | no filter |
| `CARBIUM_WS_URL` | The WebSocket endpoint the bridge connects to. | `wss://services.carbium.sh` |

## The Solana side: one program subscription

Carbium's [WebSocket endpoint](https://carbium.sh/docs#endpoints) is `wss://services.carbium.sh`. The [key goes on the URL](https://carbium.sh/docs#auth) as `?api-key=`, and the bridge sets it with `URL.searchParams`, which only encodes it. The key stays out of the logs because the bridge never prints the URL. Node 24 has a global `WebSocket`, so there is nothing to install apart from `@solana/kit`, which the bridge uses to check the program address before it connects.

The request is `programSubscribe` with the program address and a config of `encoding: "base64"` and `commitment: "confirmed"`. Confirmed means each notification reflects a block the cluster has voted on, so you do not publish writes from a fork that is later dropped. A processed subscription is quicker to the first byte but can announce a write that never lands.

With `DATA_SIZE` set, the config also carries the standard `dataSize` filter. Many programs own several kinds of account, and the sizes usually differ: a pool account and an order book account are not the same length. Filtering at the subscription keeps the unwanted kinds from being sent to you at all, which matters because bytes sent are what you pay for.

A notification carries the account's state after the write, with the slot in its context. It does not carry the transaction that caused it, so a consumer that needs the transaction takes the slot and the address to a lookup of its own. Several writes to one account in one slot can arrive as a single notification.

## The Kafka side: a REST proxy and batches

The bridge produces over HTTP, using the Kafka REST Proxy v2 format: a POST to `/topics/<topic>` with content type `application/vnd.kafka.json.v2+json` and a body of `{"records": [{"key": ..., "value": ...}]}`. That keeps the bridge to the global `fetch` and the Node built-ins. If you already run a native Kafka client in your stack, the same record shape moves into its producer call unchanged.

Records collect in a queue and a loop flushes up to 500 of them every half second. The proxy answers with one offset entry per record, and a record whose entry carries an error code goes back to the front of the queue, ahead of newer writes. A whole call that fails, such as a proxy that is down, requeues the batch the same way. The queue holds at most 20,000 writes, in a dry run too, and drops the oldest past that, with a log line that names the count.

Produces are at least once. A retried batch can put a record on the topic twice if the proxy stored it and the answer was lost. Give consumers an idempotent step: the pair of address and slot identifies a write, so a consumer that keeps the highest slot seen per address ignores repeats.

## The bridge

Install with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Run it with the program address as the argument. A busy program shows output within seconds, and with `KAFKA_REST_URL` unset each tick prints the running count of every write received and the last address and slot.

`main.ts` (run: `node main.ts <program address>`)

```ts
// I0030 · Kafka program account topic
// https://carbium.sh/library/integrate/kafka-program-account-topic
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { isAddress } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1); }
const program = process.argv[2];
if (!program || !isAddress(program)) { console.error("Usage: node main.ts <program address>"); process.exit(1); }
const rest = process.env.KAFKA_REST_URL; // unset: dry run, records are counted and shown
const topic = process.env.TOPIC ?? `solana.${program}.accounts`;
const dataSize = Number(process.env.DATA_SIZE) || 0;
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);

type Rec = { key: string; value: Record<string, unknown> };
const queue: Rec[] = [];
let received = 0; // every notification, counted as it arrives
let delivered = 0;
let neverOpened = 0; // closes in a row that never reached open (a 401 refuses the upgrade)

async function flush() {
  if (queue.length > 20_000) console.error(`queue full, dropped ${queue.splice(0, queue.length - 20_000).length} oldest writes`);
  const records = queue.splice(0, rest ? 500 : queue.length); // a dry run drains the whole queue
  if (!records.length) return;
  if (!rest) {
    const last = records.at(-1)!;
    console.log(`dry run: ${received} writes, last ${last.key} at slot ${last.value.slot}`);
    return;
  }
  let retry = records;
  try {
    const res = await fetch(`${rest}/topics/${encodeURIComponent(topic)}`, {
      method: "POST",
      headers: { "content-type": "application/vnd.kafka.json.v2+json" },
      body: JSON.stringify({ records }),
      signal: AbortSignal.timeout(5_000),
    });
    if (!res.ok) throw new Error(`REST proxy answered ${res.status}`);
    const { offsets = [] } = (await res.json()) as { offsets?: { error_code?: number | null }[] };
    retry = records.filter((_, i) => offsets[i]?.error_code); // one entry per record
    delivered += records.length - retry.length;
  } catch (e) {
    console.error("produce failed:", e instanceof Error ? e.message : e);
  }
  queue.unshift(...retry); // back to the front, ahead of newer writes
}

function connect() {
  const ws = new WebSocket(wsUrl);
  let opened = false;
  ws.onopen = () => {
    opened = true;
    neverOpened = 0;
    const config = { encoding: "base64", commitment: "confirmed", ...(dataSize ? { filters: [{ dataSize }] } : {}) };
    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "programSubscribe", params: [program, config] }));
  };
  ws.onmessage = (ev) => {
    const m = JSON.parse(String(ev.data));
    if (m.error) { console.error(`subscribe refused (${m.error.code}): ${m.error.message}`); process.exit(1); }
    if (m.id === 1) console.log(`subscribed to ${program}, subscription ${m.result}, topic ${topic}`);
    if (m.method !== "programNotification") return;
    const { context, value } = m.params.result;
    const a = value.account;
    received++;
    queue.push({
      key: value.pubkey,
      value: { pubkey: value.pubkey, slot: context.slot, lamports: a.lamports, owner: a.owner, executable: a.executable, data: a.data[0] },
    });
  };
  ws.onerror = () => console.error("socket error");
  ws.onclose = (ev) => {
    console.error(`socket closed (code ${ev.code}, reason "${ev.reason}"), reconnecting in 2 s`);
    if (!opened && ++neverOpened >= 5) { console.error("socket never opened 5 times in a row: check CARBIUM_KEY holds the whole key"); process.exit(1); }
    setTimeout(connect, 2_000);
  };
}

connect();
for (;;) {
  await flush();
  await new Promise((r) => setTimeout(r, 500));
}
```

## What it costs against your limits

A program subscription is the heaviest of the three opening weights: it [costs 200 credits to open](https://carbium.sh/docs#limits), then 20 credits per MiB sent. A refused subscription costs nothing. A Dev month of 10M credits covers about 500,000 MiB of notifications at that rate, leaving aside the 200-credit opening charge.

A notification carries the account data in base64, which is about a third larger than the raw bytes, plus a small JSON envelope. A 165-byte token account comes to well under 1 KB, and a large account is many KB. A program that writes thousands of accounts a second therefore sends a lot of bytes. Check the volume before you point the bridge at a firehose: run it in dry mode for a minute, multiply the writes by their size, and compare with your credit balance, then set `DATA_SIZE` if the volume is too high.

[Sockets are capped](https://carbium.sh/docs#websocket) per account, and Free carries 5. The bridge uses one. Limits are per account, so every key on the account shares the same budget.

## Where it ends

- There is no replay. When the socket drops, writes made before the reconnect never arrive. The bridge reconnects after 2 seconds, but the gap stays a gap on the topic. Each reconnect also opens a new program subscription at 200 credits, so a link that keeps dropping costs credits as well as leaving gaps.
- To close a gap, a consumer can re-read the accounts it cares about with `getMultipleAccounts`, at most [100 addresses a call](https://carbium.sh/docs#rpc) below Pro. That fills the latest state of each account, and it cannot rebuild the writes in between.
- The bridge learns of an account only when it is written. It reads no existing state, so a topic starts empty and a consumer that needs the starting state loads it by another route.
- A close may never arrive. A closed account usually ends owned by the System Program, so the program subscription may not report it, and a `dataSize` filter never matches empty data. A consumer that needs deletes finds them by re-reading its addresses with `getMultipleAccounts`, where a closed account comes back null.
- One socket carries the whole program, and with a proxy set one bridge is limited by its loop: it flushes at most 500 records and then waits 500 ms, so it produces under 1,000 writes a second. A program that writes faster fills the 20,000-write queue and the bridge drops writes. Split it across several bridges on separate `dataSize` filters, or use the [gRPC Carbon stream](https://carbium.sh/docs#stream) at `https://services.carbium.sh:9443`, which takes the key in `x-token` and opens on Dev, Business and Pro.
- The bridge has no state of its own. A crash loses the queue, so run it under a supervisor and treat the topic as at least once.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The log shows `subscribe refused` and the process exits. | Read the code and message in the line. Your plan caps connections and subscriptions per account, and Free carries 5 sockets, so close another subscription or connection, or move to a plan with more. |
| The log shows `produce failed: REST proxy answered 404` on every flush and the queue grows. | The URL or the topic is wrong. `KAFKA_REST_URL` is the proxy's base address, without `/topics`, and the topic must exist unless your cluster creates topics on first write. The bridge keeps the writes and retries, so they appear once the cause is fixed. |
| The log shows `queue full, dropped` lines. | Kafka or the proxy has been down longer than the 20,000-write queue covers, or the program writes faster than one bridge can produce. Restore the produce path, then re-read the accounts you care about with `getMultipleAccounts` to repair the gap, in batches of at most 100. |
| Consumers see the same address and slot twice. | A batch was retried after the proxy stored it. Keep the highest slot per address and skip anything at or below it. |
| Nothing prints in the dry run after `subscribed`. | The program has had no account writes since you connected. Pick a busier program, or drop `DATA_SIZE`, which may exclude the accounts that are being written. |
| The log shows `socket error` and `socket closed` every 2 seconds and never `subscribed`. | Carbium answers an unknown key with 401 and refuses the WebSocket upgrade, so the bridge never reaches `subscribe refused`. It exits after 5 closes in a row that never opened, so check that `CARBIUM_KEY` holds the whole key. If the socket did open and then drops, each `socket closed` line carries the close code and reason, and a flapping network path shows up as repeated lines: check the host's connectivity before you change the bridge. |

## Questions

### Why a REST proxy and not a Kafka client library?

The proxy keeps the bridge to the Node built-ins and one HTTP call, which is all this job needs. A native producer takes the same key and JSON value, so you can swap it in without changing the subscription code.

### Can I get only one kind of account from a program?

Set `DATA_SIZE` to the account length in bytes. Programs whose account kinds share a length need a `memcmp` filter on the discriminator as well, which goes in the same `filters` array.

### Will every write show up on the topic?

Every write the socket receives does. Anything written while the socket was down is missing, and several writes to one account in a slot can arrive as one notification. Treat the topic as the latest known state per account.

### Is the gRPC stream a better fit for a very busy program?

It can be, since it filters on the server and opens on Dev, Business and Pro. It needs a gRPC client and the proto files, so the WebSocket path is the shorter one to start with.

## Related

- [Python program subscriptions](https://carbium.sh/library/integrate/python-program-subscriptions) (Integrations, I0005)
- [On-chain event webhooks](https://carbium.sh/library/blockchainideas/on-chain-event-webhooks) (Blockchain ideas, BI0013)
- [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)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
