---
id: I0027
title: "Redis live balance cache"
url: https://carbium.sh/library/integrate/redis-live-balance-cache
collection: Integrations
category: Document and key-value stores
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Redis live balance cache

A Node watcher subscribes to the logs of each wallet you name over the Carbium WebSocket, re-reads the SOL balance after every transaction that touches it, and writes the result to a Redis hash your app reads in one command.

## What lands in Redis

The watcher keeps one Redis hash per wallet, named `balance:<address>`, with two fields. `lamports` is the SOL balance as a decimal string, and `slot` is the slot of the read that produced it. Your app reads the pair with one `HGETALL`, and no request path of yours calls Solana.

The process is one Node file with `@solana/kit` as its only dependency. It takes the wallets as arguments, opens one WebSocket to Carbium, and subscribes to the logs of each wallet. When a transaction touches a wallet, it reads that wallet's balance once and writes the hash. The Redis connection is plain RESP over `node:net`, so no Redis package is needed.

| Step | Call | Effect |
|---|---|---|
| Start | `getBalance` for each wallet | The cache is filled before any event arrives. |
| Subscribe | `logsSubscribe` with one mention | One subscription id per wallet, and a fresh read once it is live. |
| Notification | `logsNotification` at `confirmed` | The wallet is queued for 250 ms, so a burst of hits becomes one read. |
| Read | `getBalance` with `minContextSlot` | The answer comes from a node at or past the notified slot. A failed read is tried again after 1 s, up to 5 more times. |
| Write | `HSET balance:<address>` | Lamports and slot replace the old pair, unless the same or a newer slot is already stored. |

## Why logs, and then a read

A plain SOL wallet is not a streamed account, so [accountSubscribe sends it nothing](https://carbium.sh/docs#websocket) on Carbium. The route that works is `logsSubscribe` with a `mentions` filter, followed by `getBalance`. A mention filter matches any transaction that lists the wallet among its accounts, which covers incoming transfers, outgoing transfers and the fee the wallet pays.

A notification carries log lines and a slot, never a balance, so the watcher treats it as a signal and reads the balance itself. Both the subscription and the read run at `confirmed`. Change both to `finalized` if the cache must never hold a balance that a dropped fork could take back.

A failed transaction still charges its fee to the fee payer, so that wallet's balance changes. A failed transaction that only lists the wallet leaves its balance unchanged. The handler ignores the `err` field of the logs and reads after every notification.

The read passes the notified slot as `minContextSlot`, so a node that has not reached that slot answers with an error and never with an old number. The watcher logs that error and asks again a second later, up to 5 more times. `getBalance` also returns the slot it read at, which the watcher compares with the slot it last stored for that wallet, because two reads in flight can finish in either order.

## The watcher

Install it with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is your [API key](https://carbium.sh/docs#auth) and is required, and the wallets follow the file name on the command line.

`REDIS_HOST`, `REDIS_PORT` and `REDIS_PASSWORD` are optional. With no `REDIS_HOST` the file prints each `HSET` instead of sending it, which lets you try the watcher before a Redis exists.

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

```ts
// I0027 · Redis live balance cache
// https://carbium.sh/library/integrate/redis-live-balance-cache
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Slot } from "@solana/kit";
import net from "node:net";

const key = process.env.CARBIUM_KEY;
const wallets = process.argv.slice(2);
if (!key || wallets.length === 0) {
  console.error("Set CARBIUM_KEY and pass wallet addresses: node main.ts <wallet> [wallet ...]");
  process.exit(1);
}
const apiKey: string = key;

// Redis side: plain RESP over TCP. With REDIS_HOST unset the commands print instead.
const redis = process.env.REDIS_HOST
  ? net.connect({ host: process.env.REDIS_HOST, port: Number(process.env.REDIS_PORT ?? 6379) })
  : null;
const send = (...args: string[]) => {
  if (!redis) return void console.log(args.join(" "));
  redis.write(`*${args.length}\r\n` + args.map((a) => `$${Buffer.byteLength(a)}\r\n${a}\r\n`).join(""));
};
redis?.on("data", (d) => String(d).split("\r\n").filter((l) => l.startsWith("-")).forEach((l) => console.error("redis:", l)));
redis?.on("error", (e) => { console.error("redis:", e.message); process.exit(1); });
if (redis && process.env.REDIS_PASSWORD) send("AUTH", process.env.REDIS_PASSWORD);

const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey } }),
);
const seen = new Map<string, Slot>();

// A failed read is tried again after 1 s, up to 5 more times, so every hit ends in a write.
async function refresh(wallet: string, minContextSlot?: Slot, tries = 5) {
  try {
    const { context, value } = await rpc
      .getBalance(address(wallet), { commitment: "confirmed", minContextSlot })
      .send({ abortSignal: AbortSignal.timeout(5_000) });
    if (context.slot <= (seen.get(wallet) ?? 0n)) return; // an older read never overwrites a newer one
    seen.set(wallet, context.slot);
    send("HSET", `balance:${wallet}`, "lamports", String(value), "slot", String(context.slot));
  } catch (e) {
    console.error(`getBalance ${wallet}:`, e instanceof Error ? e.message : e);
    if (tries > 0) setTimeout(() => void refresh(wallet, minContextSlot, tries - 1), 1_000);
  }
}

// A burst of hits on one wallet becomes one read, at the newest slot seen.
const pending = new Map<string, Slot>();
function touch(wallet: string, slot: Slot) {
  const queued = pending.has(wallet);
  if (slot > (pending.get(wallet) ?? 0n)) pending.set(wallet, slot);
  if (queued) return;
  setTimeout(() => {
    const s = pending.get(wallet);
    pending.delete(wallet);
    void refresh(wallet, s);
  }, 250);
}

const subscribed = new Map<string, string>(); // subscription id as text -> wallet
function connect() {
  const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
  url.searchParams.set("api-key", apiKey);
  const ws = new WebSocket(url);
  subscribed.clear();
  ws.onopen = () =>
    wallets.forEach((w, i) =>
      ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params: [{ mentions: [w] }, { commitment: "confirmed" }] })),
    );
  ws.onmessage = (ev) => {
    const m = JSON.parse(String(ev.data));
    if (m.method === "logsNotification") {
      const w = subscribed.get(String(m.params.subscription));
      if (!w) return;
      const slot = BigInt(m.params.result.context.slot) as Slot;
      console.log("logs", w, String(slot)); // failed transactions pay a fee too, so every hit triggers a read
      touch(w, slot);
    } else if (m.error) {
      console.error("subscribe", wallets[m.id - 1], "refused:", m.error.message);
    } else if (m.result != null) {
      subscribed.set(String(m.result), wallets[m.id - 1]);
      void refresh(wallets[m.id - 1]); // read once the subscription is live, so nothing falls in a gap
    }
  };
  ws.onclose = () => {
    console.error("socket closed, reconnecting in 2 s");
    setTimeout(connect, 2_000);
  };
}

wallets.forEach((w) => void refresh(w)); // fill the cache at once
connect();
```

## Run it and read the cache

Start it with `REDIS_HOST=127.0.0.1 node main.ts WALLET_1 WALLET_2` under a supervisor such as a systemd unit. The first lines are the startup reads, one `HSET` per wallet. After that each transaction that touches a wallet prints a `logs <wallet> <slot>` line, and an `HSET` follows it about 250 ms later. A read that fails is retried after a second, so that write can arrive a second or more late.

A reader needs `HGETALL balance:<address>`, or `HGET balance:<address> lamports` for the number alone. Lamports are a string of digits, 1,000,000,000 to the SOL, so parse them into an integer type that holds 64 bits. The `slot` field tells you which read the number came from. A quiet wallet keeps an old slot with a correct balance, so a wide gap to the current slot says nothing against the value.

## What it costs on Carbium

A `logsSubscribe` with a mentions filter [costs 25 credits to open](https://carbium.sh/docs#limits), then 20 credits per MiB sent, and a refused subscription costs nothing. Each notification carries the transaction's log lines. 1,000 notifications of 2 KiB each come to about 2 MiB, about 40 credits.

Every notification also triggers one RPC read, so the read rate is the number to watch. The 250 ms queue caps it at 4 reads a second per wallet before retries, and all keys on an account share one budget. A call over its rate can end in a 429.

Free carries 5 sockets, and this file uses one however many wallets it follows. Subscriptions are capped per plan too, so how many wallets one account can follow depends on the plan. Hundreds of wallets call for a different design, and [Wallet watch list at scale](https://carbium.sh/library/integrate/wallet-watch-list-at-scale) is the entry for it.

## Where it ends

- It caches SOL only. A token balance lives in a token account, and a token transfer to an existing token account lists the token accounts and the sender's authority, never the receiving wallet. Watch the token account itself and read it with `getTokenAccountBalance`; [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) shows that read.
- Lamport changes that arrive without a transaction, such as the block fee reward a leader's identity account collects for each block it produces, send no log. The cache catches up at the next transaction that touches the wallet or at the next reconnect.
- It is a latest-value cache. It keeps no history, and two changes inside one 250 ms window show up as the second value only.
- The slot guard lives only in the watcher's memory. Run one watcher per set of wallets, since two writers can overwrite each other with an older read.
- A watcher that dies leaves its last values in place with no sign. Supervise the process, or write a heartbeat key of your own and have readers check it.
- The Redis client is the smallest one that works: plain TCP, no TLS, no cluster, and replies are only checked for errors. For a managed Redis, replace `send` with your client's `HSET`.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The log fills with `socket closed, reconnecting in 2 s` and no wallet ever updates. | The handshake is being refused. An [unknown key gets a 401](https://carbium.sh/docs#errors) at the door, so check that `CARBIUM_KEY` holds the whole key and that `CARBIUM_WS_URL`, if set, points at `wss://services.carbium.sh`. |
| The log repeats `redis: -NOAUTH Authentication required` after each write and no hash appears in Redis. | Your Redis wants a password. Each write logs the error and the process keeps running, so set `REDIS_PASSWORD`, check that `REDIS_HOST` and `REDIS_PORT` name the server you meant, and restart. |
| A line `subscribe <wallet> refused:` appears for some wallets and those hashes never change after the first read. | Read the message after it. If it names a limit, the plan caps subscriptions per account: follow fewer wallets or move to a plan with more room. A refused subscription costs nothing, and the wallets that were accepted keep working. |
| A line `getBalance <wallet>:` names a minimum context slot that was not reached. | The node that answered was behind the slot the notification named. The watcher retries the read itself, once a second and up to 5 more times, so the value repairs without another notification. If the line keeps repeating, raise the 250 ms queue delay in `touch` so the read goes out a little later. |
| `getBalance` fails with an HTTP 429 during a busy stretch and some hashes lag. | The account is over its [read rate](https://carbium.sh/docs#limits), often because other keys on it are busy too. Raise the queue delay to cut the reads per wallet, follow fewer wallets from this key, or use a plan with a higher rate. |
| A wallet receives tokens and its hash shows nothing new. | Its SOL did not move, and a transfer to an existing token account never lists the receiving wallet, so no log mentions it. Follow the token account for the balance you want. |

## Questions

### Why not accountSubscribe on the wallet?

Carbium sends account state on change for streamed accounts and sends nothing for a plain SOL wallet. The route for a wallet is `logsSubscribe` with a mention, then `getBalance`.

### Does a failed transaction update the cache?

Only when the wallet paid the fee. The watcher reads after every notification without looking at the error field, so when the wallet only appeared in the failed transaction it stores the same number again with a newer slot.

### Why not poll getMultipleAccounts on a timer?

A 100-wallet call costs 1,000 cells, and a call carries at most 100 pubkeys below Pro, so a poll pays for every wallet whether or not it changed. [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) is the polling version of this job.

### Can two watchers write to the same Redis?

They can, but each keeps its own memory of the newest slot, so one can overwrite the other with an older read. Run one watcher per set of wallets.

## Related

- [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) (Blockchain ideas, BI0006)
- [Wallet watch list at scale](https://carbium.sh/library/integrate/wallet-watch-list-at-scale) (Integrations, I0011)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
