---
id: I0123
title: "Athena SQL over Parquet blocks"
url: https://carbium.sh/library/integrate/athena-sql-over-parquet-blocks
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
---

# Athena SQL over Parquet blocks

A Node script reads the newest blocks from Carbium RPC and writes one JSON Lines row per block. Athena maps the file in S3, a CTAS statement rewrites it as Parquet, and you query slots, block times and transaction counts with plain SQL.

## What one run writes

Athena reads its tables from files in S3, so the end product of this job is a file in a bucket. The script pulls the newest blocks over Carbium RPC and appends one JSON object per block to `blocks.jsonl`. You upload that file, define an Athena table over it, and a single `CREATE TABLE AS SELECT` produces the Parquet copy. After that, queries read compressed columns.

Node has no built-in Parquet writer, and the script stays on `@solana/kit` plus built-ins. Athena writes the Parquet itself, and you pick the column types and the compression in SQL.

1. Read the current slot with `getSlot` and take the slots just below it.
2. Fetch each block with `getBlock`, asking for signatures only, all calls started together.
3. Count the signatures per block and write one row per block that exists.
4. Print a summary with the rows written and the slots that had no block.

| Field | Holds |
|---|---|
| slot | The slot the block was produced in. |
| parent_slot | The slot of the block it builds on. A gap to `slot` is a skipped slot. |
| block_height | The block's height. Null when the node leaves it out. |
| block_time | Unix seconds of the block. Null when the node has no time for it. |
| blockhash | The block's hash, base58. |
| tx_count | The number of transactions in the block. |

## The Carbium calls

`getSlot` gives the tip, and the script takes the slots just below it, oldest first. `getBlock` runs with `transactionDetails: "signatures"` and `rewards: false`, so an answer carries a list of signatures and no transaction bodies. `tx_count` is the length of that list. The script sets no commitment, so @solana/kit fills in `confirmed` for both methods.

Requests go to the [RPC endpoint](https://carbium.sh/docs/endpoints), and the key travels in the `x-api-key` [request header](https://carbium.sh/docs/auth). `getBlock` also carries `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and without that setting a block holding one comes back as -32015.

Mainnet blocks carry no vote transactions since the Alpenglow switch, so `tx_count` counts user and program transactions only. A slot has no block when its leader produced nothing. `getBlock` rejects that slot, the script counts it as skipped and prints the reason, and the `slot` column shows the hole.

## The Athena table over the raw file

Copy the file to a prefix of its own, for example `aws s3 cp blocks.jsonl s3://your-bucket/solana/blocks_raw/`. Then create a table over that prefix in the Athena console or with `aws athena start-query-execution`.

`CREATE EXTERNAL TABLE blocks_raw (slot bigint, parent_slot bigint, block_height bigint, block_time bigint, blockhash string, tx_count int) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' LOCATION 's3://your-bucket/solana/blocks_raw/';`

The JSON SerDe wants one object per line with keys that match the column names. The script writes exactly that. Slots and block heights stay far below 2^53, so a JavaScript number holds them exactly and `bigint` columns in Athena read them without loss.

A quick check before the rewrite: `SELECT slot, tx_count, from_unixtime(block_time) FROM blocks_raw ORDER BY slot DESC LIMIT 10;` should show the slots the script printed.

## Rewriting it as Parquet

One statement converts the raw table. The target prefix must be empty, so each conversion gets a fresh `external_location`.

`CREATE TABLE blocks WITH (format = 'PARQUET', parquet_compression = 'SNAPPY', external_location = 's3://your-bucket/solana/blocks/') AS SELECT slot, parent_slot, block_height, block_time, CAST(from_unixtime(block_time) AS timestamp) AS block_ts, blockhash, tx_count FROM blocks_raw;`

- `SELECT date(block_ts) AS day, count(*) AS blocks, sum(tx_count) AS txs FROM blocks GROUP BY 1 ORDER BY 1;` counts blocks and transactions per day.
- `SELECT slot, slot - lag(slot) OVER (ORDER BY slot) AS step FROM blocks ORDER BY slot;` lists the steps between stored slots. Any step above 1 is a skipped slot or a block that was never loaded.
- `SELECT max(tx_count), avg(tx_count) FROM blocks;` sizes the busiest block against the average.

Athena bills by the data a query scans. Parquet stores each column separately, so a query on `slot` and `tx_count` skips `blockhash` entirely. To skip whole files as well, add `partitioned_by = ARRAY['day']` to the CTAS and select the day as the last column. Partitions then prune by date.

> A second load of new blocks goes into a new raw prefix and a new CTAS target, or into `INSERT INTO blocks SELECT ...` on the existing Parquet table. Do not copy a file into the Parquet prefix by hand.

## The script and how to run it

Install with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types when it loads the file. `CARBIUM_KEY` is required, and the script exits with a message when it is unset. `CARBIUM_RPC_URL` is optional and defaults to `https://services.carbium.sh`. The one argument is how many blocks to read, 10 by default.

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

```ts
// I0123 · Athena SQL over Parquet blocks
// https://carbium.sh/library/integrate/athena-sql-over-parquet-blocks
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { writeFileSync } from "node:fs";
import { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const count = Number(process.argv[2] ?? 10);
const OUT_FILE = "blocks.jsonl";

const transport = createDefaultRpcTransport({
  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
  headers: { "x-api-key": key },
});
const rpc = createSolanaRpcFromTransport(transport);

interface Row {
  slot: number;
  parent_slot: number;
  block_height: number | null;
  block_time: number | null;
  blockhash: string;
  tx_count: number;
}
type Result = { slot: bigint; row?: Row; reason?: string };

const orNull = (v: bigint | number | null): number | null => (v === null ? null : Number(v));

// One slot in, one result out: a row, an empty slot, or the failure reason.
async function fetchOne(slot: bigint): Promise<Result> {
  try {
    const b = await rpc
      .getBlock(slot, { transactionDetails: "signatures", rewards: false, maxSupportedTransactionVersion: 1 })
      .send();
    if (b === null) return { slot, reason: "no block" };
    const row: Row = {
      slot: Number(slot),
      parent_slot: Number(b.parentSlot),
      block_height: orNull(b.blockHeight),
      block_time: orNull(b.blockTime),
      blockhash: b.blockhash,
      tx_count: b.signatures.length,
    };
    return { slot, row };
  } catch (err) {
    return { slot, reason: (err as Error).message };
  }
}

const tip = await rpc.getSlot().send();
const slots = Array.from({ length: count }, (_, i) => tip - BigInt(count - i));
const results = await Promise.all(slots.map(fetchOne));

const rows = results.flatMap((r) => (r.row ? [r.row] : []));
const failed = results.filter((r) => !r.row);
for (const f of failed) {
  if (f.reason !== "no block") console.error(`slot ${f.slot} skipped: ${f.reason}`);
}

// JSON Lines, oldest slot first: one object per line for Athena's JSON SerDe.
const text = rows.map((r) => `${JSON.stringify(r)}\n`).join("");
writeFileSync(OUT_FILE, text);
console.log(`tip ${tip}: ${rows.length} rows in ${OUT_FILE}, ${failed.length} skipped`);
text.split("\n").slice(0, 2).filter(Boolean).forEach((l) => console.log(l));
```

A run prints one summary line with the tip slot, the rows written and the skipped slots, then the first two rows. Each row's `slot` can be looked up in a block explorer to confirm the hash and the transaction count.

## How much one run can read

A slot lasts about 200 ms since the Alpenglow switch, so a day holds about 432,000 slots and a run of 10 blocks covers about two seconds of chain time. [Slot to timestamp conversion](https://carbium.sh/library/howsolana/slot-to-timestamp-conversion) shows how `block_time` maps back to a slot when you need a block for a given moment.

Each block is its own `getBlock` call, and all of them start together, so a large count can hit the 429 limit with a `retry-after` hint. Every key on the account draws on [one shared budget](https://carbium.sh/docs/limits). The script settles each call on its own, so a 429 on one slot prints a failure line and the other rows still land. Raise the count in steps and watch for those lines.

## Where it ends

- The script writes JSON Lines. The Parquet comes from the Athena CTAS, and the S3 upload and the SQL are yours to run.
- It reads the newest blocks. A bulk history of a whole day or a week means many runs, and a loader that walks slots and keeps its place between runs is a separate job ([BigQuery chain dataset](https://carbium.sh/library/integrate/bigquery-chain-dataset) shows the same shape for another warehouse).
- A skipped slot leaves no row, and a rejected call for a slot that does have a block looks the same in the file. The printed reasons tell them apart.
- `tx_count` counts transactions. Instruction contents, token movements and logs are not in these rows, and `signatures` mode returns no transaction bodies.
- The script keeps no state and rewrites `blocks.jsonl` on every run. Two overlapping runs uploaded under different names put the same slots in S3 twice, and since the repeated rows are identical, `SELECT DISTINCT` removes them before you trust a count.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The run exits with `Set CARBIUM_KEY to your Carbium API key.` | Export `CARBIUM_KEY` in the shell that runs `node main.ts`. A cron job or a container needs the variable in its own environment. |
| Lines print `skipped` with a -32015 error. | The `maxSupportedTransactionVersion: 1` setting is missing or set to 0 in the `getBlock` call. Restore it so blocks holding a v1 transaction resolve. |
| A call fails with HTTP 401. | Carbium does not know the key it received and answers with a [401 error](https://carbium.sh/docs/errors), `UNKNOWN_KEY`. Set `CARBIUM_KEY` to the whole key with nothing cut off, and check that `CARBIUM_RPC_URL` is unset or points at Carbium. |
| Several slots print a 429 failure and the file holds fewer rows than the count. | Lower the count or space the runs out. A 429 carries a `retry-after` hint, and other keys on the account share the budget. |
| Athena returns rows where every column is NULL. | The SerDe could not match keys to columns or could not parse a line. Check that the file holds one object per line and that the column names in the DDL equal the keys, which are snake case. |
| The CTAS fails because the external location is not empty. | Athena writes Parquet only to an empty prefix. Choose a new `external_location`, or load further blocks with `INSERT INTO` on the existing table. |

## Questions

### Why does the script write JSON Lines and not Parquet?

A Parquet writer needs a library, and this script stays on `@solana/kit` plus Node built-ins. Athena reads JSON Lines natively and its CTAS statement writes the Parquet for you.

### Why ask `getBlock` for signatures only?

The answer stays small, and a row per block needs only the count. A job that wants one row per transaction asks for full transactions, which returns far more data per call.

### Can I load a whole day of blocks with this?

A day holds about 432,000 slots and each needs its own call, so it takes many runs spread over your rate. Start with a count that fits your plan, then add a loop that remembers the last slot it wrote.

### Why is `block_time` sometimes null?

The node has no time recorded for some blocks. The script writes null and Athena reads it as NULL, so wrap the column in `coalesce` or filter it out in queries that group by day.

## Related

- [Slot to timestamp conversion](https://carbium.sh/library/howsolana/slot-to-timestamp-conversion) (How to use Solana, HS0062)
- [BigQuery chain dataset](https://carbium.sh/library/integrate/bigquery-chain-dataset) (Integrations, I0012)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
