library / Blockchain ideas / Developer tools / BI0078
gRPC gap detection and replay
A gRPC consumer that drops its connection can rebuild the missed range without losing or doubling an update. Detect the gap from slot numbers, refetch those slots with getBlock at full detail, run your own filter, and dedupe by signature.
Who needs it
A team that runs a gRPC consumer in production meets the same event sooner or later: the connection drops, the process restarts, and for a few seconds nobody was listening. The stream carried a filter, so the first update after the reconnect says nothing about what arrived in between. The fix rebuilds the missing stretch and feeds it to the same handler as live updates, with no update lost and none handled twice.
Indexers that write rows, alerting services that page a person and ledgers that count payments need the same guarantee: every matching event handled exactly once, whatever the network did.
A production stream consumer needs three things: filters applied on the server, a way to replay what it missed, and a service level it can plan around.
| The ask | Where it is answered |
|---|---|
| Server-side filters | The gRPC stream filters on the server: you subscribe with filters and only matches reach you. It runs on port 9443 for Dev, Business and Pro, with the key in the x-token header. |
| Replay | The consumer does it. After a disconnect it works out which slots it missed, fetches them with getBlock and runs the same filter itself. |
| Production service levels | A figure is agreed between you and a provider in a contract. What you control is a consumer that stays correct at any disconnect rate, and the gap check plus backfill give you that. |
Detect the gap
A filtered stream is quiet by design. With an account or transaction filter, a slot that held no match produces no update, so two updates at slots 400 and 407 prove nothing. Six slots may have passed with no match, or the connection may have dropped some of them. Slot numbers on filtered updates cannot reveal a gap.
Add a slots filter to the same subscription. A slot update then arrives for every slot the validator produced, match or no match, and it carries the slot number and the parent slot. When a new slot is above the last one you saw plus one, the numbers in between are the range to replay.
The code below runs the check on the WebSocket's slotSubscribe, which needs no gRPC client or proto files, so it runs with Node alone. That subscription opens at 5 credits and then costs 20 credits per MiB sent. The same check works on the gRPC stream (Dev, Business and Pro) with a slots filter.
Backfill with getBlock
For each missing slot, call getBlock with transactionDetails: "full". One call per slot returns every transaction with its meta: the status, the log messages, the balance changes and the inner instructions a live update would have carried. No second call per signature is needed. The "signatures" setting returns only the list, which is enough to count transactions and check for repeats. A consumer that processes the transactions asks for "full".
Pass maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with the value absent or 0 getBlock answers -32015, uncharged, for any block holding one. getBlock takes confirmed or finalized commitment and never processed, so a slot announced a moment ago can answer -32004 until it is confirmed, and the retry covers that. The code asks at confirmed commitment.
- A block: run your filter over its transactions and hand the matches to your handler.
- -32007: the slot was skipped, so nothing happened in it. Move on. A slot you saw live can end here too, when its fork was dropped.
- -32001: the slot is below the node's first available block, which the node has cleaned up. A retry cannot bring it back, so the code reports the slot as unrecovered at once.
- Any other error, including a 429 or a -32004 for a slot not yet confirmed: try again, up to three tries, and wait the retry-after seconds a 429 carries. After the last try, report the slot as unrecovered and let a later pass take it.
The block holds every transaction in the slot, so the filter is yours to apply. For an account filter, check the transaction's account keys and also the writable and readonly addresses loaded from lookup tables, which sit in meta.loadedAddresses. A program that most callers reach through a lookup table matches only if you read both lists.
Replay draws on the same budget as everything else on the account, because limits are per account. Keep each pass short and pace the calls.
Dedupe by signature
Start the live subscription first and buffer what it delivers, then run the backfill, then drain the buffer. That order leaves no slot between the replay and the live stream. It also makes them overlap, and the overlap is where a transaction gets handled twice.
The first signature of a transaction identifies it. Keep a set of signatures handled recently, trim it by slot as the stream moves on, and skip any signature already in it. The same set serves the live path, the replay and a restart that replays a few slots too many on purpose.
Save the last slot you fully handled after every batch, as in checkpointing your last slot. After a crash the consumer starts from that slot, finds the gap against the first live slot and runs the same backfill.
The code
One file, Node 24 and nothing to install. It plays the outage itself and then recovers from it. It is read-only: no private key, nothing sent.
- Open slotSubscribe on wss://services.carbium.sh with the key as ?api-key= and record slot numbers for 2 seconds.
- Close the socket and wait 4 seconds, which is about 20 slots.
- Reconnect, listen again and take the smallest slot number of the new window.
- The missing range runs from the last slot seen plus one to that slot minus one. The code takes the first 10.
- Call getBlock at full detail and version 1 for each, three tries, with -32007 counted as skipped and -32001 counted as unrecovered without a retry.
- Keep the transactions that mention PROGRAM_ID in their account keys or loaded addresses, skip signatures already seen, and print matches, failures and log lines for every slot.
PROGRAM_ID takes any address that busy transactions mention, such as a popular program or one vault. The default is an active program, so a run shows matches.
// BI0078 · gRPC gap detection and replay// https://carbium.sh/library/blockchainideas/grpc-gap-detection-and-replay// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key: string = process.env.CARBIUM_KEY ?? "";if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const RPC_URL = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const WS_URL = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;const WATCH = process.env.PROGRAM_ID ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";const MAX_SLOTS = 10;const TRIES = 3;const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));type Tx = { transaction: { signatures: string[]; message: { accountKeys: string[] } }; meta: { err: unknown; logMessages?: string[]; loadedAddresses?: { writable: string[]; readonly: string[] } } | null;};type Reply = { result?: { transactions: Tx[] }; error?: { code: number; message: string } };function listen(ms: number): Promise<number[]> { return new Promise((resolve) => { const slots: number[] = []; const ws = new WebSocket(WS_URL); ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" })); ws.onmessage = (ev) => { const msg = JSON.parse(String(ev.data)); if (msg.error) console.error("slotSubscribe refused:", msg.error.message); if (msg.method === "slotNotification") slots.push(msg.params.result.slot); }; ws.onerror = () => console.error("socket error"); setTimeout(() => (ws.close(), resolve(slots)), ms); });}async function getBlock(slot: number): Promise<Tx[] | "skipped"> { for (let attempt = 1; ; attempt++) { const res = await fetch(RPC_URL, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getBlock", params: [slot, { commitment: "confirmed", encoding: "json", transactionDetails: "full", rewards: false, maxSupportedTransactionVersion: 1 }], }), }); const reply = (await res.json().catch(() => ({}))) as Reply; if (reply.result) return reply.result.transactions; if (reply.error?.code === -32007) return "skipped"; if (reply.error?.code === -32001) throw new Error("below the node's first available block (-32001)"); const why = reply.error?.message ?? `HTTP ${res.status}`; if (attempt === TRIES) throw new Error(`${why} after ${TRIES} tries`); await sleep(Number(res.headers.get("retry-after") ?? 1) * 1000); }}async function main(): Promise<void> { const seen = new Set<string>(); const before = await listen(2000); console.log(`live: ${before.length} slots, last ${before[before.length - 1]}`); console.log("socket closed for 4 seconds"); await sleep(4000); const after = await listen(1500); if (!before.length || !after.length) { console.error("no slot notifications received"); process.exit(1); } const from = Math.max(...before) + 1; const to = Math.min(...after) - 1; console.log(`reconnected at slot ${to + 1}, missing ${Math.max(to - from + 1, 0)} slots`); for (let slot = from; slot <= Math.min(to, from + MAX_SLOTS - 1); slot++) { try { const block = await getBlock(slot); if (block === "skipped") { console.log(`slot ${slot}: skipped`); continue; } const hits = block.filter((tx) => { const sig = tx.transaction.signatures[0]; const loaded = tx.meta?.loadedAddresses; const keys = [...tx.transaction.message.accountKeys, ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])]; if (seen.has(sig) || !keys.includes(WATCH)) return false; seen.add(sig); return true; }); const failed = hits.filter((tx) => tx.meta?.err != null).length; const lines = hits.reduce((n, tx) => n + (tx.meta?.logMessages?.length ?? 0), 0); console.log(`slot ${slot}: ${block.length} transactions, ${hits.length} match, ${failed} failed, ${lines} log lines`); } catch (e) { console.error(`slot ${slot} not recovered:`, e instanceof Error ? e.message : e); } }}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });
run: CARBIUM_KEY=<YOUR_KEY> PROGRAM_ID=<PROGRAM_ADDRESS> node main.ts
The per-slot line counts log lines from meta. Those lines came in the same getBlock reply, with no call per signature. A real consumer swaps the console.log for its handler and writes the last slot to storage.
Where it ends
- A block has transactions and their meta, and it does not have account contents at that slot. A filter on account data, such as a memcmp match on bytes, replays only as far as the transactions touching the account. Read the account again after the replay if you need its current state.
- Your replay filter must match the server filter's rules. A rule you forgot gives counts that differ between live and replayed slots, most often an account reached only through meta.loadedAddresses.
- -32007 reads as skipped, or missing due to a ledger jump to a recent snapshot. A slot below the node's first available block answers -32001 instead, and the code counts it as unrecovered without a retry, so replay promptly.
- The code takes 10 slots a run. A gap of thousands of slots needs batches and a saved slot after each.
- Live updates and replayed blocks can differ in commitment. Pick one for both, and decide what your handler does with a slot that was announced and later skipped.
- The gRPC stream opens on Dev and above. The WebSocket check in the code runs on any plan that opens a slot subscription.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getBlock answers -32015 for a slot. | The slot holds a v1 transaction and the call left out the version. Send maxSupportedTransactionVersion: 1 with an encoding, as the code does. |
| Every slot in the range answers -32001. | The range sits below the node's first available block, which the node has cleaned up. Print the first and last slot of the range and compare them with getSlot, then replay sooner after a disconnect. |
| A slot answers -32004 during replay. | The slot was announced at processed and is not confirmed yet. The retry pauses and asks again; a slot still failing after the last try is left for a later pass. |
| The same transaction reaches the handler twice, once live and once replayed. | Keep the signatures handled recently and skip repeats across the replay, the live buffer and a restart. The first signature of a transaction is its id. |
| Replayed counts for a slot differ from what the live stream sent. | The usual cause is an account that only appears through a lookup table. Match against meta.loadedAddresses as well as the account keys, and confirm your filter applies the same rules as the server's. |
| The range comes back empty after a reconnect. | The socket was back within one slot, so nothing was missed. An empty range is a valid result and needs no replay. |
Questions
Why add a slots filter just to find gaps?
Filtered updates skip slots with no match, so their slot numbers cannot tell a quiet stretch from lost updates. A slots filter delivers every produced slot, and a jump in those numbers marks the missing range.
Which plans can run the gRPC side?
Dev, Business and Pro open the gRPC stream on port 9443, and Free is off. The WebSocket slot subscription in the code uses the same arithmetic and needs only the key.
Does getBlock return logs and inner instructions?
Yes, with transactionDetails: "full". Each transaction's meta carries its logs, balance changes and inner instructions, in one call per slot.
How many slots can I replay in one pass?
The code takes 10 to keep one run short. Page a longer gap in batches and save the last replayed slot after each.
A slot I handled live now answers -32007. What do I do?
Its fork was dropped, so the slot never became part of the chain. Treat it as skipped and reconcile any transaction you handled from it.