---
id: I0076
title: "Postgres backfill-to-live handoff"
url: https://carbium.sh/library/integrate/postgres-backfill-to-live-handoff
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
---

# Postgres backfill-to-live handoff

A Node script opens a logsSubscribe on one program, pages its signature history backwards while the socket listens, fetches logs for the newest three, and prints counts plus one insert. The signature primary key absorbs the overlap.

## Two sources, one table

An indexer that wants every log line of one program has two jobs that look separate. History comes from `getSignaturesForAddress`, which lists signatures newest first, and from `getTransaction`, which returns the log messages of one of them. New activity comes from `logsSubscribe` with a `mentions` filter, which pushes each transaction's logs as it lands. Each source answers a different stretch of time, and neither covers the moment where the other is still catching up.

Both feed one Postgres table keyed by signature. A signature names one transaction for good, so a row that arrives from both sources is the same row. The table has three columns: `signature text primary key`, `slot bigint` and `logs jsonb`. The order in which the two sources start decides whether the table ends up with a gap.

## Why live starts first

Suppose the loader pages history first and opens the socket afterwards. The listing ends at the moment of its last call. Anything that lands between that call and the moment the subscription is acknowledged sits in neither source: the listing already ran, and the socket was not open yet. On a busy program that window is a few seconds wide, and it is easy to miss, because every count you check afterwards looks plausible.

Reverse the order. Open the subscription, wait for its reply, then start listing. Every transaction that lands from then on arrives on the socket, and everything older is in the listing. A transaction that lands while the listing runs can appear in both. That is the cheap failure: a duplicate is something the primary key absorbs, and a gap is something you cannot see.

## Paging back with before

`getSignaturesForAddress` returns up to the `limit` you set, newest first. To go further back, pass the oldest signature of the page you hold as `before`, and the next page starts just below it. The script reads two pages of 5 to show the move. A real loader keeps going until it reaches a stop point, and the stop point depends on the job.

- First load: stop at a cutoff you choose, such as a slot or a block time, or at an empty page.
- Catch-up after downtime: stop when a page contains the newest signature already stored in Postgres.
- Reload of a range: stop at the first signature older than the range, and delete the range's rows first only if you must correct them.

The listing comes from Carbium's [address index](https://carbium.sh/docs/migrate), which keeps up to 30 days. An empty page past 30 days marks the index's age limit, and the address may have older transactions. The pages reach below the validator's ledger floor, so `getTransaction` can answer null for an older signature the listing returned. The script reports those and moves on.

## The overlap and ON CONFLICT DO NOTHING

The script prints one statement: `insert into program_logs (signature, slot, logs) values ... on conflict (signature) do nothing`. When the live side and the backfill side hand over the same signature, the second insert changes nothing. Postgres also accepts the same key twice inside one statement under `do nothing`, so live rows and backfilled rows go into one insert with no deduplication step.

`do update` behaves differently. It raises an error when one statement holds the same key twice, so if you want a later row to replace an earlier one, apply the rows in separate statements or deduplicate in code first. For logs there is nothing to replace: a transaction's log messages never change after it lands.

| Transaction landed | Seen by | Rows in the table |
|---|---|---|
| Before the subscription was acknowledged | Listing only | One |
| While the listing was running | Socket and listing | One, and the overlap count goes up |
| After the listing finished | Socket only | One |

> The script fetches logs for the newest 3 listed signatures and counts the rest. Counted signatures have no row yet. A full loader runs `getTransaction` for each one and inserts the result the same way.

## The handoff script and how to run it

Install with `npm install @solana/kit@8.6.0`, set `"type": "module"` in `package.json`, and use Node 24, which strips the types on load. The first argument is a program address, and the script 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` and `CARBIUM_WS_URL` are optional. It only reads.

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

```ts
// I0076 · Postgres backfill-to-live handoff
// https://carbium.sh/library/integrate/postgres-backfill-to-live-handoff
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";
import type { Signature } 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 wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
const commitment = "confirmed"; // socket and listing use the same level
const PAGE = 5; // signatures per listing page
const FETCH = 3; // newest signatures whose logs are fetched
const WINDOW_MS = 8000; // how long the socket listens
const q = (s: string) => `'${s.replaceAll("'", "''")}'`;
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ");

const rows: string[] = [];
const add = (sig: string, slot: number | bigint, logs: readonly string[]) =>
  rows.push(`(${q(sig)}, ${slot}, ${q(JSON.stringify(logs))}::jsonb)`);

// 1. Live first: open logsSubscribe and wait for its reply before any listing.
const liveSigs = new Set<string>();
let wsNote = "";
const started = Date.now();
const ws = new WebSocket(wsUrl);
const ready = new Promise<void>((done) => {
  ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [program] }, { commitment }] }));
  ws.onclose = ws.onerror = () => { wsNote ||= "socket closed or failed"; done(); };
  ws.onmessage = (e) => {
    const m = JSON.parse(String(e.data));
    if (m.error) wsNote = `subscribe refused: ${m.error.message}`;
    if (m.id === 1) done();
    if (m.method === "logsNotification") {
      const { context, value } = m.params.result;
      liveSigs.add(value.signature);
      add(value.signature, context.slot, value.logs);
    }
  };
});
await ready;

// 2. Backfill: two pages, each one starting below the oldest signature of the last.
const back: Signature[] = [];
let before: Signature | undefined;
for (let page = 1; page <= 2; page++) {
  try {
    const list = await rpc.getSignaturesForAddress(program, { commitment, limit: PAGE, before }).send();
    back.push(...list.map((s) => s.signature));
    before = list.at(-1)?.signature;
  } catch (e) {
    console.log(`-- failed: page ${page} ${msg(e)}`);
    break;
  }
  if (!before) break;
}
const fetched = await Promise.allSettled(
  back.slice(0, FETCH).map(async (sig) => {
    const tx = await rpc.getTransaction(sig, { commitment, encoding: "json", maxSupportedTransactionVersion: 1 }).send();
    if (!tx) throw new Error(`no transaction for ${sig}`); // listed below the ledger floor
    add(sig, tx.slot, tx.meta?.logMessages ?? []);
  }),
);
for (const r of fetched) if (r.status === "rejected") console.log(`-- failed: ${msg(r.reason)}`);

// 3. Let the socket finish its window, then report.
await new Promise((r) => setTimeout(r, Math.max(0, WINDOW_MS - (Date.now() - started))));
ws.onclose = ws.onerror = null;
ws.close();
const overlap = back.filter((s) => liveSigs.has(s)).length;
console.log(`-- live ${liveSigs.size}, backfilled ${back.length}, overlap ${overlap}`);
if (!liveSigs.size) console.log(`-- socket silent${wsNote ? ` (${wsNote})` : ""}; backfill result only`);
console.log("create table if not exists program_logs (signature text primary key, slot bigint, logs jsonb);");
if (rows.length) console.log(`insert into program_logs (signature, slot, logs) values\n${rows.join(",\n")}\non conflict (signature) do nothing;`);
```

The socket and the listing both name `confirmed`, so a signature that one side sees can show up on the other. The socket stays open for 8 seconds, then closes. Everything the script prints is SQL or an SQL comment, so `node main.ts | psql -v ON_ERROR_STOP=1` applies it. The counts line is a comment with the live count, the backfilled count and the overlap count.

If the socket delivered nothing, the script prints a `-- socket silent` comment, with the reason when the subscription was refused, and still prints the backfill result. To check the key, save the output with `node main.ts > out.sql` and apply that file twice. The second apply reports `INSERT 0 0`. Running the command twice is no check on a busy program, because the newest signatures change between runs.

## What a run costs

A `logsSubscribe` with `mentions` costs 25 credits to open, then 20 credits per MiB sent. A refused subscription costs nothing. The listing costs 50 cells and each `getTransaction` costs [50 more](https://carbium.sh/docs/rpc), so the 2 listing pages and 3 transaction reads are 250 cells, inside the [1,024-cell burst](https://carbium.sh/docs/limits) every rate class absorbs.

A long backfill is limited by call rate. `getSignaturesForAddress` allows 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. `getTransaction` allows 0.24, 1.2, 5 and 25. One listing page gives you up to 1,000 signatures, and each of them needs a `getTransaction` call to get its logs, so the transaction reads set the pace. The live side costs by volume: a program that thousands of transactions mention sends a lot of MiB, so size the subscription from that. Limits and credits are per account, and Free carries 5 sockets.

## Where it ends

- History reaches back 30 days at most, the age of the address index. Older logs come from your own records.
- The script holds the socket for 8 seconds. A loader that runs for days keeps it open and reconnects. A dropped socket loses the notifications for the time it was down, and nothing replays them. After a reconnect, run the same handoff again: reopen the subscription first, then page back to the newest stored signature.
- A transaction that logs a lot has its messages cut short by the runtime, and the last entry reads `Log truncated`. Both sources return the cut text.
- A `mentions` filter matches transactions that name the program as an account, so the table also holds logs of other programs those transactions called.
- Failed transactions appear in both sources, and the script keeps them, since their logs say why they failed.
- The demo fetches logs for 3 signatures. It shows the handoff and the counts, and a complete history needs the full loop.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The table has a hole right after the switch from backfill to live. | The listing ran before the subscription was acknowledged. Open `logsSubscribe` first, wait for its reply, then page history. |
| The insert fails with a message that the command cannot affect a row a second time. | The statement uses `do update` and holds one signature twice. Use `on conflict (signature) do nothing`, or deduplicate the rows before building the statement. |
| A `-- failed:` comment shows error -32015 from `getTransaction`. | A [v1 transaction](https://carbium.sh/docs/rpc) was read without `maxSupportedTransactionVersion: 1`. Set it on every `getTransaction` call, as the script does. |
| A `-- failed:` comment says no transaction was found for a listed signature. | `getTransaction` answered null for an older signature that the [address index](https://carbium.sh/docs/migrate) still lists, since its pages reach below the ledger floor. Skip it or load it from your own records. |
| The output says `-- socket silent`. | Read the reason in brackets. A refused subscription means a [plan cap](https://carbium.sh/docs/websocket) such as the 5 sockets on Free is used up. With no reason, the program had no transactions during the 8 seconds, so pick a busier address or lengthen the window. |
| Paging back with `before` returns an empty page long before the history you expected. | The address index keeps up to 30 days, and an empty page past that marks its age limit. Load older logs from your own records. |

## Questions

### What does an overlap count of 0 mean?

Nothing landed on the program between the subscription's reply and the end of the listing. The order of the two sources prevents the gap, and the count only shows how many repeats the key absorbed.

### Can the backfill and the live writer run as separate processes?

Yes, with the table as the join point: start the live writer first, then run the backfill into the same table. Both insert with `do nothing`, so neither needs to know about the other.

### Why key on the signature and not the slot?

A signature names one transaction for good, and a slot read early can end up skipped when its fork is dropped. Keep `slot` as an indexed column for range reads and reloads.

### Where do I read how the socket behaves over time?

See [WebSocket keepalive and reconnect](https://carbium.sh/library/howsolana/websocket-keepalive-and-reconnect) for the reconnect loop, and the [WebSocket docs](https://carbium.sh/docs/websocket) for the notification fields and plan caps.

## Related

- [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) (How to use Solana, HS0034)
- [Postgres indexer slot checkpoints](https://carbium.sh/library/integrate/postgres-indexer-slot-checkpoints) (Integrations, I0047)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
