---
id: I0028
title: "Prometheus program activity counters"
url: https://carbium.sh/library/integrate/prometheus-program-activity-counters
collection: Integrations
category: Search and time series
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Prometheus program activity counters

A small Node exporter opens one Carbium WebSocket log subscription per program, counts the transactions that mention it as ok or failed, and serves the totals at /metrics in Prometheus text format, ready for a scrape job, rate queries and alert rules.

## What the exporter exposes

The exporter is one Node process. You give it program addresses on the command line, and it keeps counters for each one in memory and answers Prometheus scrapes on `/metrics`. The only dependency is `@solana/kit`, used to check that every argument is a valid address before anything connects.

| Series | Type | Meaning |
|---|---|---|
| `carbium_program_transactions_total{program,result}` | counter | Transactions that mention the program, split into `result="ok"` and `result="failed"`. |
| `carbium_program_last_slot{program}` | gauge | The highest slot among the notifications received for the program. |
| `carbium_ws_reconnects_total` | counter | How many times the socket closed and the exporter opened it again. |

Every series exists from the start at 0, so a quiet program draws a flat line and never a gap. The counters live in the process and start again at 0 after a restart. Prometheus reads a drop in a counter as a reset, so `rate()` and `increase()` stay correct across restarts.

## The Solana side: one log subscription per program

Carbium's [WebSocket](https://carbium.sh/docs#websocket) takes `logsSubscribe`, which streams transaction logs for every transaction or only for those that mention an address. The exporter opens one mentions subscription per program, because a mentions filter holds a single address. The notification for each transaction carries its signature, the slot, the logs and an `err` field.

`err` is null when the transaction succeeded and holds the error otherwise. That one field decides the `result` label: null counts as `ok`, anything else as `failed`. Failed transactions arrive in the log stream like any other, so a failure rate needs no `getTransaction` call at all.

The subscribe call names commitment `confirmed`, so the counts depend on no server default. Change that string to `processed` or `finalized` for another level.

A subscribe request is answered with a subscription number, and every notification carries the number of the subscription that produced it. The exporter keeps a small map from number to program and builds it again on each new connection, since a reconnect hands out new numbers. A socket that closes is reopened after 2 seconds, and `carbium_ws_reconnects_total` goes up by one.

> A transaction that mentions two of your programs is counted once under each, so a sum across programs counts it twice.

## The exporter

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is required, and the program addresses follow the file name. `CARBIUM_WS_URL`, `METRICS_PORT` (default 9464) and `METRICS_HOST` (default 127.0.0.1) are optional. The socket URL carries the key in the [query string](https://carbium.sh/docs#auth) as `?api-key=`, and the code never prints it.

`main.ts` (run: `node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4`)

```ts
// I0028 · Prometheus program activity counters
// https://carbium.sh/library/integrate/prometheus-program-activity-counters
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createServer } from "node:http";
import { isAddress } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
const programs = [...new Set(process.argv.slice(2))];
if (!key || programs.length === 0 || !programs.every((p) => isAddress(p))) {
  console.error("Set CARBIUM_KEY and pass program addresses: node main.ts <program> [<program>...]");
  process.exit(1);
}
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
const port = Number(process.env.METRICS_PORT ?? 9464);
const host = process.env.METRICS_HOST ?? "127.0.0.1";

type Count = { ok: number; failed: number; slot: number };
// Every series starts at 0, so a quiet program still shows up.
const counts = new Map<string, Count>(programs.map((p): [string, Count] => [p, { ok: 0, failed: 0, slot: 0 }]));
let reconnects = 0;

function render(): string {
  const rows = [...counts];
  return [
    "# HELP carbium_program_transactions_total Transactions that mention the program, at confirmed commitment.",
    "# TYPE carbium_program_transactions_total counter",
    ...rows.flatMap(([p, c]) => [
      `carbium_program_transactions_total{program="${p}",result="ok"} ${c.ok}`,
      `carbium_program_transactions_total{program="${p}",result="failed"} ${c.failed}`,
    ]),
    "# TYPE carbium_program_last_slot gauge",
    ...rows.map(([p, c]) => `carbium_program_last_slot{program="${p}"} ${c.slot}`),
    "# TYPE carbium_ws_reconnects_total counter",
    `carbium_ws_reconnects_total ${reconnects}`,
    "",
  ].join("\n");
}

function connect(): void {
  const subs = new Map<number, string>(); // subscription number -> program, rebuilt per connection
  const ws = new WebSocket(wsUrl.href);
  ws.onopen = () =>
    programs.forEach((p, i) =>
      ws.send(JSON.stringify({ jsonrpc: "2.0", id: i, method: "logsSubscribe", params: [{ mentions: [p] }, { commitment: "confirmed" }] })),
    );
  ws.onmessage = (ev) => {
    const m = JSON.parse(String(ev.data));
    if (m.id !== undefined) {
      if (m.error) console.error(`subscribe failed for ${programs[m.id]}: ${m.error.message}`);
      else subs.set(m.result, programs[m.id]);
      return;
    }
    const c = counts.get(subs.get(m.params?.subscription) ?? "");
    const r = m.params?.result;
    if (m.method !== "logsNotification" || !c || !r) return;
    if (r.value.err === null) c.ok++;
    else c.failed++;
    c.slot = Math.max(c.slot, r.context.slot);
  };
  ws.onerror = () => console.error("socket error");
  ws.onclose = () => {
    reconnects++;
    console.error("socket closed, reconnecting in 2 s");
    setTimeout(connect, 2000);
  };
}

const server = createServer((req, res) => {
  if (req.url !== "/metrics") {
    res.writeHead(404).end();
    return;
  }
  res.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" }).end(render());
});
server.on("error", (e) => {
  console.error("metrics server failed:", e.message);
  process.exit(1);
});
server.listen(port, host, () => console.log(`metrics on http://${host}:${port}/metrics for ${programs.length} program(s)`));
connect();
setInterval(() => {
  for (const [p, c] of counts) console.log(`${p} ok=${c.ok} failed=${c.failed} slot=${c.slot}`);
}, 10_000);
```

Start it with `node main.ts` and one or more program addresses. Every 10 seconds it prints one line per program with the ok count, the failed count and the newest slot, so a first run shows activity before Prometheus is involved. `curl http://127.0.0.1:9464/metrics` shows the same numbers in scrape format.

## Scrape it and query it

Add a `scrape_configs` entry with `job_name: carbium-programs` and `static_configs: [{ targets: ['127.0.0.1:9464'] }]`, then reload Prometheus.

- `sum by (program) (rate(carbium_program_transactions_total[5m]))` gives transactions per second for each program.
- `sum by (program) (rate(carbium_program_transactions_total{result="failed"}[5m])) / sum by (program) (rate(carbium_program_transactions_total[5m]))` gives the share of transactions that fail.
- `increase(carbium_ws_reconnects_total[15m]) > 3` fires when the socket keeps dropping.

For a program that normally sees traffic, add an alert on `increase(carbium_program_transactions_total[10m]) == 0`. It is the only way to catch a subscription that goes silent while the socket stays open, and the exporter has no check of its own for that. For the dashboard side, see [Grafana network metrics](https://carbium.sh/library/integrate/grafana-network-metrics).

## What it costs against your limits

One exporter holds one socket, and a plan caps [connections and subscriptions](https://carbium.sh/docs#websocket) per account; Free carries 5 sockets. Each program is one subscription. Opening a logs mentions subscription costs 25 credits, then [20 credits per MiB sent](https://carbium.sh/docs#limits), and a refused one costs nothing.

The per-MiB part follows the program's traffic. Every notification carries the full log of its transaction, so a busy program sends far more than a quiet one. Run the exporter against one program for ten minutes and compare your credit use before and after to get your own figure. A flapping socket also pays the opening cost again for every program on every reconnect. Credits meter this work, and unspent ones stay, so a quiet program costs little to keep open.

## Where it ends

- It counts transactions that mention the program in their account keys. Most of them invoke it, but a transaction that only lists the address as an account is counted too.
- A closed socket leaves a gap. Transactions that landed while it was down are never counted, and the exporter does not backfill. `getSignaturesForAddress` reaches back 30 days at 50 cells a call and could fill a gap, but this code does not call it.
- The exporter parses no log lines, so it gives no per-instruction or compute-unit breakdown. Only fees need a fetch of each transaction.
- Counters start at 0 on every restart and nothing is written to disk. Query with `rate()` and `increase()`, never the raw value.
- The `/metrics` endpoint has no authentication and listens on loopback by default. Set `METRICS_HOST` to a private address only on a network you control.
- A very busy program can use credits quickly, and one process holds every subscription you pass it. Split programs across processes if one gets too heavy.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The log fills with `socket error` and `socket closed, reconnecting in 2 s`, and the counters stay at 0. | Send the whole key in `CARBIUM_KEY`: an unknown key gets [401 at the door](https://carbium.sh/docs#errors) and the socket never opens. Then check that `CARBIUM_WS_URL` is unset or holds only the WebSocket endpoint, with no path or query. |
| The log shows `subscribe failed for <program>` followed by a message from the server. | The server refused that subscription, for example when the plan's [cap on connections and subscriptions](https://carbium.sh/docs#websocket) is reached. Pass fewer programs or close other clients on the account. A refused subscription costs no credits. |
| `carbium_ws_reconnects_total` climbs several times an hour. | Each reopen leaves a gap in the counts and pays the opening credits again for every program. Look in the exporter log and on the network path for whatever cuts the connection, such as a proxy with a short idle timeout, and keep the reconnect alert on. |
| A program that is busy on chain shows 0 new transactions for minutes while the socket is up. | The subscription went quiet. Restart the exporter, and compare with a program you know is busy to confirm the stream works. The zero-increase alert exists to catch this. |
| Credits drain faster than expected. | Cost follows the [MiB sent](https://carbium.sh/docs#limits), which follows the program's traffic. Count fewer or quieter programs or move to a plan with more monthly credits, and measure again over ten minutes. |
| Prometheus shows the target down with connection refused from another host. | The exporter listens on 127.0.0.1 by default. Run Prometheus on the same host, or set `METRICS_HOST` to an address on a private network and open only that port. |

## Questions

### Why a subscription and not a poll of getSignaturesForAddress?

A poll costs [50 cells a call](https://carbium.sh/docs#rpc) and returns pages that you must deduplicate between runs. The subscription pushes each transaction once, and its credit cost follows the program's traffic.

### Can I put several programs in one subscription?

No. A mentions filter takes one address, so the exporter opens one subscription per program and maps each notification back by its subscription number.

### Can I count at processed or finalized instead?

Yes. Change the commitment string in the subscribe call. The exporter names `confirmed` in code so the counts do not depend on a server default.

### Does it run on the Free plan?

It holds one socket, and Free carries 5. Free's 500K credits arrive once at sign-up, so a busy program can spend them quickly.

## Related

- [Grafana network metrics](https://carbium.sh/library/integrate/grafana-network-metrics) (Integrations, I0017)
- [Failed-mint monitor](https://carbium.sh/library/blockchainideas/failed-mint-monitor) (Blockchain ideas, BI0001)
- [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#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
