---
id: I0124
title: "Airflow block-by-block ingest"
url: https://carbium.sh/library/integrate/airflow-block-by-block-ingest
collection: Integrations
category: Data warehouses
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Airflow block-by-block ingest

A Node script for an Airflow BashOperator reads a bounded range of finalized slots, writes one NDJSON line per slot, and prints the last slot it finished. Airflow keeps the cursor, so a retry rewrites the same file and a warehouse loader picks it up.

## One slot range per task run

An Airflow DAG that ingests Solana block by block needs a task that does a bounded amount of work and says exactly where it stopped. This task reads a run of consecutive slots from Carbium RPC, writes one line per slot to a newline-delimited JSON file and prints the last slot it finished as its final line of output. Airflow's `BashOperator` pushes the last line of stdout to XCom, so the next task and the next run can pick it up.

A slot lasts about 200 ms, so a schedule of five minutes leaves roughly 1,500 slots between two runs. The script reads up to `BLOCK_COUNT` of them, 5 by default, starting at `START_SLOT`. With no `START_SLOT` it reads the newest `BLOCK_COUNT` finalized slots, so a first run and a test run need no setup. In production, set `BLOCK_COUNT` above that gap, for example 2,000 on a five-minute schedule, so each run reads its whole interval and gains on the tip after a pause. With a smaller value the cursor falls further behind on every run.

## The cursor lives in Airflow

The script holds no state. An Airflow Variable named `next_slot` carries the first slot the next run should read. The ingest task is a `BashOperator` with the command `START_SLOT={{ var.value.get("next_slot", "") }} node main.ts`. An empty Variable gives an empty `START_SLOT`, and the script falls back to the newest slots.

A second `BashOperator` runs after the ingest task and moves the cursor: `airflow variables set next_slot $(( {{ ti.xcom_pull(task_ids="ingest") }} + 1 ))`. It only runs when the ingest task succeeded, so a failed ingest leaves the Variable alone. Once the Variable holds a slot, the retry reads the same range again and, because the file name comes from the range, writes the same file over itself.

Set `max_active_runs=1` and `catchup=False` on the DAG. Only one run then holds the cursor at a time, and a long pause produces a single run that starts from the cursor instead of one run per missed interval.

## Reading the range in slot order

The script finds the tip with `getSlot` at `finalized`, a [cheap cached read](https://carbium.sh/docs/rpc) at 1 cell, and caps the range there. Every call names `finalized`, because @solana/kit sends `confirmed` for a call that leaves commitment out. [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) covers the three levels.

Blocks are fetched in waves of four `getBlock` calls with `transactionDetails: "signatures"`, and each wave is settled together with `Promise.allSettled`. The script then walks the wave in slot order and adds a line per slot until the first failure. Everything after the failed slot is dropped, even a block that arrived, so the file always holds a contiguous range and the printed last slot is true.

`getBlock` also takes `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and with that value absent or 0 the call [answers -32015](https://carbium.sh/docs/rpc) for a block holding one, which would stop the task at the first such block.

A slot whose leader produced no block answers -32007, or -32009 when the request reaches long-term storage. The script writes `{"slot":N,"skipped":true}` for those and moves on. A skipped slot belongs in the file, so a loader can tell it from a slot nobody read.

## The NDJSON file

Each run writes `blocks-<first>-<last>.ndjson`, with one JSON object per line.

| Field | Content |
|---|---|
| `slot` | The slot number |
| `blockhash` | The block's hash, absent on a skipped slot |
| `parent_slot` | The slot the block builds on |
| `block_time` | Unix seconds, or null when the node has none |
| `signatures` | Every transaction signature in the block, in block order |
| `skipped` | `true` on a slot that produced no block, with no other fields |

The script writes `blocks-<first>-<last>.ndjson.tmp` first and renames it, so a loader that matches `*.ndjson` never sees a half-written file. A warehouse load task, for example a `COPY` or a bulk load into a staging table, can run on every new file, and loading the same file twice is harmless when the slot is the key.

> Mainnet blocks carry no vote transactions since Alpenglow, so the signature lists hold only the other transactions.

The file lists signatures and no transaction bodies. A `getTransaction` call costs 50 cells, so turning the signatures of a block that holds 1,000 transactions into bodies costs 50,000 cells. Fetch bodies in a separate task you can size on its own.

## The task script

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 script needs `CARBIUM_KEY` in the Airflow worker's environment and exits with a message when it is unset. `CARBIUM_RPC_URL` is optional. The output goes to the working directory, so point the task there. On the chain side it only reads.

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

```ts
// I0124 · Airflow block-by-block ingest
// https://carbium.sh/library/integrate/airflow-block-by-block-ingest
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { renameSync, writeFileSync } from "node:fs";
import {
  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";

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 count = BigInt(process.env.BLOCK_COUNT ?? "5");
const wave = 4n;

const read = async (slot: bigint) => {
  try {
    const b = await rpc
      .getBlock(slot as Slot, { commitment, transactionDetails: "signatures", rewards: false, maxSupportedTransactionVersion: 1 })
      .send();
    if (!b) throw new Error("block not available");
    return {
      slot: Number(slot),
      blockhash: b.blockhash,
      parent_slot: Number(b.parentSlot),
      block_time: b.blockTime === null ? null : Number(b.blockTime),
      signatures: b.signatures,
    };
  } 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)) {
      return { slot: Number(slot), skipped: true }; // no block was produced
    }
    throw e;
  }
};

try {
  const tip = await rpc.getSlot({ commitment }).send();
  const start = process.env.START_SLOT ? BigInt(process.env.START_SLOT) : tip - count + 1n;
  const end = start + count - 1n < tip ? start + count - 1n : tip;
  const lines: string[] = [];
  let last = start - 1n;
  let failed = "";
  for (let s = start; s <= end && !failed; s += wave) {
    const slots: bigint[] = [];
    for (let i = s; i < s + wave && i <= end; i++) slots.push(i);
    const done = await Promise.allSettled(slots.map(read));
    for (const [i, r] of done.entries()) {
      if (r.status === "rejected") {
        failed = `slot ${slots[i]}: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
        break; // drop everything after the first failure: the file stays contiguous
      }
      lines.push(JSON.stringify(r.value));
      last = slots[i]!;
    }
  }
  if (lines.length) {
    const name = `blocks-${start}-${last}.ndjson`;
    writeFileSync(`${name}.tmp`, lines.join("\n") + "\n");
    renameSync(`${name}.tmp`, name); // a loader never sees a half file
    console.log(`wrote ${name}`);
  }
  if (failed) console.error(`stopped at ${failed}`);
  if (failed && !lines.length) process.exit(1);
  console.log(`blocks read: ${lines.length}`);
  console.log(String(last)); // last line of stdout: Airflow pushes it to XCom
} catch (e) {
  console.error(`run failed: ${e instanceof Error ? e.message : String(e)}`);
  process.exitCode = 1;
}
```

A run with no `START_SLOT` prints the file name, `blocks read: 5` and the last slot. Run it with `START_SLOT` set to that last slot plus one, and it continues from there with no gap and no overlap.

## Where it ends

- It reads the finalized tip and walks forward. A `START_SLOT` far in the past works as far as `getBlock` still answers, and the script stops at the first slot that fails. It does not check how far back that reaches.
- One slot range at a time. Two runs with the same `START_SLOT` write the same file name, and the rename makes the later one win. The data stays the same, and the calls are spent twice.
- Waves of four are a fixed choice. A key on a low plan can spend its budget quickly, and [limits are per account](https://carbium.sh/docs/limits), so every key of the account draws on the same budget as this task.
- The file carries signatures only. Instructions, token balances and logs need `getTransaction`, and a block that holds many transactions makes that a larger job than the block read.
- A run that fails on its first slot exits with code 1 and writes nothing, so Airflow's retry decides what happens next. A run that fails later exits 0 with the slots it did read, and the next run picks up at the failed slot.
- The slot is the key. A warehouse table that keeps slot and signature as a composite key accepts a re-run without duplicates. See [Postgres indexer slot checkpoints](https://carbium.sh/library/integrate/postgres-indexer-slot-checkpoints) for the same idea with the cursor in the database.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The task stops on a block that holds a v1 transaction with error -32015. | Pass `maxSupportedTransactionVersion: 1` in the `getBlock` options. Absent or 0, a block holding a v1 transaction answers -32015. |
| The run exits with code 1 and prints `stopped at slot N` with no file written. | The first slot of the range failed. The Variable is unchanged, so Airflow's retry reads the same range. Read the message for the cause, and lower `BLOCK_COUNT` if the account's budget was spent. |
| The same slots appear in two files. | Two runs held the same cursor. Set `max_active_runs=1` on the DAG and move the Variable in a task that depends on the ingest task. |
| A loader reads a file that stops in the middle of a line. | The loader matched the temporary file. Match `*.ndjson` only. The script renames the file when it is complete. |
| The run prints `blocks read: 0` and the cursor does not move. | `START_SLOT` is ahead of the finalized tip, so there is nothing to read yet. The printed last slot is one below `START_SLOT`, and the next run starts at the same slot. |

## Questions

### Why one task per range and not one task per slot?

A slot lasts about 200 ms, so a task per slot asks the Airflow scheduler to track about five tasks a second. A range per run keeps the task count flat and lets the script settle a wave of reads at once.

### Why read finalized and not processed?

A finalized block is not dropped with a fork, so a line never needs correcting later. Since Alpenglow, finalized sits 0 to 1 slots behind processed, so the tip is current.

### Can the script run outside Airflow?

Yes. It keeps no state, so a cron job or a shell loop can run it by passing `START_SLOT` from the last printed slot plus one.

### How do I get the transactions themselves?

Read the signatures from each file in a later task and call `getTransaction` with `maxSupportedTransactionVersion: 1` for them. The call can answer null, so handle that in the loader.

## Related

- [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) (How to use Solana, HS0003)
- [Postgres indexer slot checkpoints](https://carbium.sh/library/integrate/postgres-indexer-slot-checkpoints) (Integrations, I0047)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
