services
Get a key

library / Integrations / Document and key-value stores / I0079

Memcached RPC response cache

A get and set wrapper that answers repeat Solana RPC reads from Memcached, with a key built from method and hashed params, a TTL per method, and a short list of calls that always go upstream, so repeat reads stop counting against the rate limit.

By Carbium · Document and key-value stores · I0079 · updated 2026-11-22

01

What triggers the 429

A 429 on a repeated read means the same question is being asked faster than the key's rate allows. An app that polls getSlot on every render, a dashboard that re-reads one balance for each visitor, and a worker that asks for a mint's supply on every job all send identical calls, and each one is charged again.

On Carbium a call over its rate waits once and is served if its cells refill within 1 s. Past that it gets a 429 with a retry-after hint. Limits are per account, so every key on the account draws on one budget, and a second service sharing it can push yours over.

Cells are the admission charge per call, and the classes differ. Cheap cached reads such as `getSlot` cost 1 cell, while account reads such as `getAccountInfo` cost 10, so the same repeat rate sits closer to the limit on the second kind. On a Free key getAccountInfo runs at 0.5 req/s.

A cache in front of the client drops the calls whose answer has not changed since the last one, so they never reach the limit.

02

Key format

Memcached keys are at most 250 bytes and cannot hold spaces or control characters. Params are JSON with addresses and config objects, so a raw key breaks both rules quickly. Hash them. The key is rpc:<method>:<sha256 of the JSON params>, which is the prefix, the method name and 64 hex characters, about 100 bytes.

  • Put everything that changes the answer into the hashed array: addresses, commitment, minContextSlot, encoding and dataSlice.
  • Put the commitment in explicitly. @solana/kit 8.6.0 fills in confirmed when a call leaves it out, while the JSON-RPC server's own default is finalized. The code passes confirmed in every call and in the hash, so a finalized read of the same address gets its own key.
  • Keep the order of params fixed. JSON.stringify follows insertion order, so build config objects the same way at every call site, or sort their keys before hashing.
03

TTL per method

Set the TTL to the age at which a stale answer starts to mislead the caller. These values are starting points for a read-only app. Tune them against how your callers use the number.

MethodTTLWhy
getSlot1 sA slot is about 200 ms since Alpenglow, so 1 s serves an answer up to five slots old.
getBalance5 sThe value moves only when a transaction touches the wallet. 5 s suits a display.
getTokenSupply30 sSupply moves on a mint or a burn.
getMinimumBalanceForRentExemption1 hThe answer depends on the data length and the rent rate.
getBlockTime for a finalized slot1 dayA finalized slot's time never changes.
04

What to leave uncached

  • getLatestBlockhash for a transaction you will sign. A blockhash has a lastValidBlockHeight, and a transaction signed with a cached one near that height never lands. Read it fresh and sign right after.
  • getSignatureStatuses while you wait for a confirmation. A cached null or processed holds your loop on old state for the whole TTL. A status that reads finalized never changes and can be stored.
  • Any read with minContextSlot. Its job is to prove the node had reached a slot, and a hit returns the first answer however far the chain has moved since. Consistent reads with minContextSlot shows the read.
  • A null from getAccountInfo for an account that may be about to exist. Cached for 30 s, it hides an account created a second later.
  • Every failed call. The code stores a value only after the call succeeds, so a 429 body never becomes an answer.
  • Write methods such as sendTransaction.
05

The wrapper

Install it with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required, and CARBIUM_RPC_URL defaults to the RPC endpoint. Pass a mint and a wallet after the file name.

The store is a Map with the two calls a Memcached client gives you, get(key) and set(key, value, ttlSeconds). To use a real server, replace the cache object with your client's two methods and map a missing key to undefined. Values are strings: each call stores the one number it returns.

main.ts
// I0079 · Memcached RPC response cache// https://carbium.sh/library/integrate/memcached-rpc-response-cache// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { createHash } from "node:crypto";const key = process.env.CARBIUM_KEY;const [mint, wallet] = process.argv.slice(2);if (!key || !mint || !wallet) {  console.error("Set CARBIUM_KEY and pass a mint and a wallet: node main.ts <mint> <wallet>");  process.exit(1);}const apiKey: string = key;// The Memcached shape: get(key) and set(key, value, ttlSeconds), values as strings. A Map stands in for the server.const store = new Map<string, { v: string; exp: number }>();const cache = {  async get(k: string): Promise<string | undefined> {    const e = store.get(k);    if (!e || e.exp < Date.now()) return void store.delete(k);    return e.v;  },  async set(k: string, v: string, ttl: number) {    store.set(k, { v, exp: Date.now() + ttl * 1000 });  },};const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey } }),);const stats = { calls: 0, hits: 0, misses: 0 };// Key: rpc:<method>:<sha256 of the params>, about 100 bytes, no spaces. The commitment sits inside the params.async function cached(method: string, params: unknown[], ttl: number, fresh: () => Promise<string>) {  stats.calls++;  const k = `rpc:${method}:${createHash("sha256").update(JSON.stringify(params)).digest("hex")}`;  const hit = await cache.get(k);  if (hit !== undefined) {    stats.hits++;    return `${hit} (hit)`;  }  stats.misses++;  const v = await fresh(); // a failed call throws here, so nothing is stored  if (Buffer.byteLength(v) <= 1_000_000) await cache.set(k, v, ttl); // Memcached refuses items near 1 MB  return `${v} (miss)`;}const confirmed = { commitment: "confirmed" } as const;type Call = [method: string, params: unknown[], ttl: number, fresh: () => Promise<string>];const calls: Call[] = [  ["getSlot", [confirmed], 1, async () => String(await rpc.getSlot(confirmed).send())],  ["getBalance", [wallet, confirmed], 5, async () => String((await rpc.getBalance(address(wallet), confirmed).send()).value)],  ["getTokenSupply", [mint, confirmed], 30, async () => (await rpc.getTokenSupply(address(mint), confirmed).send()).value.uiAmountString],];for (let round = 1; round <= 3; round++) {  const out = await Promise.allSettled(calls.map(([m, p, t, f]) => cached(m, p, t, f)));  out.forEach((r, i) => {    const text = r.status === "fulfilled" ? r.value : `failed: ${r.reason instanceof Error ? r.reason.message : r.reason}`;    console.log(`round ${round} ${calls[i][0]}: ${text}`);  });}console.log(`calls ${stats.calls}, hits ${stats.hits}, misses ${stats.misses}, upstream calls avoided ${stats.hits}`);

run: node main.ts <mint> <wallet>

Run it with node main.ts <mint> <wallet>. It makes three rounds of three calls: getSlot, getBalance for the wallet and getTokenSupply for the mint. The first round prints three (miss) lines and each later round three (hit) lines. The last line gives calls, hits, misses and upstream calls avoided, which is nine, six, three and six when every call succeeds.

A call that fails prints failed and its reason, stores nothing, and the round carries on. The rounds run back to back, so on a slow link a getSlot read can pass its 1 s TTL and turn into a miss.

06

Where it ends

  • The first request still pays. A cold key, an expired key and a restarted Memcached all send the call upstream, and a burst of identical requests at that moment all miss together. Hold one in-flight call per key (the code does not) or warm the keys on start.
  • A hit is as old as its TTL. A balance cached for 5 s can show the value from before a transfer that has already confirmed. After a user's own transaction confirms, delete that key or read once without the cache.
  • A value over the item limit is refused. Memcached's default is 1 MB, header included, so large getAccountInfo or getBlock answers will not store. The code skips the set above 1,000,000 bytes.
  • Memcached evicts the least recently used items when it is full, so a key can vanish before its TTL. That costs one call.
  • Memcached has no login by default. Keep it on a private interface, and keep answers that belong to one user out of a cache that other services share.
  • It caches reads for one app. When an app reads many distinct addresses, most calls miss and still count against the account's rate. Redis live balance cache takes the opposite route, following wallets and refreshing on change.
07

When it goes wrong

what goes wrongwhat to do
The hit count stays at zero and every call still goes upstream.The key changes between calls. Look for a config object built in a different order, a timestamp or slot inside the params, or a minContextSlot that keeps moving. Log the JSON before the hash and compare two calls.
Memcached rejects a set with a key error.The key has a space or a control character, or it is over 250 bytes. Hash the params, keep the method name short, and never put an address list into the key itself.
A transaction signed with a cached blockhash is never confirmed.Take getLatestBlockhash off the cached list, read it fresh and sign right after. A blockhash is refused once the chain passes its lastValidBlockHeight.
The cache shows a balance from before a transfer the user just made.Delete the wallet's key once the user's own transaction confirms, or give balances a shorter TTL.
A 429 still arrives right after a restart or a deploy.Many keys were empty at once and refilled together. Add a few seconds of random jitter to each TTL and warm the keys one after another. A 429 carries a retry-after hint, so wait that long before the retry.
getAccountInfo returns null for an account that exists.A null was cached before the account was created. Leave null answers uncached, or give them a few seconds.
08

Questions

Does a cache raise my rate limit?

No. It lowers the calls you send. The limit stays per account, and a hit costs no cells because it never reaches Carbium.

Memcached or process memory?

Process memory is enough for one process. Memcached pays off when several processes or hosts ask the same questions, since they then share one answer per TTL.

Can I cache the calls inside a batch?

Yes. Keep each call under its own key and send only the misses as a batch. A batch takes up to 100 calls.

Which commitment goes in the key?

The one the call uses. @solana/kit 8.6.0 fills in confirmed and the JSON-RPC server defaults to finalized, so two clients can send the same bare params and mean different reads. Put the commitment in the params.