---
id: I0020
title: "Kubernetes reader service"
url: https://carbium.sh/library/integrate/kubernetes-reader-service
collection: Integrations
category: Infrastructure and ops
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Kubernetes reader service

A small Node HTTP service for a Kubernetes pod: a cached account read backed by Carbium RPC, a liveness route that never calls out, a readiness route tied to a slot and health check, and a SIGTERM drain.

## What the pod serves

The service is one Node file with a single dependency, `@solana/kit`. It listens on `PORT` (default 8080) and answers three routes. Everything it learns about Solana comes from [Carbium's RPC](https://carbium.sh/docs#endpoints) at `https://services.carbium.sh`, and the one secret it needs is the key, read from `CARBIUM_KEY`.

| Route | Answers | Calls Carbium? |
|---|---|---|
| `/livez` | 200 while the process runs | No |
| `/readyz` | 200 when the last check passed less than 15 seconds ago, 503 otherwise or while draining | No, it reads the result of the background check |
| `/account/<address>` | JSON with slot, lamports, owner and data length | Yes, one `getAccountInfo`, cached 2 seconds per address |

A background check runs every 5 seconds and reads `getSlot` and `getHealth` together. Both must answer for the pod to report ready. The probe routes answer from the result of that check and never wait on Carbium themselves, so a probe stays inside the kubelet's default timeout of one second whatever the upstream is doing.

## The Solana side: confirmed reads of one account

The account route calls `getAccountInfo` with base64 encoding at `confirmed` commitment, and the file names the level on every call.

A missing account is a valid answer: the route returns 200 with `exists: false` and null fields. A found account returns its lamports, its owner and the byte length of its data, and the data itself stays out of the response. The route reads one named account. A wallet can own several token accounts for one mint, so a per-wallet token view needs `getTokenAccountsByOwner` and a route of its own.

`getHealth` answers `ok` when the node judges itself healthy and returns an error otherwise, so an unhealthy node fails the check the same way an unreachable one does. When every failed call is a 429, the check leaves the last answer in place and logs `check hit a 429; keeping the last answer`. If the 429s go on, the answer ages past 15 seconds and `/readyz` turns 503.

## Probes, drain and the pod spec

| Setting | Value | Reason |
|---|---|---|
| Liveness probe | `httpGet` on `/livez`, every 10 s | Restarts a process that hangs. It never calls Carbium, so a rate limit or an upstream error cannot restart the pods. |
| Readiness probe | `httpGet` on `/readyz`, every 5 s, 3 failures | Takes the pod out of the Service while the check is down or the pod is draining. |
| `terminationGracePeriodSeconds` | the default 30 | Must stay above the 5 second drain. |
| `CARBIUM_KEY` | `secretKeyRef` into a Secret | Keeps the key out of the image and the manifest. |

On SIGTERM the service marks itself draining at once, so `/readyz` answers 503, and it keeps the listener open for 5 seconds before it closes and exits 0. Kubernetes removes the pod from the endpoints and sends SIGTERM at about the same time, so the wait lets the removal reach the proxies before the port closes.

Create the Secret from a literal so the value carries no trailing newline, and map it with `secretKeyRef`. A running pod keeps the value it started with, so a rotated key needs a rollout restart.

## Replicas against the shared budget

Every key on an account shares [one budget](https://carbium.sh/docs#limits), so ten replicas draw from the pool one replica would. `getSlot` and `getHealth` are cached reads at 1 cell each, and a pod makes two of them every 5 seconds: 24 cells a minute, or 0.4 req/s. Free allows [5 req/s](https://carbium.sh/docs#rpc) for this class, so twelve pods probing use 4.8 of it before any traffic arrives. Dev, Business and Pro allow 30, 100 and 500.

Account reads cost 10 cells each, at 0.5, 15, 50 and 400 req/s on Free, Dev, Business and Pro. The cache keeps an answer for an address 2 seconds, and simultaneous requests for it share one call. A pod therefore sends at most one `getAccountInfo` per address every 2 seconds, which is the whole 0.5 req/s of a Free account for a single address. The cache holds up to 1,000 addresses and empties itself when full. A cached answer can be up to 2 seconds older than the confirmed read behind it.

When Carbium answers 429, the account route passes the status and the `retry-after` hint to its caller, so a client or an ingress retry policy sees what Carbium sent. [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) covers alerting on them. The file builds one client at start and every request uses it.

## Build, run and try it

Install the dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load, so the image runs `node main.ts` from a Node 24 base with no build step.

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

```ts
// I0020 · Kubernetes reader service
// https://carbium.sh/library/integrate/kubernetes-reader-service
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createServer } from "node:http";
import { createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, type Address } 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 rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const commitment = "confirmed";
const CHECK_MS = 5_000, STALE_MS = 15_000, CACHE_MS = 2_000, DRAIN_MS = 5_000; // check cadence, readiness lifetime, cache, SIGTERM wait
const deadline = () => AbortSignal.timeout(4_000);

const http = (e: unknown) => (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) ? e.context : null);
const limited = (e: unknown) => http(e)?.statusCode === 429;
const why = (e: unknown) => (http(e) ? `HTTP ${http(e)?.statusCode}` : e instanceof Error ? e.message : String(e));

let probe = { ok: false, slot: "0", at: 0, why: "starting" };
let draining = false, lastLine = "";
async function check() {
  const [slot, health] = await Promise.allSettled([rpc.getSlot({ commitment }).send({ abortSignal: deadline() }), rpc.getHealth().send({ abortSignal: deadline() })]);
  const errors = [slot, health].flatMap((r) => (r.status === "rejected" ? [r.reason as unknown] : []));
  if (slot.status === "fulfilled" && health.status === "fulfilled") probe = { ok: true, slot: slot.value.toString(), at: Date.now(), why: "" };
  else if (errors.every(limited)) return void console.error("check hit a 429; keeping the last answer");
  else probe = { ...probe, ok: false, why: [...new Set(errors.map(why))].join("; ") };
  const line = `readiness ${probe.ok ? "up" : "down"}${probe.why ? `: ${probe.why}` : ""}`;
  if (line !== lastLine) console.log(`${line} (slot ${probe.slot})`);
  lastLine = line;
}

const cache = new Map<string, { at: number; body: Promise<string> }>();
function read(addr: Address): Promise<string> {
  const hit = cache.get(addr);
  if (hit && Date.now() - hit.at < CACHE_MS) return hit.body; // simultaneous requests share one call
  if (cache.size >= 1_000) cache.clear();
  const body = rpc.getAccountInfo(addr, { commitment, encoding: "base64" }).send({ abortSignal: deadline() }).then(({ context, value }) =>
    JSON.stringify({ address: addr, slot: context.slot.toString(), exists: value !== null, lamports: value?.lamports.toString() ?? null,
      owner: value?.owner ?? null, bytes: value ? Buffer.from(value.data[0], "base64").length : null }));
  cache.set(addr, { at: Date.now(), body });
  body.catch(() => cache.delete(addr)); // a failed read is not cached
  return body;
}

const server = createServer(async (req, res) => {
  const reply = (status: number, body: string) => { res.writeHead(status, { "content-type": "application/json" }); res.end(body); };
  const [, route, arg] = (req.url ?? "/").split("?")[0].split("/");
  if (route === "livez") return reply(200, '{"live":true}');
  if (route === "readyz") {
    const ready = !draining && probe.ok && Date.now() - probe.at < STALE_MS;
    return reply(ready ? 200 : 503, JSON.stringify({ ready, slot: probe.slot, why: draining ? "draining" : probe.why }));
  }
  if (route !== "account") return reply(404, '{"error":"not found"}');
  if (!arg || !isAddress(arg)) return reply(400, '{"error":"not a base58 address"}');
  try {
    reply(200, await read(arg));
  } catch (e) {
    const wait = limited(e) ? Number(http(e)?.headers.get("retry-after")) || 1 : 0;
    if (wait) res.setHeader("retry-after", String(wait));
    reply(wait ? 429 : 502, JSON.stringify({ error: why(e) }));
  }
});

await check(); // the first answer exists before the first probe
server.listen(Number(process.env.PORT ?? 8080), () => {
  const a = server.address();
  console.log(`listening on port ${typeof a === "object" && a ? a.port : a}`);
});
setInterval(() => void check(), CHECK_MS);
process.on("SIGTERM", () => {
  draining = true; // /readyz answers 503 now; the listener stays open while the endpoints catch up
  setTimeout(() => server.close(() => process.exit(0)), DRAIN_MS);
});
const first = process.argv[2]; // optional: read one account, print it and exit
if (first) {
  if (!isAddress(first)) { console.error("Not a base58 address."); process.exit(1); }
  try { console.log(await read(first)); process.exit(0); } catch (e) { console.error(`read failed: ${why(e)}`); process.exit(1); }
}
```

| Variable | Default | Meaning |
|---|---|---|
| `CARBIUM_KEY` | required | The API key. The process exits with a message when it is unset. |
| `CARBIUM_RPC_URL` | `https://services.carbium.sh` | The RPC endpoint. |
| `PORT` | 8080 | The listen port. 0 picks a free one. |

To try it locally, export `CARBIUM_KEY` and run `node main.ts` with one address as the first argument. The log prints the readiness state, the port and that account's JSON, and the process then exits with 0, or with 1 when the read fails. Run it with no argument to keep it serving, then call `/readyz` and `/account/<address>` with curl on the port the log prints. The four timings sit as constants at the top of the file.

## Where it ends

- It reads one account per call. There is no list, no token holdings view and no write, and it signs nothing.
- Each pod keeps its own cache and runs its own check. Replicas add their calls together against one account budget, and no shared store joins them.
- Readiness reflects Carbium and the account's rate. When the budget is spent, every pod ages to not ready at once and the Service has no endpoints.
- A check every 5 seconds sees the state at that moment. A dip that begins and ends between two checks goes unseen.
- The service has no authentication of its own. Anyone who can reach `/account` spends your budget, so keep it behind a NetworkPolicy or an authenticating ingress.
- It exposes no metrics endpoint, and the log lines are the only trace.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The pod sits in CreateContainerConfigError, or restarts and logs `Set CARBIUM_KEY to your Carbium API key.` | The `secretKeyRef` names a Secret or a key that does not exist, or the variable is empty. Compare the names in `kubectl describe pod` with the Secret, then recreate the Secret with the whole key as its value. |
| `/readyz` stays at 503 and the log shows `readiness down: HTTP 401 (slot 0)`. | Carbium [does not know the key](https://carbium.sh/docs#errors). Attach the whole key: check that the Secret holds it complete and with no trailing newline, and that nothing else sets `CARBIUM_RPC_URL` to a different endpoint. |
| Every pod goes not ready at about the same time, and the log shows `check hit a 429; keeping the last answer` first. | The account budget is spent, usually by traffic on other keys or by too many replicas probing. Raise `CHECK_MS`, run fewer replicas, or move to a plan with a higher rate. |
| Pods restart in a loop whenever Carbium rate limits or answers an error. | The liveness probe points at `/readyz`. Point it at `/livez`, which never calls out. A restart cannot repair an upstream problem. |
| A rollout drops a few requests. | The Service still sent traffic after the listener closed. Raise `DRAIN_MS` and keep `terminationGracePeriodSeconds` above it. Its default is 30 seconds. |

## Questions

### Why does the liveness probe skip Carbium?

A restart cannot repair a rate limit or an upstream error, and it would restart every pod at once. Readiness already takes a pod out of the Service while the check is down and puts it back when the check passes.

### How many replicas fit on a Free account?

Two pods use 0.8 of the 5 req/s for probes, and account reads share 0.5 req/s between them, so a Free account suits a small trial. More replicas need a plan with higher rates.

### Could the pods watch slots over WebSocket instead of polling?

They could, but each pod would hold a socket, and Free carries [5 sockets per account](https://carbium.sh/docs#websocket). Two cached reads every 5 seconds are simpler to probe and to reason about.

## Related

- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [Edge worker RPC reads](https://carbium.sh/library/integrate/edge-worker-rpc-reads) (Integrations, I0007)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [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#websocket](https://carbium.sh/docs#websocket)
