---
id: I0068
title: "Subscription dead-man alert"
url: https://carbium.sh/library/integrate/subscription-dead-man-alert
collection: Integrations
category: Chat and notifications
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Subscription dead-man alert

A Node script opens one WebSocket with a slot heartbeat and two log subscriptions, checks the subscription acknowledgements, then reconciles against signature history. It prints a verdict per subscription and a JSON alert body ready for a chat webhook.

## Four facts, five verdicts

A log subscription that goes silent has several causes, and each wants a different reaction. The server may have refused the subscription. The socket may have died. The program may simply have had no transactions. Or the subscription may be alive and dropping some of them. All four look like an empty stream, so staring at the logs cannot separate them. The checker reads four facts instead and turns them into one verdict with a pure function. The rules sit in one place, and a unit test can feed the function any combination.

- Acknowledgement: whether the subscribe request came back with a numeric subscription id.
- Heartbeat age: seconds since the last slot notification on the same socket.
- Last log age: seconds since the last log notification for that subscription, or none yet.
- Missed: how many signatures the address history lists inside the watched window that the socket never sent.

The function checks its rules in order and the first match wins.

| Verdict | What the facts say | Reaction |
|---|---|---|
| unknown | No subscription id came back. | A setup fault: key, plan caps or request shape. Alert. |
| dead | An id came back, but the heartbeat is older than 5 seconds. | The socket or the server's push path stopped. Reconnect and resubscribe. Alert. |
| dropping | The heartbeat is fresh and the history lists signatures the socket never sent. | Logs are lost on a live socket. Resubscribe and backfill from history. Alert. |
| quiet | The heartbeat is fresh, the history agrees, and no log arrived in the last 10 seconds. | The program had nothing to say. No alert. |
| flowing | The heartbeat is fresh, nothing is missed, and a log arrived in the last 10 seconds. | Healthy. No alert. |

## Why the acknowledgement comes first

A `logsSubscribe` request is answered with a JSON-RPC response whose `result` is a number, the subscription id. Every later `logsNotification` carries that id in `params.subscription`, so the id also routes each message to the right address. If the response is an error or never comes, nothing else is worth reading. An empty stream from a subscription that does not exist looks the same as an empty stream from a quiet program, and the heartbeat stays alive in both cases. That is why `unknown` sits above every other verdict. The code stores the id per request id and returns `unknown` while it is still null.

Carbium's [WebSocket](https://carbium.sh/docs#websocket) caps connections and subscriptions per account, and Free carries 5 sockets. A refused subscription costs nothing, so a refusal leaves no charge to notice. On an account shared by several services, close the subscriptions and sockets that your other services left open before you suspect the program or the network. Opening is metered by [filter weight](https://carbium.sh/docs#limits): a slot subscription costs 5 credits, a logs subscription with a mention costs 25, and each costs 20 credits per MiB sent after that. The run below opens one of the first and two of the second.

## The heartbeat on the same socket

`slotSubscribe` sends a notification for each slot the node processes, about every 200 ms on mainnet since the Alpenglow switch. Subscribed on the same socket as the logs, it gives a clock that needs no program to be active. While those notifications keep coming, the socket and the server's push path are alive, so empty logs most likely mean a quiet program. When they stop, the verdict is `dead`, whatever the program is doing.

The threshold is 5 seconds, about 25 slots. A slot whose leader never produced a block sends no notification, so one gap in the stream is normal. Only an age that keeps growing past a few seconds counts. A heartbeat cannot see a subscription the server dropped while leaving the socket open. That case shows up as `dropping`, through the history check.

## Reconcile against signature history

A fresh heartbeat with an empty log stream leaves one question open, and a plain timeout would answer it by assumption. The checker asks the chain's own record. After the watch window it calls `getSignaturesForAddress` for the address, newest 1,000 signatures at `confirmed` commitment, and keeps the ones inside the slots the socket covered. That range starts at the first heartbeat after every subscription was acknowledged and ends five slots below the newest heartbeat, so a signature still on its way through the confirmed stream is not counted as lost.

Any signature in that range that never arrived as a `logsNotification` goes into the missed list by signature. Fetch it with `getTransaction` and `maxSupportedTransactionVersion: 1` and carry on from there. History and the log stream both include failed transactions, so a failed one does not show up as a false gap. A non-empty list on a live heartbeat gives `dropping`. An empty list and no recent log gives `quiet` with evidence behind it.

The call costs [50 cells](https://carbium.sh/docs#rpc), and Free allows 0.24 req/s of it. The two calls in one check lean on the 1,024-cell burst allowance, so one check a minute fits comfortably. Run the reconcile on a timer, or only when the verdict is not `flowing`.

## The checker

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. The script reads `CARBIUM_KEY`, which is required, and the optional `CARBIUM_RPC_URL` and `CARBIUM_WS_URL`. The key travels in the `x-api-key` header for the history call and as `?api-key=` on the WebSocket URL. Two optional arguments name a busy address and a quiet one; the defaults are the Memo program and the Config program.

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

```ts
// I0068 · Subscription dead-man alert
// https://carbium.sh/library/integrate/subscription-dead-man-alert
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1); }
// Memo is busy and Config is rarely touched. Pass your own two addresses as arguments.
const [busyAddr = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", quietAddr = "Config1111111111111111111111111111111111111"] = process.argv.slice(2);
const WINDOW_MS = 20_000, BEAT_MAX_S = 5, QUIET_S = 10, MARGIN = 5n;
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({
  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
  headers: { "x-api-key": key },
}));
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);

type Verdict = "unknown" | "dead" | "dropping" | "quiet" | "flowing";
// Pure: four observed facts in, one verdict out. The first matching rule wins.
function verdict(f: { acked: boolean; beatAge: number | null; logAge: number | null; missed: number }): Verdict {
  if (!f.acked) return "unknown";
  if (f.beatAge === null || f.beatAge > BEAT_MAX_S) return "dead";
  if (f.missed > 0) return "dropping";
  return f.logAge === null || f.logAge > QUIET_S ? "quiet" : "flowing";
}

type Watch = { name: string; addr: string; subId: number | null; seen: Set<string>; lastLogAt: number | null };
const watches: Watch[] = [["busy", busyAddr], ["quiet", quietAddr]].map(([name, addr]) => ({ name, addr, subId: null, seen: new Set<string>(), lastLogAt: null }));
const st = { beatAt: null as number | null, from: null as bigint | null, to: 0n };

const ws = new WebSocket(wsUrl);
ws.onerror = () => console.error("socket error");
ws.onclose = (e) => console.error(`socket closed ${e.code}`);
ws.onopen = () => {
  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" }));
  watches.forEach((w, i) => ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 2, method: "logsSubscribe", params: [{ mentions: [w.addr] }, { commitment: "confirmed" }] })));
};
ws.onmessage = (e) => {
  const m = JSON.parse(String(e.data));
  if (m.method === "slotNotification") {
    st.beatAt = Date.now();
    st.to = BigInt(m.params.result.slot);
    if (st.from === null && watches.every((w) => w.subId !== null)) st.from = st.to; // window starts once every ack is in
  } else if (m.method === "logsNotification") {
    const w = watches.find((x) => x.subId === m.params.subscription);
    if (w) { w.seen.add(m.params.result.value.signature); w.lastLogAt = Date.now(); }
  } else if (m.id >= 2 && typeof m.result === "number") watches[m.id - 2].subId = m.result;
  else if (m.error) console.error(`request ${m.id} refused: ${m.error.message}`);
};

// Signatures in the covered slots that the socket never sent.
async function missedFor(w: Watch): Promise<string[]> {
  if (st.from === null) return [];
  const lo = st.from, hi = st.to - MARGIN;
  const page = await rpc.getSignaturesForAddress(address(w.addr), { limit: 1000, commitment: "confirmed" }).send();
  return page.filter((s) => s.slot >= lo && s.slot <= hi && !w.seen.has(s.signature)).map((s) => s.signature);
}

await new Promise((r) => setTimeout(r, WINDOW_MS));
// Snapshot the ages at the end of the window: notifications keep moving the timestamps during the history calls.
const end = Date.now();
const age = (t: number | null) => (t === null ? null : (end - t) / 1000);
const heartbeatAgeS = age(st.beatAt);
const lastLogAgeS = watches.map((w) => age(w.lastLogAt));
const results = await Promise.allSettled(watches.map((w) => missedFor(w)));
watches.forEach((w, i) => {
  const r = results[i];
  if (r.status === "rejected") console.error(`${w.name}: history read failed: ${String(r.reason)}`);
  const missed = r.status === "fulfilled" ? r.value : [];
  const v = verdict({ acked: w.subId !== null, beatAge: heartbeatAgeS, logAge: lastLogAgeS[i], missed: missed.length });
  console.log(`${w.name} ${w.addr.slice(0, 8)}: ${v}`);
  console.log(JSON.stringify({
    text: `Log subscription ${w.name} (${w.addr.slice(0, 8)}) is ${v}`,
    fire: v === "unknown" || v === "dead" || v === "dropping",
    verdict: v, address: w.addr, subscription: w.subId,
    heartbeatAgeS, lastLogAgeS: lastLogAgeS[i],
    received: w.seen.size, missed: missed.slice(0, 10),
  }));
});
ws.close();
process.exit(0);
```

Run `node main.ts`. The script watches for 20 seconds, reconciles, prints one verdict line and one JSON line per address, and exits. The Memo program usually shows `flowing` and the Config program usually shows `quiet`.

## The alert payload

Each address gets one JSON object. `text` is a sentence for people. `fire` is true for `unknown`, `dead` and `dropping`. The other fields are for a router or a log index: the verdict, the address, the subscription id, both ages in seconds, how many notifications arrived, and the first ten missed signatures.

Many chat incoming webhooks accept a `text` field; rename it if yours expects another. The script prints the object so the run needs no webhook URL. In a service, post the JSON with `fetch` when `fire` is true and the verdict differs from the last one you sent, and send one more message when the verdict returns to `flowing`.

## Where it ends

- One run is one 20-second window. A service keeps the last verdict between runs and loops the check.
- The history call returns at most the newest 1,000 signatures. On an address busier than that inside the window, the older end of the range goes unchecked.
- A missed event shows up as its signature, with nothing about the cause.
- The checker does not reconnect or resubscribe. For that part, read [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect).
- It sends no alert itself. Its output is a verdict and a JSON body for you to deliver.
- A slot heartbeat adds a small steady stream to the socket, billed at the same 20 credits per MiB as the logs.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every address prints `unknown` and the log shows `request 2 refused`, or shows nothing at all. | No subscription id came back. Check that `CARBIUM_KEY` holds the whole key and that the WebSocket URL carries it as `?api-key=`. The plan caps subscriptions and sockets per account, and Free carries 5 sockets, so close what your other services left open and run it again. |
| The busy address prints `dead` although the program is active. | The last slot notification is older than 5 seconds. The log line `socket error` or an early close explains it. Check the network path and the key, then reconnect and resubscribe before reading the logs again. |
| An address you picked as busy prints `quiet` on every run. | The address had no transactions in the window, and `quiet` is the right answer. Pass an address with several transactions per second as the first argument. |
| The history read fails with a 429 and the log shows `history read failed`. | Free allows 0.24 req/s of `getSignaturesForAddress`, and two calls at once lean on the burst allowance. Wait the `retry-after` the answer carries, then run the check less often. A failed history read leaves `missed` at zero, so treat that verdict as unconfirmed. |
| The chat webhook rejects the JSON body. | Your webhook expects another field name for the message. Rename `text` in the payload to the one it expects and leave the other fields for your router. |

## Questions

### Why not restart the socket whenever the logs go silent?

A restart on every silence cycles each healthy but quiet subscription too. The verdict tells you the action: reconnect for `dead`, resubscribe and backfill for `dropping`, fix the setup for `unknown`, and leave `quiet` alone.

### Does a refused subscription cost credits?

No. A refused subscription is not charged. The credits start when a subscription opens: 5 for a slot subscription, 25 for a logs subscription with a mention, then 20 per MiB sent.

### Can I watch more than two addresses?

Yes. Send one `logsSubscribe` per address and keep one id and one seen set for each. A single slot heartbeat covers all of them, but the plan caps subscriptions per account, so count them against it.

### Is 5 seconds the right heartbeat limit?

It is about 25 slots at the current slot time and a safe start. Skipped slots send no notification, so the stream has small gaps. Raise the limit on a link that stalls briefly.

## Related

- [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) (How to use Solana, HS0036)
- [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) (Integrations, I0001)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
