services
Get a key

library / Integrations / I0047

Postgres indexer slot checkpoints

A small Node loop reads finalized blocks from Carbium RPC and stores one row per slot. The checkpoint row commits in the same transaction, so a restart resumes at the next slot, skipped slots included.

By Carbium · Relational databases · I0047 · updated 2026-11-22

01

What the checkpoint records

An indexer that restarts needs one answer from its own database: which slot did I finish. The checkpoint is that answer, a single row holding the highest slot whose work is complete. On start the loop reads it, takes the next slot and carries on. With no checkpoint the loop has no safe place to begin, so it picks one and writes it down.

Complete has a precise meaning here. A slot is complete when its block row is stored, or when the chain shows it never had a block. Everything between the checkpoint and the tip is work still to do, and everything at or below the checkpoint is never read again. That second property makes a restart cheap, and it holds only while the checkpoint never gets ahead of the rows.

Two failures break it. If the checkpoint moves first and the process dies before the block row lands, the slot is lost and the table has a gap. If the block row lands first and the process dies before the checkpoint moves, the next run reads the slot again and either stores a duplicate or hits a key error. Writing both in one database transaction removes both cases, because a transaction applies in full or not at all.

02

Two tables, one transaction

Two tables carry the design. checkpoint holds one row, pinned by check (id = 1). blocks holds one row per stored slot.

TableColumnsRole
checkpointid, slotThe last completed slot, always one row
blocksslot (primary key), blockhash, parent_slot, block_time, tx_countOne row per slot that had a block

Each slot is written as begin, an insert into blocks when the slot had a block, an upsert of the checkpoint, then commit. The upsert insert into checkpoint (id, slot) values (1, ?) on conflict (id) do update set slot = excluded.slot runs unchanged on Postgres, where the placeholder is $1 and the slot columns are bigint. If anything throws between begin and commit, the code runs rollback and neither row exists.

$The code runs on node:sqlite so it needs no server. To point it at Postgres, keep the same statements and run the begin, the inserts and the commit on one connection through your driver's transaction call. Two statements on two connections are two transactions, and the guarantee is gone.

One slot per transaction is the simplest shape. A batch of many slots in one transaction is fine too, as long as the checkpoint update sits in it together with the rows it covers.

03

The loop up to the finalized tip

A pass starts with getSlot at finalized, a cheap cached read at 1 cell. That slot is the tip. The loop then walks every slot from the checkpoint plus one up to the tip and calls getBlock for each, in order, with transactionDetails: "signatures". A block comes back as its blockhash, parent slot, block time and a list of signatures, which is enough to count and to point at transactions later.

getBlock also takes maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with that value absent or 0 the call answers -32015 for a block that holds one, so the loop would halt at the first such block.

Both calls name finalized. @solana/kit fills in confirmed when a call leaves commitment out, so the code spells the level out. A checkpoint that only ever rests on finalized slots cannot sit on a fork that is later dropped. The first run begins five slots before the tip. See Solana commitment levels for the three levels.

Every getBlock sits in its own try. When a call fails for any reason except a skipped slot, the loop prints the slot and the error and stops. The checkpoint stays on the last slot that was stored, and the next pass resumes there. A 429 from the rate limit ends a pass the same way.

04

Skipped slots advance the checkpoint

A slot whose leader produced no block has nothing to store. Solana's getBlock answers it with error -32007, or -32009 when the request goes to long-term storage. @solana/kit raises both as typed errors that isSolanaError can test. The loop treats those two as an answer about the slot and advances the checkpoint to it, in a transaction that carries no block row.

Telling them apart from other failures is the point. A 429 or a dropped connection says nothing about the slot, and treating it as skipped would write a gap into blocks with the checkpoint standing on top of it. So a gap in the blocks.slot column is always a skipped slot, never a lost one, because the checkpoint and the rows commit together.

It is also why the checkpoint is a slot and not a signature. A skipped slot leaves no signature, and the loop still has to step over it or it would ask for the same slot forever.

$Mainnet blocks carry no vote transactions since Alpenglow, so tx_count counts the other transactions in the block.
05

The indexer

Install with npm install @solana/[email protected], set "type": "module" in package.json and use Node 24, which strips the types on load and ships node:sqlite. The script needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL is optional. The database is indexer.db in the working directory. On the chain side it only reads.

main.ts
// I0047 · Postgres indexer slot checkpoints// https://carbium.sh/library/integrate/postgres-indexer-slot-checkpoints// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isSolanaError,  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,  type Slot,} from "@solana/kit";import { DatabaseSync } from "node:sqlite";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set 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 = "finalized"; // named on every call: kit would send "confirmed"const db = new DatabaseSync("indexer.db"); // stands in for Postgres; same SQL, $1 for ?db.exec(`create table if not exists checkpoint (id integer primary key check (id = 1), slot integer not null);create table if not exists blocks (slot integer primary key, blockhash text not null, parent_slot integer not null, block_time integer, tx_count integer not null);`);const cp = (): bigint | undefined => {  const r = db.prepare("select slot from checkpoint where id = 1").get();  return r ? BigInt(r.slot as number) : undefined;};// One transaction: the block row (none for a skipped slot) and the checkpoint commit together.const save = (slot: bigint, row?: [string, bigint, bigint | null, number]) => {  db.exec("begin");  try {    if (row) db.prepare("insert into blocks (slot, blockhash, parent_slot, block_time, tx_count) values (?, ?, ?, ?, ?)").run(slot, ...row);    db.prepare("insert into checkpoint (id, slot) values (1, ?) on conflict (id) do update set slot = excluded.slot").run(slot);    db.exec("commit");  } catch (e) {    db.exec("rollback");    throw e;  }};const pass = async (tip: bigint) => {  let stored = 0;  let skipped = 0;  for (let s = (cp() ?? tip) + 1n; s <= tip; s++) {    try {      const b = await rpc        .getBlock(s as Slot, { commitment, transactionDetails: "signatures", rewards: false, maxSupportedTransactionVersion: 1 })        .send();      if (!b) throw new Error("block not available");      save(s, [b.blockhash, b.parentSlot, b.blockTime, b.signatures.length]);      stored++;    } catch (e) {      if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED) || isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED)) {        save(s); // no block was produced: advance the checkpoint, store no row        skipped++;        continue;      }      console.error(`slot ${s} stopped: ${e instanceof Error ? e.message : String(e)}`);      break; // the checkpoint stays on the last stored slot    }  }  return { stored, skipped };};try {  const before = cp();  const tip = await rpc.getSlot({ commitment }).send();  if (before === undefined) save(tip - 5n); // first run: start five slots behind the tip  const first = await pass(tip);  const second = await pass(tip);  console.log(`checkpoint before: ${before ?? "none"}`);  console.log(`slots stored: ${first.stored}`);  console.log(`slots skipped: ${first.skipped}`);  console.log(`checkpoint after: ${cp()}`);  console.log(`second pass stored nothing: ${second.stored === 0 && second.skipped === 0}`);} catch (e) {  console.error(`run failed: ${e instanceof Error ? e.message : String(e)}`);  process.exitCode = 1;}

run: node main.ts

With no checkpoint, main.ts starts at the tip minus five. It runs the loop twice against the same tip, then prints the checkpoint before, slots stored, slots skipped, the checkpoint after, and whether the second pass stored nothing. Run it again later and the first line shows the earlier checkpoint, so the new run walks forward from there up to the new tip, one getBlock for each slot.

06

Where it ends

  • Each row is a block with a signature count. Transactions, accounts and instructions need their own tables, written in the same transaction as the block row. Postgres instruction primary keys shows keys for that layer.
  • It starts at the tip and does not backfill. A checkpoint set to an older slot works as far as getBlock still answers for it, and the loop stops at the first slot that fails. The loop does not check how far back that reaches.
  • One writer. Two processes on one database read the same checkpoint and try the same slots. The primary key on blocks.slot rejects the second insert and rolls its transaction back, so the data stays correct and one process wastes its calls. The loop picks its slot before the transaction starts, so a row lock alone does not stop a slower writer from moving the checkpoint back. Run one, hold pg_try_advisory_lock for the process, or start each transaction with select slot from checkpoint where id = 1 for update, re-read the locked slot and skip when it is at or past the current slot.
  • A pass ends at the first failing slot, so a stuck slot holds the checkpoint until a later pass succeeds. Alert on the tip minus the checkpoint.
  • After a long stop the loop walks every slot in between, one call each. Limits are per account, so those calls draw on the same budget as the rest of your keys.
  • It sees a slot once the slot is finalized. A schedule or a WebSocket slot subscription can start each pass.
07

When it goes wrong

what goes wrongwhat to do
getBlock fails with -32015 and the loop stops on a block that holds a v1 transaction.Pass maxSupportedTransactionVersion: 1 in the getBlock options. Absent or 0, a block holding a v1 transaction answers -32015.
The run prints slot N stopped with a 429 and exits with fewer slots than expected.The account's budget was spent. The checkpoint still sits on the last stored slot, so wait and run again. The pass resumes at the slot that failed.
After a crash the checkpoint is ahead of blocks, and a slot has no row though the chain had a block.The checkpoint and the block row were written in separate transactions. Put both statements between one begin and one commit on the same connection.
Every slot reports block not available and nothing is stored.The loop asked above what the node serves at that commitment. Read the tip with getSlot at finalized, and call getBlock at finalized as well.
A second copy of the process fails with a unique constraint error on blocks.slot.Two writers raced for the same slot, and the primary key rolled the loser back. Run one writer, hold pg_try_advisory_lock for the process, or lock the checkpoint row with for update at the start of each Postgres transaction, re-read the slot and skip when it is at or past the current slot.
08

Questions

Why store a slot checkpoint and not the last signature?

Slots are ordered and a block is read by its slot. A skipped slot has no signature, so a signature cursor cannot step over it.

Can a WebSocket slot subscription drive the loop?

It can start a pass, but a slot its leader never produced sends no notification, and a slot announced at processed can still end up skipped. The loop therefore reads the finalized tip with getSlot and walks every slot up to it. A slot subscription costs credits to open and per MiB sent.

What changes to run the same code on Postgres?

The blocks insert takes $1 to $5, the checkpoint upsert takes $1, and the slot columns become bigint. The two statements run on one connection between begin and commit, and the SQL text is otherwise the same.

Where do the transactions themselves go?

Into their own table keyed by slot and position, inserted in the same transaction as the block row. The checkpoint then covers them too, with no extra cursor.