---
id: I0072
title: "SQLite recent transaction cache"
url: https://carbium.sh/library/integrate/sqlite-recent-transaction-cache
collection: Integrations
category: Relational databases
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# SQLite recent transaction cache

A Node script fills a SQLite table with the newest N signatures of an address from Carbium, then refreshes it by asking only for signatures newer than the newest stored one. A page view reads the table and spends no call.

## The table

An app that shows the last 20 transactions of an address on every page view should not ask the network on every view. A local SQLite file answers the view, and a refresh asks Carbium only for what is newer than the newest row the file holds. `node:sqlite` ships with Node 24, so the cache is one file and needs no server.

| Column | Holds |
|---|---|
| `signature` | The transaction signature, primary key |
| `slot` | The slot the transaction landed in |
| `block_time` | Unix seconds, null when the node has no time for the slot |
| `err` | The error as JSON, null when the transaction succeeded |

The signature is the key because the same signature can arrive twice, once in the first fill and again in a later pull that overlaps it. `insert or ignore` drops the repeat and reports zero changes, which is how the script counts the rows it added. The file name carries the address, so one file holds one address and a second address gets its own file.

SQLite also numbers every row in the order it was inserted. The script inserts each page oldest first, so a higher row number is a later transaction. Many transactions share a slot, and the row number settles their order inside it.

## First fill with limit N

On an empty table the script calls `getSignaturesForAddress` with `limit` set to N, here 20. The answer lists signatures newest first, each with its slot, block time and an error field that is null on success. Failed transactions are listed too, so the table holds them unless you filter.

The call [costs 50 cells](https://carbium.sh/docs/rpc) and is rated at 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. A rate class [absorbs bursts](https://carbium.sh/docs/limits) of up to 1,024 cells or one second of its rate, whichever is larger. Twenty of these calls back to back hold on Free and Dev, and Business and Pro absorb one second of their rate.

The script names `confirmed` in the call, so the table holds the chain at confirmed commitment.

## Incremental pull with until

Every later refresh asks for the signatures newer than the newest one stored. The `until` option takes a signature and ends the list there: the call returns what landed after it, newest first, and the signature itself is left out. kit types it as a `Signature`, so the script wraps the stored string with `signature()`.

The refresh sets `limit` to 1000, the most one call returns, so the backlog since the last refresh arrives in one call. The limit is set inside the pull: N applies only to an empty table, so a rerun against an existing file never trims a refresh to 20 and leaves a gap. When nothing is newer the list is empty and the whole cost is one 50-cell call. A refresh timer of 5 seconds for one address makes 0.2 calls a second, under the Free rate of 0.24. That fits one address per account on Free, because a second address on the same timer goes over the 0.24 req/s that [the account shares](https://carbium.sh/docs/limits) across all its keys.

The page view itself reads SQLite. Ten thousand views in a minute still make the one refresh the app decides to run, and the viewers share it.

## The script

Run it on Node 24 after `npm install @solana/kit@8.6.0`, with `CARBIUM_KEY` set. The first argument is the address. It makes two passes about 3 seconds apart: a fill with limit 20, then a refresh with `until`. Each pass prints how many signatures the call listed and how many rows were new, and a failed pass prints its message while the other still runs. It only reads: no signing and no sending.

`main.ts` (run: `node main.ts <address> [N]`)

```ts
// I0072 · SQLite recent transaction cache
// https://carbium.sh/library/integrate/sqlite-recent-transaction-cache
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const target = process.argv[2];
if (!target) {
  console.error("Usage: node main.ts <address> [N]");
  process.exit(1);
}
const n = Number(process.argv[3] ?? 20);
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const db = new DatabaseSync(`recent-${target}.db`); // relative: one file per address in the working directory
db.exec("create table if not exists sigs (signature text primary key, slot integer not null, block_time integer, err text)");
db.exec("create index if not exists sigs_slot on sigs(slot)");
const put = db.prepare("insert or ignore into sigs values (?, ?, ?, ?)");

async function pull(label: string, limit: number) {
  try {
    const last = db.prepare("select signature from sigs order by rowid desc limit 1").get() as { signature: string } | undefined;
    const page = await rpc
      .getSignaturesForAddress(address(target), { limit: last ? 1000 : limit, commitment: "confirmed", ...(last && { until: signature(last.signature) }) })
      .send();
    let added = 0;
    for (const s of [...page].reverse()) { // oldest first, so a higher rowid is a later transaction
      const err = s.err ? JSON.stringify(s.err, (_, v) => (typeof v === "bigint" ? v.toString() : v)) : null;
      added += Number(put.run(s.signature, s.slot, s.blockTime, err).changes);
    }
    console.log(`${label}: ${page.length} listed, ${added} added`);
  } catch (e) {
    console.log(`${label} failed: ${e instanceof Error ? e.message : String(e)}`);
  }
}

await pull("pass 1 (limit " + n + ")", n);
await new Promise((r) => setTimeout(r, 3000)); // let a few newer transactions land
await pull("pass 2 (until newest stored)", n);

type Row = { slot: number; signature: string; err: string | null };
const rows = db.prepare("select slot, signature, err from sigs order by slot desc, rowid desc limit 5").all() as unknown as Row[];
for (const r of rows) console.log(`${r.slot} ${r.signature} ${r.err ?? "ok"}`);
```

The last lines print the newest five rows, one per line, with slot, signature and `ok` or the stored error. On a busy address the refresh can list over a hundred new signatures in that gap, and it adds the same number, because everything listed is newer than the stored one.

## Reading N rows back

The read for the page is one query on the table: `order by slot desc, rowid desc limit ?`. Slot gives the chain order, and the row number breaks ties between transactions in the same slot. The script creates an index on `slot`, so SQLite reads the newest rows from the end of the index. The query touches no network and returns in the time SQLite takes to read a few rows.

A page that needs more than the row, such as the transfers inside a transaction, calls `getTransaction` for the few rows it shows. That call costs 50 cells too, and it needs `maxSupportedTransactionVersion: 1` with an encoding, because with that option absent or 0 Carbium answers [-32015](https://carbium.sh/docs/rpc) for a v1 transaction. Cache the decoded detail in a second table once you have it, so a row is fetched once.

## Where it ends

- The list comes from an address index that keeps up to 30 days. Past that the page is empty, and the address may have older transactions the index no longer serves. Rows you stored earlier stay in your file.
- The index pages reach below the validator's ledger floor, so `getTransaction` can answer null for an older signature the list returned. Show the cached row and skip the detail when it does.
- Failed transactions are listed with a non-null `err`. If the page shows N successful transactions, filter on `err is null` and keep a larger table than N.
- A refresh that finds more than 1000 new signatures gets only the newest 1000, and the older ones in between are missing. Page the call with `before` until it reaches the stored signature, or refresh more often.
- `until` is exact only when the stored signature is the newest one the table holds, so the script keeps arrival order and never inserts a page newest first.
- SQLite suits one process writing. Several writers on one address want a server database, and the signature key keeps their inserts safe to repeat.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The table has a gap between two groups of rows. | More than 1000 transactions landed since the last refresh, so the call returned only the newest 1000. Page with `before` until the stored signature appears, or refresh more often on a busy address. |
| The second pass prints `0 listed, 0 added`. | Nothing landed in the seconds between the passes, or the address is quiet. An empty list is a normal answer when `until` is the newest signature. Run again later. |
| `getTransaction` answers null for a signature the cache holds. | The index lists signatures below the validator's ledger floor, so an older one may have no transaction to read. Show the cached slot, time and error, and skip the detail. |
| `getTransaction` answers -32015. | The transaction is v1 and the call left out the version option. Pass `maxSupportedTransactionVersion: 1` with an encoding. |
| Rows in one slot show in a different order from an explorer. | A page was inserted newest first, or two files were merged. Insert each page oldest first and order the read by slot, then by row number. |

## Questions

### Why `until` and not a timestamp?

A signature names one exact place in the list, so the call returns the rows after it and no others. A timestamp can fall in the middle of a slot and either repeat rows or skip them.

### How often can the refresh run?

A call costs 50 cells, and the rate is 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. Limits are [per account](https://carbium.sh/docs/limits) and its keys share one budget, so on Free the 0.24 req/s is split across every address the account refreshes, about one call every 4 seconds in all. Refresh each address on a short timer within that budget and let every viewer read the table.

### Can the cache reach back past 30 days?

The [address index](https://carbium.sh/docs/migrate) keeps up to 30 days, and an empty page past that shows its age limit. The table keeps whatever you stored while the rows were in range.

### Where do I go from a row to the transfers inside it?

Read it with `getTransaction` and decode the instructions. [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) covers paging the list with `before`, and [Wallet transaction CSV export](https://carbium.sh/library/integrate/wallet-transaction-csv-export) walks a full list to a file.

## Related

- [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) (How to use Solana, HS0034)
- [Wallet transaction CSV export](https://carbium.sh/library/integrate/wallet-transaction-csv-export) (Integrations, I0070)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
