services
Get a key

library / Integrations / I0021

Postgres instruction primary keys

A Node script reads the newest transactions of one program from Carbium RPC and prints one Postgres row per instruction, inner calls included. The primary key is the signature plus two indexes, so reruns and overlapping loads never duplicate a row.

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

01

The key: signature plus two indexes

An instruction has no id of its own on Solana. It is a position inside a transaction, so its identity is the transaction's identity plus that position. The transaction part is its first signature. A signature is 64 bytes, written in base58 as up to 88 characters, and a transaction cannot land twice, so one signature names one transaction for good.

The position part has two levels. A transaction carries a list of top-level instructions, numbered from 0. Any of them can call other programs, and those calls come back in the transaction's metadata as inner instructions, grouped under the index of the top-level instruction that started them. Within a group they sit in the order they ran.

That gives the key (signature, ix_index, inner_index). A top-level instruction takes inner_index = -1, and an inner one takes its position in its group, counting from 0. The sentinel is a plain integer because every column of a primary key must hold a value, and a nullable inner index would let two rows with the same signature and top-level index sit side by side.

Rowix_indexinner_index
First top-level instruction0-1
Second top-level instruction1-1
First call made by instruction 110
Second call made by instruction 111
02

Why not the other candidates

A slot plus the transaction's position in the block is the other natural handle, and it works for a block loader. It needs getBlock, which returns every transaction in a slot, so it is a heavy read when you only follow one program. It also ties identity to a slot, and a slot read at an early commitment can still end up skipped when its fork is dropped. The signature does not move.

A hash of the instruction data is not unique: one program call with the same accounts and the same bytes can appear twice in a transaction, or in a thousand transactions. A program id alone repeats for the same reason. The row id from a surrogate bigserial is fine as a join key but does nothing for idempotence, because a rerun would give the same instruction a new number.

Keep slot as an ordinary column with an index. It sorts the table by time and lets you delete or reload one range, and it stays out of the key.

03

The Solana side: one listing, one fetch per signature

Carbium's RPC endpoint is https://services.carbium.sh, and the script sends the key in the x-api-key request header. getSignaturesForAddress lists the newest signatures that touched the program, and getTransaction with jsonParsed encoding returns the instruction list and the inner instruction groups for each one. Both calls name commitment finalized, since @solana/kit 8.6.0 would otherwise send confirmed, and the server's own default is finalized.

Mainnet carries v1 transactions, and getTransaction answers -32015 for one when maxSupportedTransactionVersion is absent or 0. The script sets it to 1. Failed transactions stay out of the listing's useful set: they still hold instructions on chain, but most pipelines load only the ones that changed state, so the script skips entries with an error. Remove that filter if you want failures in the table, and add a failed column.

The listing comes from Carbium's address index, which keeps up to 30 days. Its pages reach below the validator's ledger floor, so getTransaction can answer null for an older signature the listing returned. The script prints a comment for those and moves on.

04

The Postgres side: a table and an insert that ignores repeats

One table holds the instructions. Create it once.

  • Create: create table if not exists instructions (signature text, ix_index integer, inner_index integer, program_id text, slot bigint, primary key (signature, ix_index, inner_index)).
  • Index: create index if not exists instructions_slot on instructions (slot) for range reads and reloads.
  • Insert: printed by the script as insert into instructions ... on conflict do nothing, so a rerun, an overlapping run or a retried job adds nothing twice.
  • Rebuild a call tree: group by (signature, ix_index), order by inner_index, and the top-level row with -1 heads each group.
$If the table gets large, store the signature as bytea (64 bytes) instead of base58 text. The signature column shrinks by about a quarter, the three-column key by a little less, and the conversion happens in your loader.
05

The reader and how to run it

Install with npm install @solana/[email protected], set "type": "module" in package.json, and use Node 24, which strips the types on load. The script takes a program address as its optional first argument and reads the Jupiter v6 program when none is given. It needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL is optional. It only reads: no signing and no sending.

main.ts
// I0021 · Postgres instruction primary keys// https://carbium.sh/library/integrate/postgres-instruction-primary-keys// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY.");  process.exit(1);}const program = address(process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");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 LIMIT = 3; // keeps the first run short; raise it for real useconst q = (s: string) => `'${s.replaceAll("'", "''")}'`;const msg = (e: unknown) => (e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ");console.log("create table if not exists instructions (signature text, ix_index integer, inner_index integer, program_id text, slot bigint, primary key (signature, ix_index, inner_index));");let sigs;try {  sigs = await rpc.getSignaturesForAddress(program, { commitment, limit: LIMIT }).send();} catch (e) {  console.log(`-- failed: getSignaturesForAddress ${msg(e)}`);  process.exit(1);}const results = await Promise.allSettled(  sigs.filter((s) => s.err === null).map(async (s) => {    const tx = await rpc.getTransaction(s.signature, { commitment, encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();    if (!tx) throw new Error(`no transaction for ${s.signature}`); // listed below the ledger floor    const rows: string[] = [];    const row = (ix: number, inner: number, programId: string) =>      rows.push(`(${q(s.signature)}, ${ix}, ${inner}, ${q(programId)}, ${tx.slot})`);    tx.transaction.message.instructions.forEach((ix, i) => row(i, -1, ix.programId)); // top level: inner = -1    for (const group of tx.meta?.innerInstructions ?? [])      group.instructions.forEach((ix, j) => row(group.index, j, ix.programId));    return `insert into instructions (signature, ix_index, inner_index, program_id, slot) values\n${rows.join(",\n")}\non conflict do nothing;`;  }),);for (const r of results) console.log(r.status === "fulfilled" ? r.value : `-- failed: ${msg(r.reason)}`);if (results.every((r) => r.status === "rejected") && results.length) process.exitCode = 1;

run: node main.ts

The script prints SQL and never connects to Postgres, so psql applies the output: node main.ts PROGRAM | psql -v ON_ERROR_STOP=1. Each transaction becomes one multi-row insert. A signature that fails to fetch prints as a -- failed: comment and the rest still load, so one bad call costs one transaction. To check the key, save the output with node main.ts PROGRAM > out.sql and apply that same file twice with psql -v ON_ERROR_STOP=1 -f out.sql. The second apply inserts 0 rows. Running the command a second time is no check on a busy program, because the newest 3 signatures change between runs and add new rows.

Run it from cron or a systemd timer. A second run over the same newest page is harmless, since the key drops the overlap. A busy program can fill more than one page between runs, though, so a complete table needs a cursor: page with before back to the last stored signature, or keep the newest one and page down to it.

06

What it costs against your limits

The listing costs 50 cells and each getTransaction costs 50 more. A run over the newest 3 signatures is 4 calls and 200 cells. On Free, getSignaturesForAddress allows 0.24 req/s and getTransaction 0.24, on Dev 1.2 and 1.2, on Business 100 and 5, on Pro 500 and 25. A rate class also absorbs a burst of at least 1,024 cells, or one second of its rate when that is larger, which covers the 4 calls here in one go.

Limits are per account, so all your keys share one budget. A call over its budget can come back as a 429 with a retry-after hint. The script lets that error through as a -- failed: line for the transaction it hit. The next run reads the newest page, and on a busy program that page will not list the signature again, so reload it from the -- failed: line or through the cursor paging.

07

Where it ends

  • It reads the newest 3 signatures of one program per run. LIMIT = 3 keeps the first run short; raise it for real use, and run a backfill on purpose.
  • History reaches back 30 days at most, the age of Carbium's address index.
  • The key names an instruction, and it says nothing about its meaning. Decoding the data bytes of an instruction needs the program's layout, and that belongs in your loader.
  • It stores the program id and the slot only. Accounts and data are in the same getTransaction reply, so add columns when you need them; they do not change the key.
  • The inner index counts a flattened list in execution order. If you need the nesting depth of a call, the reply carries a stack height per instruction that you can store beside it.
  • A listing of one program's signatures holds transactions that mention it, so the table also gets the other programs those transactions called.
08

When it goes wrong

what goes wrongwhat to do
A second run inserts rows that look like repeats.The primary key is missing, or inner_index is nullable and holds null for top-level rows. Postgres treats nulls as distinct in a unique index, so use -1 and declare the three columns as the primary key.
The output has a -- failed: comment with a -32015 error.A v1 transaction was read without maxSupportedTransactionVersion: 1. Set it on every getTransaction call, as the script does.
The output has a -- failed: comment saying the transaction was not found.getTransaction answered null for an older signature that the listing still returned, since the address index reaches below the validator's ledger floor. Skip it, or load it from your own records.
The output has a -- failed: comment with a 429.The account's budget is spent for now. Wait and rerun: the key makes the repeat safe. The newest page may no longer list that signature, so reload it from the -- failed: line or through cursor paging.
A top-level instruction and an inner one collide on the key.The inner row was written with a top-level inner_index of -1. Number inner instructions from 0 inside each group and keep -1 for top-level rows only.
A backfill that pages back with before stops with no rows for transactions older than a month.The address index keeps up to 30 days, and an empty page past that marks its age limit. Load older instructions from your own records.
09

Questions

Is the signature alone a good primary key?

Only for transactions. One transaction holds many instructions, so a signature repeats once per instruction. Add the top-level index and the inner index to make each row unique.

Can two different transactions share a first signature?

No. A signature is a 64-byte value over the transaction's message, and the network rejects a second transaction with the same one. That is why the first signature works as the transaction's id.

Should the slot be part of the key?

No. A signature already names one transaction, and the slot adds nothing to uniqueness. Keep it as an indexed column so you can reload or delete a range.

Can a WebSocket feed the same table?

Yes. logsSubscribe on the WebSocket streams transaction logs by mention, and each notification carries a signature. Fetch the transaction with getTransaction and insert the same rows; the primary key drops any signature you also read by polling.