services
Get a key

library / How to use Solana / HS0057

Node-behind error handling

One TypeScript file turns a -32005 node-behind error into a wait sized from numSlotsBehind, shown on a synthetic error and then on live getHealth and getSlot calls, with the slot time measured from recent performance samples.

By Carbium · Confirmation and retries · HS0057 · updated 2026-11-22

01

What the error says

Error -32005 means the node that received your call sees itself behind the cluster. The message reads like Node is behind by 166 slots, and the error data carries the same count as numSlotsBehind. The count measures the gap between that node's view and the tip it knows about. It says nothing about your request, and the same call sent a moment later to a node that has caught up would have worked.

getHealth returns ok when the node is inside its threshold and this error when it is not, so it is a light way to ask the question before you touch anything of yours. @solana/kit throws the error with the JSON-RPC code in context.__code and the count in context.numSlotsBehind. The count can be missing, so the handler below treats a missing count as zero and still waits a short time.

Your callWhat to doWhy
A read where a later answer is fineWait, then repeat the callThe error carries no data about your request, so there is nothing to correct
A read that must not be older than a slot you have seenAdd minContextSlot, wait on refusalThe node then refuses an old view instead of serving it
A send with a blockhash that is still validSend the same signed bytes again after the waitThe same bytes carry the same signature, and a signature can land once
A send whose blockhash has expiredProve the old signature never landed, then sign anewTwo different signed transactions can both land
$The error describes the node at that moment. The code classifies it and waits. Nothing in it is a reason to rebuild or re-sign a transaction.
02

Reads while the node is behind

A plain read has one safe answer: pause and ask again. The pause is sized from the count. Since the Alpenglow switch on 2026-10-21 a mainnet slot lasts about 200 ms, so 166 slots is about 33 seconds of cluster time. Use that product as the first pause and cap it, because a pause longer than your caller can stand is a worse failure than one more error. The next call comes back with either an answer or a fresh count, and the fresh count is a better guide than the first one.

Measure the slot time on each run. getRecentPerformanceSamples returns recent windows with a slot count and a window length in seconds, and dividing one by the other gives the milliseconds per slot your cluster is producing right now.

When the read has to be at least as new as something you already saw, such as the slot of your own write, pass minContextSlot. A node that has not reached that slot answers -32016 with the slot it did reach in the error data, and you wait exactly as for -32005. The pattern is the subject of Consistent reads with minContextSlot. The difference is that -32005 is the node's own statement about its health, while -32016 is a refusal tied to the number you passed.

03

Sends while the node is behind

A send that comes back with -32005 came back with an error and no signature, so you hold bytes that the node did not accept. You still hold the signed transaction, and you know its signature, because the signature is the first signature inside the signed bytes. Sending those same bytes again after the wait is safe while the blockhash is valid: both attempts carry one signature, and the chain executes a signature once.

A blockhash stays valid for 150 blocks of block height, which at about 200 ms per slot is about 30 seconds. A 166-slot lag is therefore about as long as the blockhash lives. Keep the lastValidBlockHeight that came with the blockhash and compare it to getBlockHeight before every resend. Once the height has passed it, the old transaction can no longer land, and only then is a new signature safe. Before that, getSignatureStatuses on the old signature tells you whether it landed anyway.

Each send is a metered call. On Carbium sendTransaction costs 20 cells without preflight and 70 with it, so a resend loop spends that on every try. Cap the tries and wait between them as the handler does. Dropped transaction detector covers the check that tells a dropped transaction from a slow one.

04

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on load. The RPC endpoint is https://services.carbium.sh unless CARBIUM_RPC_URL says otherwise, and the key travels in the x-api-key header.

main.ts
// HS0057 · Node-behind error handling// https://carbium.sh/library/howsolana/node-behind-error-handling// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { setTimeout as sleep } from "node:timers/promises";import { createDefaultRpcTransport, createSolanaRpcFromTransport } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),);type Decision = { action: "wait" | "fail"; waitMs: number; behind?: number };const MAX_WAIT_MS = 30_000;let slotMs = 200; // assumed until the samples replace it// -32005 describes the node, so the answer is a wait. Any other error is not ours to retry.function classify(e: unknown, msPerSlot: number): Decision {  const ctx = (e as { context?: { __code?: number; numSlotsBehind?: number } } | null)?.context;  if (ctx?.__code !== -32005) return { action: "fail", waitMs: 0 };  const behind = Number(ctx.numSlotsBehind ?? 0);  const waitMs = Math.min(MAX_WAIT_MS, Math.max(500, Math.round(behind * msPerSlot)));  return { action: "wait", waitMs, behind };}// Three tries; a wait decision sleeps and repeats the same call.async function guarded<T>(call: () => Promise<T>): Promise<T> {  for (let attempt = 1; ; attempt++) {    try {      return await call();    } catch (e) {      const d = classify(e, slotMs);      if (d.action === "fail" || attempt === 3) throw e;      console.error(`node ${d.behind} slots behind, waiting ${d.waitMs} ms (try ${attempt} of 3)`);      await sleep(d.waitMs);    }  }}console.log("synthetic -32005, 166 slots at 200 ms:", classify({ context: { __code: -32005, numSlotsBehind: 166 } }, 200));console.log("synthetic other error:", classify(new Error("bad request"), 200));const samples = await Promise.allSettled([guarded(() => rpc.getRecentPerformanceSamples(10).send())]);const [sample] = samples;if (sample.status === "fulfilled") {  const secs = sample.value.reduce((n, s) => n + Number(s.samplePeriodSecs), 0);  const slots = sample.value.reduce((n, s) => n + Number(s.numSlots), 0);  if (slots > 0) {    slotMs = (secs * 1000) / slots;    console.log(`measured slot time ${slotMs.toFixed(0)} ms over ${slots} slots`);  }} else {  console.error(`getRecentPerformanceSamples failed: ${sample.reason}`);}const [health, processed, finalized] = await Promise.allSettled([  guarded(() => rpc.getHealth().send()),  guarded(() => rpc.getSlot({ commitment: "processed" }).send()),  guarded(() => rpc.getSlot({ commitment: "finalized" }).send()),]);if (health.status === "fulfilled") console.log(`getHealth: ${health.value}`);else console.error(`getHealth failed: ${health.reason}`, classify(health.reason, slotMs));if (processed.status === "fulfilled" && finalized.status === "fulfilled") {  console.log(`slots processed=${processed.value} finalized=${finalized.value} spread=${processed.value - finalized.value}`);} else {  for (const r of [processed, finalized]) if (r.status === "rejected") console.error(`getSlot failed: ${r.reason}`);}

run: node main.ts

classify is the whole policy. It reads the code and numSlotsBehind from any thrown value and returns a decision: wait this many milliseconds, or fail. A thrown value with another code returns fail, so a bad request or a missing method never gets retried. guarded wraps a call, asks classify after each error and sleeps for the returned time, for at most three tries.

The file first runs classify on a made-up error with a count of 166, which shows the decision without needing a lagging node. Then it makes four real calls: getRecentPerformanceSamples first to measure the slot time, then getHealth and getSlot at processed and at finalized together. Each result is settled on its own, so one failing call prints its error and the rest still print. getSlot carries an explicit commitment on both calls, since @solana/kit fills in confirmed when a call leaves it out.

getHealth and getSlot are cheap cached reads at 1 cell each, with 5 requests per second on Free, so the three calls sent together fit in one second there.

05

Reading the output

The first two lines come from the made-up errors. At 200 ms per slot the count of 166 asks for 33,200 ms, and the handler caps that at 30,000. The second line shows an ordinary error getting fail.

The third line prints the slot time measured from the samples. It will sit near 200 ms. If it drifts, the wait the handler computes drifts with it, which is the reason to measure it on each run.

The live lines follow. On a healthy node getHealth prints ok, and the slot line shows processed and finalized with their difference. Since Alpenglow, finalized trails processed by 0 or 1 slots. Two separate reads can also show the pair equal or in the wrong order by one slot, because they answer at different instants, so a spread of -1 is not an error. A spread of dozens of slots on one endpoint means finalization has stalled. A node behind the cluster shows only against getHealth or another endpoint's slot.

$On a healthy node you will not see a wait on a live call. The synthetic lines are the only place the wait path runs, and the file labels them that way.
06

Where it ends

The file reacts to what a node says now. It cannot tell you why the node fell behind or when it will catch up, and a wait sized from the count is a first guess that the next answer corrects. A node that is not catching up returns a larger count on each try. After the third try guarded rethrows and the call's promise rejects. The file prints that call's error and carries on with the other results, and that error is the point to alert a person or send through another node.

The file is read-only: it signs nothing and sends nothing. A resend loop needs your blockhash, your lastValidBlockHeight and your status checks, and those belong to your sending code.

A status read from a lagging node can itself be old. A getSignatureStatuses answer of null from a node that is behind does not prove the transaction never landed, so treat expiry of the blockhash plus a null answer from a node with no lag as the condition for signing again.

The file also says nothing about how often any endpoint returns -32005. Count it on your own traffic before you decide how much of a wait your caller can absorb.

07

When it goes wrong

what goes wrongwhat to do
A send is signed again with a new blockhash right after -32005.Resend the same bytes while the old blockhash is valid. Sign anew only after getBlockHeight is past the old lastValidBlockHeight and getSignatureStatuses shows the old signature never landed. Two different signed transactions can both land.
The wait ends and the next call returns -32005 with a larger count.The node is not catching up. After three tries stop, report the count, and send through another node if your setup has one.
The wait comes out at about half a second.The error arrived without numSlotsBehind, or with a count of 2 slots or fewer. The handler floors the wait at 500 ms in both cases, and a log line reading node 0 slots behind shows that the count was missing.
A read after your own write returns the old state although getHealth says ok.getHealth says ok while the node is within its threshold, which can still be a few slots short of your write. Pass minContextSlot set to the slot of your write, and wait on -32016 the same way as on -32005.
Every call returns the same error immediately and is never retried.The code is not -32005, so classify returned fail. Read the error: a bad key, a missing method or a malformed request will not improve with a wait.
The file stops with Set CARBIUM_KEY to your Carbium API key.Export CARBIUM_KEY in the shell that runs node main.ts. The file reads it from the environment and never prints it.
08

Questions

Is it safe to resend a transaction after -32005?

Yes while its blockhash is valid, because the same signed bytes carry the same signature and the chain executes a signature once. Past the blockhash lifetime, confirm the old signature never landed before you sign a new transaction.

How long should I wait for numSlotsBehind of 166?

About 33 seconds of cluster time at 200 ms per slot, which the handler caps at 30 seconds. Treat it as a first pause: the next call returns a fresh count that tells you more.

Does -32005 mean my transaction failed?

No. The error describes the node that answered, and it comes back for any call that node refuses while it lags. Your transaction has no verdict until you read its signature status.

Should I use getHealth before every call?

No. Handle the error when a call returns it. A health check before each call doubles your calls, and the answer can change before the second call arrives.