Architecture of the Ethereum indexer

A fault-tolerant pipeline that mirrors canonical chain data into PostgreSQL, built around idempotent ingest, reorg tolerance, and a single-writer model.

On this page

A fault-tolerant Ethereum indexer that mirrors canonical chain data — blocks, transactions, and logs — into PostgreSQL. It is designed around three properties: idempotent ingestion (safe to retry), reorg tolerance (roll back to a common ancestor and re-ingest), and single-writer coordination (one active daemon).

Overview

The indexer reads the chain, verifies lineage against the database head, and writes only the data that extends the canonical chain. The database is a mirror; the chain is the source of truth.

Monorepo layout

PackageResponsibility
@app/schemasZod schemas and inferred types: TransactionSchema, LogSchema, BlockDataSchema, CheckpointSchema.
@app/blockchainBlockchainClient (viem) and ReliableProviderManager for provider failover, health checks, and 429 throttling.
@app/db-coreIndexerDb with injected pg.Pool: inserts, saveBlock, rollbackState, head cursors, partition creation, and advisory locks.
@app/indexer-daemonLong-running poller: daemon.ts loop and index.ts bootstrap, lock acquisition, and signal handling.
@app/imuIndexer Management Utility for backfill and rollback.

Data flow

mermaid
RPC via viemBlockchainClient.fetchBlockDataDaemon lineage checkIndexerDb insertRows /bulkInsertPostgreSQL
View source
flowchart LR
  RPC[RPC via viem] --> C[BlockchainClient.fetchBlockData]
  C --> D[Daemon lineage check]
  D --> DB[IndexerDb insertRows / bulkInsert]
  DB --> PG[PostgreSQL]

A fetch returns block number, hash, parent hash, transactions, and logs. The daemon only writes it when parentHash matches the current database head.

Database schema

  • blocks(block_number PK, block_hash, parent_hash, created_at) — ancestry for reorg walk-back.
  • checkpoints(id PK = 'chain_head', block_number, block_hash, last_updated) — fast head cursor.
  • transactions(tx_hash, block_number, block_hash, transaction_index, from_address, to_address, amount NUMERIC, is_internal_call, ...) — primary key on (tx_hash, block_number), range-partitioned on block_number.
  • logs(block_number, block_hash, tx_hash, tx_index, log_index, address, data, topics TEXT[], ...) — primary key on (block_number, log_index), partitioned the same way.

Transactions and logs use 1M-block partitions, BRIN indexes on block_number, and B-tree indexes on address fields. Logs also have a GIN index on topics. Partitions are created on ingest as p{startM}m_{endM}m.

Precision

Block numbers remain bigint end-to-end and are serialized as strings at the Postgres boundary. Native value in wei is stored as NUMERIC and never passes through a JavaScript number.

Ingestion

  • insertRows uses parameterized per-row inserts for small batches.
  • bulkInsert uses COPY into a staging table, then one INSERT ... SELECT ... ON CONFLICT DO NOTHING.
  • COPY input is pushed in roughly 1 MB chunks, reducing protocol and socket overhead.
  • Checkpoint upserts and CREATE TABLE IF NOT EXISTS keep retries and overlapping ranges safe.

Everything is idempotent: ON CONFLICT DO NOTHING and upserts make the pipeline safe to rerun.

Concurrency & consistency

  • A session-scoped PostgreSQL advisory lock (pg_try_advisory_lock) ensures one active daemon per database.
  • Idempotent writes are the correctness backstop if coordination ever fails.
  • The daemon reads chainHead and dbHead independently and only acts when lineage agrees.
  • Serializable Snapshot Isolation is documented as a future optimistic alternative.
  • Foreign keys are deliberately not used.

Reorg handling

mermaid
yesnochainHead + dbHeadparentHash matches?Ingest blockRollback to commonancestor
View source
flowchart LR
  A[chainHead + dbHead] --> B{parentHash matches?}
  B -->|yes| D[Ingest block]
  B -->|no| E[Rollback to common ancestor]
  E --> D

On a mismatch, the fast path rolls back one block if the previous block is still canonical. Otherwise the indexer walks stored ancestry to find the common ancestor, deletes transactions, logs, and blocks above it, restores the checkpoint, and re-ingests.

Provider reliability

  • viem-native fallback with rank and retry across configured RPC providers.
  • Health check every HEALTH_CHECK_INTERVAL_MS (default 30s); a provider is stale if it fails or lags more than STALE_BLOCK_THRESHOLD (default 3) blocks.
  • HTTP 429/503 responses are detected through onFetchResponse and trigger a THROTTLE_COOLDOWN_MS cooldown (default 30s).
  • The fallback client is cached and rebuilt only when the active provider set changes.

Configuration

Env varPurpose
RPC_URLSComma-separated RPC endpoints.
DB_HOST / DB_PORT / DB_USER / DB_PASSWORD / DB_NAMEPostgreSQL connection.
DEBUG_RPC=1Verbose provider logging.
HEALTH_CHECK_INTERVAL_MSHealth-check cadence, default 30000.
STALE_BLOCK_THRESHOLDBlocks behind before a provider is stale, default 3.
THROTTLE_COOLDOWN_MS429/503 cooldown, default 30000.

.env is loaded explicitly from the repo root regardless of the current working directory.

Operations

  • Run from the repo root with Bun, for example bun run packages/indexer-daemon/src/index.ts.
  • Per-block logging reports indexed transactions and logs.
  • The 2s poll interval affects new-block detection latency, not ingest throughput.
  • Partitions are auto-created; retention is planned as partition drops.
  • One daemon per database, enforced by the advisory lock.

Future additions

Additional networks

The target set includes Ethereum mainnet, Polygon PoS, and Arbitrum. Adding chains means introducing a chain_id dimension (or a database per chain), parameterizing block time, partition size, poll interval, retention, and confirmation depth, and removing the mainnet assumption from the daemon.

Block time is the main sizing concern: mainnet is roughly 12s, Polygon roughly 2s, and Arbitrum roughly 0.25s. A 1M-block partition covers months on mainnet but only days on Arbitrum.

Token standards

Token indexing is a decoding layer over logs, not a second ingest path. It maps topic0 to an ABI and emits typed fields.

StandardSignatureNotes
ERC-20Transfer(address,address,uint256)Value is in data; normalize by decimals.
ERC-721Transfer(address,address,uint256)tokenId is indexed in topics[3].
ERC-1155TransferSingle / TransferBatchBatch events carry ids[] and values[].

Supporting pieces include a token registry (standard, symbol, decimals), a normalized token_transfers table across standards, and optional price feeds for USD views.

Whale-watch

Native transfers can already be filtered by exact NUMERIC amount. Token transfers require the registry and decimals normalization; USD views require price feeds.

Other

  • Retention and pruning by dropping old partitions.
  • Gap-tolerant reconcileFork.
  • WebSocket "poll now" triggers for sub-second detection.
  • Parallel backfills and sharded writers over disjoint ranges.

References

architecture_decisions.md (ADR-001…005), concurrency_model.md, referential_integrity.md, reorg_handling_design.md, indexer_schema.md.