services
Get a key

library / Integrations / I0032

AWS Lambda getBalance fix

A Lambda handler that reads a SOL balance through Carbium and returns a plain result for every failure, with the cause chain of fetch failed written out, so you can tell a missing route, a bad key and a rate limit apart.

By Carbium · Serverless and edge · I0032 · updated 2026-11-22

01

What fetch failed means

TypeError: fetch failed is the message Node's built-in fetch throws when no HTTP response came back at all. It names no cause. The cause sits on the error's cause property as a second error with a code such as ENOTFOUND, ETIMEDOUT, ECONNRESET or UND_ERR_CONNECT_TIMEOUT. A log line that prints only the outer error hides the one piece of information you need.

A response with an error status is a different case. fetch returns it, and @solana/kit turns a non-2xx answer into an HTTP transport error that carries the status code and the headers. The file below keeps the cases apart. An HTTP error is reported with its status and any retry-after, a JSON-RPC error answered with HTTP 200 is reported with its message, and anything else is reported as a network failure with the whole cause chain written out.

02

Why it happens inside Lambda

  • The function sits in a VPC. A function attached to private subnets has no route to the internet unless the subnet routes through a NAT gateway. The call hangs until the file's 5 second abort fires, and the result names a TimeoutError. A security group or network ACL that blocks outbound 443 gives the same result.
  • The name does not resolve. ENOTFOUND in the cause points at DNS: a custom VPC resolver, or a typo in the URL held in an environment variable.
  • The runtime is old. fetch is a global from Node 18 on, so a function still on Node 16 has none. Use a current Node runtime.
  • The function times out first. Lambda's default timeout is 3 seconds, and a cold start plus a TLS handshake can use much of it. The platform ends the invocation and logs a timeout, and no fetch error appears at all.
  • A frozen socket. Lambda freezes the process between invocations, and the far end can close a kept connection during the freeze. The next call fails with ECONNRESET or, in Node's fetch, UND_ERR_SOCKET, and a retry on a fresh connection works.
03

The file

main.ts exports balance, which makes the getBalance call and returns a plain object for every outcome, and handler, the Lambda entry that takes { "address": "<pubkey>" }. Lambda loads JavaScript, so bundle it first, for example esbuild main.ts --bundle --platform=node --format=esm --outfile=index.mjs, and set the handler to index.handler. Install @solana/[email protected]. For a local check, export CARBIUM_KEY and pass addresses on the command line. CARBIUM_RPC_URL is an optional variable that replaces the endpoint.

main.ts
// I0032 · AWS Lambda getBalance fix// https://carbium.sh/library/integrate/aws-lambda-getbalance-fix// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isAddress,  isSolanaError,  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,} from "@solana/kit";const connect = (key: string) =>  createSolanaRpcFromTransport(    createDefaultRpcTransport({      url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",      headers: { "x-api-key": key },    }),  );let rpc: ReturnType<typeof connect> | undefined; // outside the handler: warm invocations reuse it// "fetch failed" hides its reason one level down: walk the cause chain.function describe(e: unknown): string {  const parts: string[] = [];  let c = e as { code?: unknown; name?: string; message?: string; cause?: unknown } | undefined;  while (c && parts.length < 4) {    parts.push(typeof c.code === "string" ? c.code : `${c.name}: ${c.message}`);    c = c.cause as typeof c;  }  return parts.join(" <- ");}export async function balance(addr: string) {  const key = process.env.CARBIUM_KEY;  if (!key)    return { ok: false, address: addr, kind: "config", detail: "Set CARBIUM_KEY in the function configuration." };  rpc ??= connect(key);  try {    // commitment left out: kit 8.6.0 sends confirmed    const { context, value } = await rpc      .getBalance(address(addr))      .send({ abortSignal: AbortSignal.timeout(5_000) });    return { ok: true, address: addr, lamports: value.toString(), slot: context.slot.toString() };  } catch (e) {    if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR))      return {        ok: false,        address: addr,        kind: "http",        status: e.context.statusCode,        retryAfter: e.context.headers.get("retry-after"),      };    // any other Solana error is a JSON-RPC error answered with HTTP 200    if (isSolanaError(e)) return { ok: false, address: addr, kind: "rpc", detail: e.message };    return { ok: false, address: addr, kind: "network", detail: describe(e) };  }}// Lambda entry: invoke with { "address": "<pubkey>" }.export const handler = async (event: { address?: string }) =>  event.address && isAddress(event.address)    ? balance(event.address)    : { ok: false, kind: "input", detail: "send { address: <pubkey> }" };// Local check only: node main.ts <address> [<address> ...]if (globalThis.process?.argv[1]?.endsWith("main.ts")) {  if (!process.env.CARBIUM_KEY) {    console.error("Set CARBIUM_KEY.");    process.exit(1);  }  const results = await Promise.all(process.argv.slice(2).map((a) => handler({ address: a })));  console.log(JSON.stringify(results, null, 1));}

run: node main.ts So11111111111111111111111111111111111111112 11111111111111111111111111111111

Lamports are a bigint in @solana/kit, and JSON.stringify refuses a bigint, so the file writes them as a decimal string. The client is built once outside the handler, so warm invocations reuse its connection. The call has its own 5 second abort, which fires before a Lambda timeout of 10 seconds or more and leaves a readable error in the log.

04

Reading the result

ResultWhat it meansNext step
ok: trueThe call reached Carbium and lamports holds the balance.Nothing to fix.
kind: networkNo HTTP answer came back. detail lists the error and its causes.Read detail: TimeoutError: The operation was aborted due to timeout points to routing, ENOTFOUND to DNS.
kind: rpcCarbium answered with HTTP 200 and a JSON-RPC error. detail holds the error message.Read the message and correct the request.
kind: http, status 401The network path works and the key is unknown.Attach the whole key.
kind: http, status 429The account's rate is spent.Wait for retryAfter.
kind: configCARBIUM_KEY is not set in the function configuration.Set it and deploy again.
kind: inputThe event held no valid address.Fix the caller.

The split between network and http finds the broken half quickly. Any HTTP status, even a 401, proves the function reached Carbium, so the route and DNS are fine and only the request needs work.

05

The Carbium side

The RPC endpoint is https://services.carbium.sh and the key travels in the x-api-key header. Put both in the function's environment configuration, or read the key from a secrets store at start-up. The file never logs either one. An unknown key gets a 401 UNKNOWN_KEY, and the fix is to attach the whole key.

Carbium keeps connections open for 600 s and asks callers to reuse one client, which is why the client sits outside the handler.

The call leaves commitment out, and @solana/kit 8.6.0 sends confirmed when a call does that, while the JSON-RPC server's own default is finalized. The slot in the answer is the slot the read reflects. For the first call from a plain script, see First Solana RPC API call.

A burst of concurrent invocations can reach the rate limit. Limits are per account, so every key on the account shares one budget. A call over its rate gets a 429 with a retry-after hint, which the file returns as retryAfter. Cap the function's reserved concurrency or queue the work if invocations arrive together. To read many accounts in one call, see Edge worker RPC reads.

06

Where it ends

  • Invoke the bundle once in your own account and VPC before you rely on it.
  • No code change fixes a missing route. A function with no path to the internet needs a NAT gateway or a place outside the VPC.
  • The file does not retry. A network result with ECONNRESET or UND_ERR_SOCKET is safe to retry once in your own code.
  • getBalance returns the lamports of one address. A token balance lives in a token account and needs a different read.
  • Nothing is cached, so every invocation spends a call. A JSON-RPC batch carries up to 100 calls, and this file sends one.
07

When it goes wrong

what goes wrongwhat to do
The result shows kind: network with TimeoutError: The operation was aborted due to timeout.The function has no route out. Add a NAT gateway to the private subnet's route table, or take the function out of the VPC, and allow outbound 443.
ENOTFOUND in the cause chain.The host name did not resolve. Check CARBIUM_RPC_URL for typos and confirm the VPC resolver answers public names.
ECONNRESET or UND_ERR_SOCKET on the first call after the function sat idle.A kept socket was closed during the freeze. Retry once, and the second call opens a new connection.
The invocation ends with Task timed out after 3.00 seconds and no error from the file.The default function timeout is 3 seconds. Raise it to 10 seconds or more, so the file's own 5 second abort fires first and names the cause.
The result shows kind: http with status 401.Carbium does not know the key, which is the 401 error for an unknown key. Send the whole key in x-api-key, with no quotes or trailing space copied from the console.
The result shows kind: http with status 429 and a retryAfter value.The account's rate is spent, often by other invocations or keys on the same account. Wait for the hint, lower the function's concurrency, or move to a plan with a higher rate.
08

Questions

Why does the same script work on my laptop and fail on Lambda?

Your laptop has a route to the internet, and a function in a VPC may not. The error in detail tells which: a TimeoutError points to routing and ENOTFOUND to DNS.

Do I need a fetch polyfill on Lambda?

No. fetch is a global from Node 18 on. A function on an older runtime should move to a current one.

Should I build the client inside the handler?

Build it once outside, as the file does. Warm invocations then reuse the open connection instead of paying a new TLS handshake.

Can I read several balances in one invocation?

Call balance for each address. It returns a result for every outcome instead of throwing, so Promise.all works.