library / Integrations / Document and key-value stores / I0167
Valkey latest blockhash cache
A small Node script keeps the latest blockhash in a Valkey key with a short TTL, checks its lastValidBlockHeight against the current block height on Carbium, and fetches a new blockhash only when the cached one has expired.
What the check compares
A blockhash expires by block height, so expiry is one comparison between two numbers.
getLatestBlockhash returns the blockhash and a lastValidBlockHeight, the last block height at which a transaction built on that blockhash can still land. getBlockHeight returns the current block height. When the current height is above lastValidBlockHeight, the blockhash has expired and a new one is needed before signing. For a loop that waits on block height, see the block-height confirmation loop.
The query names @solana/web3.js. The comparison is the same there, because the library exposes the same two values. This code uses @solana/kit 8.6.0 and sends every call through one transport, so the key goes in the x-api-key header on each call.
| Value | Read with | Meaning |
|---|---|---|
| Current block height | getBlockHeight at confirmed | The height the check is made at. |
| lastValidBlockHeight | getLatestBlockhash at confirmed | The last height a transaction on this blockhash can land. |
| Expired | Current height above lastValidBlockHeight | Fetch a new blockhash before signing. |
Both reads pass the commitment confirmed explicitly. The JSON-RPC server defaults to finalized, while @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out. Writing the value in each call keeps both reads on one level.
The Valkey key
Valkey holds one key, solana:latest-blockhash, with the JSON of the blockhash and its last valid height. Every process that reads the key gets the same blockhash until it expires, so a new expiry costs one getLatestBlockhash call and the requests in between read the key instead.
The key lives for 20 seconds. The TTL only bounds how long a copy sits. The height check still decides whether the copy can be used, because a blockhash read late in its window may already be close to its last height.
The helper speaks RESP over node:net, so the code needs no Redis client package. It sends AUTH only when the URL carries a password, and it closes each connection with QUIT after the commands it sent.
The check in code
Install the one dependency with npm install @solana/[email protected], and set "type": "module" in package.json. Node 24 strips the types on load. The script reads CARBIUM_KEY and exits with a message when it is unset. VALKEY_URL is optional: without it the script reads from Carbium only and says that the cache was skipped.
// I0167 · Valkey latest blockhash cache// https://carbium.sh/library/integrate/valkey-latest-blockhash-cache// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { connect } from "node:net";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium 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" as const;const CACHE_KEY = "solana:latest-blockhash";const TTL_SECONDS = "20"; // short on purpose: a copy never outlives the height testtype Latest = { blockhash: string; lastValidBlockHeight: string };// Minimal RESP client on node:net. Sends the commands, closes with QUIT, returns one entry per command.function valkey(url: URL, cmds: string[][]): Promise<(string | null)[]> { return new Promise((resolve, reject) => { const sock = connect(Number(url.port || 6379), url.hostname); const wire = cmds .map((args) => `*${args.length}\r\n` + args.map((a) => `$${Buffer.byteLength(a)}\r\n${a}\r\n`).join("")) .join(""); let data = ""; sock.setEncoding("utf8"); sock.on("connect", () => sock.write(wire + "*1\r\n$4\r\nQUIT\r\n")); sock.on("data", (d: string) => { data += d; }); sock.on("error", reject); sock.on("close", () => { const out: (string | null)[] = []; let at = 0; for (let i = 0; i < cmds.length; i++) { const eol = data.indexOf("\r\n", at); if (eol < 0) return reject(new Error("Valkey closed before it answered")); const line = data.slice(at, eol); if (line.startsWith("-")) return reject(new Error(`Valkey: ${line.slice(1)}`)); const n = line.startsWith("$") ? Number(line.slice(1)) : -1; out.push(n >= 0 ? data.slice(eol + 2, eol + 2 + n) : null); at = n >= 0 ? eol + 4 + n : eol + 2; } resolve(out); }); });}const vk = process.env.VALKEY_URL ? new URL(process.env.VALKEY_URL) : null;const auth: string[][] = vk?.password ? [vk.username ? ["AUTH", vk.username, vk.password] : ["AUTH", vk.password]] : [];const height = await rpc.getBlockHeight({ commitment }).send();let latest: Latest | null = null;if (vk) { const replies = await valkey(vk, [...auth, ["GET", CACHE_KEY]]); const cached = replies[replies.length - 1]; if (cached) latest = JSON.parse(cached) as Latest;}let source = "Valkey";if (!latest || height > BigInt(latest.lastValidBlockHeight)) { source = "Carbium"; const { value } = await rpc.getLatestBlockhash({ commitment }).send(); latest = { blockhash: value.blockhash, lastValidBlockHeight: value.lastValidBlockHeight.toString() }; if (vk) await valkey(vk, [...auth, ["SET", CACHE_KEY, JSON.stringify(latest), "EX", TTL_SECONDS]]);}const left = BigInt(latest.lastValidBlockHeight) - height;console.log(`block height ${height} at confirmed`);console.log(`blockhash ${latest.blockhash} from ${source}, valid through block height ${latest.lastValidBlockHeight}`);console.log(left >= BigInt(0) ? `${left} blocks left` : "expired: fetch a new blockhash before signing");if (!vk) console.log("VALKEY_URL not set: cache skipped, read from Carbium only.");
run: node main.ts
Set VALKEY_URL to a Valkey server you run, for example redis://:<password>@<host>:6379, to read and write the key. The script never signs or sends anything.
Run it and read the output
The run prints three lines: the current block height at confirmed, the blockhash with where it came from and its last valid height, and either the blocks left or the word expired. The run behind this entry had no Valkey server, so it reads from Carbium and says so.
With VALKEY_URL set, the first run fetches from Carbium and writes the key. A run started inside the 20 seconds reads the key back and prints from Valkey with the same blockhash, and the blocks left count drops as the chain advances.
Where it ends
- The check reads the height it is made at. A blockhash can expire between the check and the send, so build the transaction and check again just before signing.
- The cache holds a copy. The height comparison decides whether the copy can be used, and the cache only saves the call that fetches a new blockhash.
- The helper is a small RESP client that sends one short command set per connection. It has no pipelining, no pub/sub and no TLS option, so a Valkey server that requires TLS needs another client.
- The script reads and never signs or sends. The blockhash it stores is for a transaction that other code builds and signs.
- The run behind this entry had no Valkey server, so the cache branch is shown by its code and not by a run against a real server.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The script exits with Set CARBIUM_KEY to your Carbium key. | Export the key in the shell or service that starts the script. The key goes in the x-api-key header, and the script never prints it. |
| A call returns 429 and the output stops with an HTTP error. | Limits are per account, so other services on the same key spend the same budget. Lower their call rate or move to a plan with a higher rate, wait the time the hint gives, then run the check again. |
| The script stops with Valkey: followed by a server message. | Valkey answered with an error line, most often a password in VALKEY_URL that the server does not expect. Match the password part of the URL to the server's setting and run it again. |
| The output says from Valkey and the send then fails with an expired blockhash. | The cached height passed the check when it was read, and the chain moved past lastValidBlockHeight before the send. Fetch a fresh blockhash when the check fails, rebuild the transaction and check again just before signing. |
| The key stays in Valkey for much longer than 20 seconds. | Another writer set the key without a TTL. Check the key's TTL, find that writer, and remove its write or give it EX 20. |
Questions
Does this work with @solana/web3.js?
Yes. The check compares the current block height with lastValidBlockHeight, and web3.js exposes both values from the same two calls. The code here uses @solana/kit 8.6.0 so the key goes in the x-api-key header through one transport.
Why keep the cache TTL so short?
The TTL bounds how long a copy sits, and the height check is what decides whether the copy can be used. A long TTL would leave stale copies for the check to reject, so a short one keeps the cache to recent copies.
Can one cached blockhash serve every wallet?
Yes. A blockhash is not tied to a wallet, so any transaction built on it can carry the signatures of its own signers while the blockhash is inside its window.
Is block height the same as the slot number?
No. A slot can pass with no block produced in it, so slot numbers run ahead of block height. lastValidBlockHeight is counted in block heights, so the check reads block height.