---
id: HS0098
title: "Transient RPC error retries"
url: https://carbium.sh/library/howsolana/transient-rpc-error-retries
collection: How to use Solana
category: Confirmation and retries
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Transient RPC error retries

One TypeScript file wraps read calls in a retry that sorts errors into transient and permanent, backs off with jitter, honours retry-after on a 429 and times out each try, so a dropped connection stops killing your getLatestBlockhash.

## What fetch failed means

`TypeError: fetch failed` comes from Node's built-in fetch, and it means the request never produced an HTTP response. The connection was refused, reset, timed out or could not be resolved. The real reason sits in the error's `cause`, usually a code such as `ECONNRESET`, `ETIMEDOUT` or `ENOTFOUND`. There is no status code and no body to read, so the response cannot tell you what to do next.

A message like `failed to get recent blockhash` is a wrapper some client library adds around that failure. The blockhash call is only the first one that happened to run. The same failure hits any call, and a single dropped socket in a long-lived process is enough to cause it. Reusing one client keeps connections open for a while, and an idle connection that the far side closed shows up as a reset on the next write.

Not every failure deserves a retry. Retrying a call that can never succeed only delays the error and spends rate budget. The table sorts the errors a read call meets.

| Error | Transient | What to do |
|---|---|---|
| `TypeError: fetch failed` | Yes | Wait with backoff and send again. Log the `cause` code. |
| Attempt timeout | Yes | Abort the try after a fixed time and send again. |
| HTTP 429 | Yes | Wait the `retry-after` seconds, then send again. |
| HTTP 500, 502, 503, 504 | Yes | Back off and send again. |
| HTTP 401 | No | The key is wrong or cut short. Fix it. |
| JSON-RPC -32601 | No | The method is not served or does not exist. Change the method. |
| JSON-RPC -32015 | No | `getTransaction` or `getBlock` met a v1 transaction. Pass `maxSupportedTransactionVersion: 1`. |

The rule behind the table: retry when the same bytes sent again could get a different answer, and surface the error when they could not.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on load. It needs no arguments. It reads three things at once, the latest blockhash, the slot and the block height, each wrapped in the same retry.

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

```ts
// HS0098 · Transient RPC error retries
// https://carbium.sh/library/howsolana/transient-rpc-error-retries
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import {
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  isSolanaError,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
} 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 } }),
);

const MAX_TRIES = 5;
const TRY_TIMEOUT_MS = 5000;

// Wait in ms before the next try, or undefined when the error should surface at once.
function retryDelay(e: unknown, n: number): number | undefined {
  const backoff = Math.random() * Math.min(4000, 250 * 2 ** n);
  if (e instanceof TypeError) return backoff; // fetch failed: no HTTP response at all
  if ((e as Error)?.name === "TimeoutError") return backoff;
  if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR)) {
    const { statusCode, headers } = e.context;
    if (statusCode === 429) return Math.min(10, Number(headers.get("retry-after")) || 1) * 1000;
    if (statusCode >= 500) return backoff;
  }
  return undefined; // 401, -32601, -32015 and the rest answer the same way every time
}

function why(e: unknown): string {
  const cause = (e as { cause?: { code?: string } })?.cause?.code;
  return cause ?? (e as Error)?.name ?? String(e);
}

async function withRetry<T>(name: string, call: (signal: AbortSignal) => Promise<T>): Promise<T> {
  for (let n = 0; ; n++) {
    try {
      return await call(AbortSignal.timeout(TRY_TIMEOUT_MS));
    } catch (e) {
      const wait = retryDelay(e, n);
      if (wait === undefined || n + 1 >= MAX_TRIES) throw e;
      console.error(`${name}: ${why(e)}; try ${n + 2} of ${MAX_TRIES} in ${Math.round(wait)} ms`);
      await sleep(wait);
    }
  }
}

const calls: Record<string, (signal: AbortSignal) => Promise<unknown>> = {
  getLatestBlockhash: (s) => rpc.getLatestBlockhash({ commitment: "confirmed" }).send({ abortSignal: s }),
  getSlot: (s) => rpc.getSlot({ commitment: "confirmed" }).send({ abortSignal: s }),
  getBlockHeight: (s) => rpc.getBlockHeight({ commitment: "confirmed" }).send({ abortSignal: s }),
};

const names = Object.keys(calls);
const results = await Promise.allSettled(names.map((name) => withRetry(name, calls[name])));
results.forEach((r, i) => {
  if (r.status === "fulfilled") {
    console.log(`${names[i]} ok ${JSON.stringify(r.value, (_k, v) => (typeof v === "bigint" ? String(v) : v))}`);
  } else {
    console.error(`${names[i]} failed after ${MAX_TRIES} tries or a permanent error: ${why(r.reason)}`);
  }
});
```

`retryDelay` is the whole policy. It returns a wait in milliseconds for a transient error and `undefined` for anything else, and `withRetry` rethrows on `undefined` or when the tries run out. Exponential backoff doubles a ceiling from 250 ms to 2 s over the four waits that five tries allow, and the wait is a random point under that ceiling. A 429 waits its `retry-after` seconds instead, capped at 10, or 1 s when the header is missing or not a number. The randomness matters when many workers lose a connection together: without it they all come back on the same tick and fail together again.

Each try gets its own `AbortSignal.timeout`. Without one, a hung socket holds the call open until the operating system gives up, which can take minutes. A timeout turns that hang into a `TimeoutError` that the policy treats as transient.

The three reads run under `Promise.allSettled`, so one call that exhausts its tries does not hide the other two. A failure is printed with its name and the run still prints what succeeded. `getLatestBlockhash` is sent at `confirmed`, which is also the level `@solana/kit` fills in when a call leaves commitment out.

## Reading the output

On a healthy connection each call answers on its first try and prints one line with its result. You see no retry lines at all, and that is the normal case. The retry path only shows when something went wrong, so a quiet run proves very little about it.

A retry line looks like `getSlot: ECONNRESET; try 2 of 5 in 118 ms`. It names the call, the cause code, the try that comes next and the wait. If a call fails on all five tries, the error line carries the last cause and the other two calls still print.

To watch the policy work, run the file while you break the path on purpose: point `CARBIUM_RPC_URL` at a closed local port and every call fails with `ECONNREFUSED` on each try, then reports a failure after the fifth. Set it back and the same file passes. The attempt count and the waits are the numbers to compare against your own traffic.

> A blockhash is good only for a limited stretch of blocks, set by its `lastValidBlockHeight`. If a retry loop stalls for long, fetch a fresh blockhash after it recovers and never reuse the one from before the stall.

## On Carbium

The RPC endpoint is `https://services.carbium.sh`, and the key rides in the `x-api-key` header on every call. A call over its [rate](https://carbium.sh/docs/limits) waits once on the server, and it is served if its cells refill within a second. Past that it gets a 429 with a retry-after hint, which the policy waits out before sending again.

Connections stay open for 600 seconds and TLS sessions resume, so one client reused across the process pays the handshake rarely. A closed connection still happens, and the retry covers it. A [method or key error](https://carbium.sh/docs/errors) such as `-32601` or a 401 answers the same way each time, so the policy surfaces it on the first try.

`getSlot` is a cheap cached read at 1 cell a call, at 5, 30, 100 and 500 requests per second on Free, Dev, Business and Pro. Limits belong to the account, so every key on it draws from one budget, and a retry loop that spins on many workers spends that shared budget. Backoff with jitter keeps retries from stacking on top of each other.

For a retry that follows a webhook, see [Webhook-to-RPC fetch retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries). For a payment check that stays safe when a send is repeated, see [Safe-retry payment check](https://carbium.sh/library/blockchainideas/safe-retry-payment-check).

## Where it ends

The file retries reads, and a read is safe to send twice. A transaction send is different. If a `sendTransaction` call fails with `fetch failed`, you do not know whether the request reached the node before the connection dropped, so a retry needs care. The same signed bytes sent again land at most once, because a signature lands only once. A transaction rebuilt with a fresh blockhash carries a new signature and can land a second time. Check the first signature's status before you build a new one, and keep sends out of this wrapper until you have that check.

Five tries and a 2 s ceiling suit a script. A service with a deadline per request should pass its own budget and stop retrying when the budget is spent, so it does not finish all five tries after the caller has given up.

A retry hides a failure that keeps coming back. A run of retry lines every hour points at a network path, a proxy or a connection pool that closes idle sockets, and it deserves a fix at the source. Count retries and alert on the rate.

The policy does not open a circuit. During a long outage every call spends all its tries before it fails. A breaker that stops sending for a while after repeated failures is the next step, and it belongs to the application that knows what a fallback looks like.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every try fails with ECONNREFUSED or ENOTFOUND. | The URL is wrong or unreachable from this machine. Check `CARBIUM_RPC_URL` and DNS before you raise the number of tries, because more tries cannot fix a bad address. |
| HTTP 429 keeps coming after the wait. | The loop sends faster than the plan's rate for that method. Slow the caller, spread the calls, or move to a plan with a higher rate. Waiting only helps with a short burst. |
| A call hangs for minutes before failing. | No timeout was set on the try. Pass an `AbortSignal.timeout` to each `send`, as the file does, so a hung socket turns into a `TimeoutError` that can be retried. |
| A 401 is retried and fails five times. | A 401 never reaches the transient list in this policy. If you added it, remove it: the key is unknown or cut short and needs the whole key. |
| All workers retry at the same moment after an outage. | The wait has no jitter. Use a random point under the ceiling, as the file does, so the workers spread out. |
| 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. |

## Questions

### Why does fetch failed give no status code?

The request ended before any response came back, so there is no status to read. Look at `error.cause` for the system code, such as `ECONNRESET`, which says how the connection ended.

### How many times should I retry?

Three to five tries with backoff covers most dropped connections. If a call still fails after that, the cause is likely not brief, and more tries only delay the error.

### Is it safe to retry getLatestBlockhash?

Yes, it is a read and sending it twice changes nothing. Take the blockhash from the try that succeeded and check its `lastValidBlockHeight` before you build a transaction on it.

### Can I retry sendTransaction the same way?

Not with this policy. A dropped connection leaves you unsure whether the node got the transaction, so check the signature's status before you sign a new one with a fresh blockhash.

## Related

- [Webhook-to-RPC fetch retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries) (How to use Solana, HS0041)
- [Safe-retry payment check](https://carbium.sh/library/blockchainideas/safe-retry-payment-check) (Blockchain ideas, BI0097)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
