Blockchain Data Indexing

Production engineering guide for blockchain data indexing in Web3 and blockchain systems.

Blockchain data indexing is the process of transforming raw blockchain data—blocks, transactions, logs, state changes—into a structured, queryable form tailored for applications. It matters when applications need fast, complex queries over blockchain history, such as a dApp dashboard showing user activity, a DeFi protocol tracking all positions, or a wallet service listing all token transfers. Without indexing, querying the blockchain directly via RPC is slow and expensive, especially for time-series and joined data.

Querying Historical Data

Applications often need to answer questions like "What were all the trades in the last 30 days?" or "Show me all users who made at least three swaps on Uniswap in the last week." These queries require scanning hundreds or thousands of blocks and parsing event logs across multiple contracts.

The standard approach uses a blockchain client (e.g., eth_getBlockByNumber, eth_getLogs) to retrieve raw data, then a local database to store and serve it. The key pattern is streaming and batch indexing, where a service listens to new blocks and processes them incrementally.

Start an indexer with indexer start

indexer start \
  --network mainnet \
  --rpc https://mainnet.infura.io/v3/abc123 \
  --db-url postgres://user:[email protected]:5432/indexer \
  --start-block 15000000 \
  --poll-interval 2s \
  --batch-size 100 \
  --contracts-file contracts.json \
  --workers 4

The contracts.json file defines which contracts to monitor and how to interpret their events:

[
  {
    "address": "0x1f98431c8ad98523631ae4a59f267346ea31f984",
    "name": "UniswapV2Pair",
    "events": [
      {
        "name": "Swap",
        "signature": "0xd78ad95fa46c994d8a250320414b188618b7e3c36031340139d18d0886d26391",
        "fields": [
          { "name": "sender", "type": "address", "indexed": true },
          { "name": "amount0In", "type": "uint256", "indexed": false },
          { "name": "amount1In", "type": "uint256", "indexed": false },
          { "name": "amount0Out", "type": "uint256", "indexed": false },
          { "name": "amount1Out", "type": "uint256", "indexed": false },
          { "name": "to", "type": "address", "indexed": true }
        ]
      }
    ]
  }
]

The indexer uses the signature field to decode event logs and inserts the decoded data into a swaps table in the database.

Indexer failure: missing events due to missing blocks

A common silent failure occurs when the indexer misses a block. The poll-interval determines how often the indexer checks for new blocks, but if the network is slow or the RPC provider is under load, blocks can be missed.

The error manifests as gaps in the block_number sequence in the blocks table. When the indexer restarts, it uses start-block to bootstrap, but after a restart, it reads the last processed block from a state table:

CREATE TABLE state (
  key TEXT PRIMARY KEY,
  value JSONB
);

INSERT INTO state (key, value) VALUES ('last-indexed-block', '{"block_number": 15000020, "timestamp": "2023-05-10T12:34:56Z"}');

If the state entry is not written atomically, the indexer may process the same block twice or skip a block. The most common cause is a crash during the indexing phase—the indexer fetches a block, processes its transactions and events, but fails before writing the updated last-indexed-block.

To detect this, query:

SELECT 
  b.number,
  b.timestamp,
  COUNT(e.id) AS event_count
FROM blocks b
LEFT JOIN events e ON b.number = e.block_number
WHERE b.number BETWEEN 15000000 AND 15000020
GROUP BY b.number, b.timestamp
ORDER BY b.number;

A missing block appears as a row with event_count = 0. The indexer can be configured to reindex from scratch after a gap:

reindex:
  enabled: true
  max-gap: 100
  strategy: "full"
  retry-after: 5m

When the gap exceeds max-gap, the indexer starts reprocessing from the first block in the gap, using eth_getBlockByNumber and eth_getLogs for each block.

Building a Queryable Schema

After indexing, data becomes available through a database. The schema must support fast, complex queries over time and relationships.

Define tables for common patterns

For a multi-contract dApp, define tables with normalized and denormalized forms:

CREATE TABLE accounts (
  id SERIAL PRIMARY KEY,
  address BYTEA NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE TABLE tokens (
  id SERIAL PRIMARY KEY,
  symbol TEXT,
  name TEXT,
  decimals INT,
  contract_address BYTEA NOT NULL UNIQUE,
  chain_id INT NOT NULL
);

CREATE TABLE balances (
  id SERIAL PRIMARY KEY,
  account_id INT REFERENCES accounts(id),
  token_id INT REFERENCES tokens(id),
  block_number BIGINT NOT NULL,
  amount NUMERIC(78, 18) NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  UNIQUE(account_id, token_id, block_number)
);

CREATE INDEX idx_balances_block_number ON balances(block_number);
CREATE INDEX idx_balances_account_token ON balances(account_id, token_id);
CREATE INDEX idx_balances_account_block ON balances(account_id, block_number);

The balances table is time-travelable: by querying balances at a given block_number, you reconstruct the state of all balances at that point.

To efficiently compute balances at a block, use a materialized view:

CREATE MATERIALIZED VIEW balance_snapshot AS
SELECT
  account_id,
  token_id,
  MAX(block_number) AS block_number,
  SUM(amount) AS balance
FROM balances
GROUP BY account_id, token_id;

CREATE INDEX idx_snapshot_account_token ON balance_snapshot(account_id, token_id);
CREATE INDEX idx_snapshot_block_number ON balance_snapshot(block_number);

Refresh the snapshot with a cron job:


0,15,30,45 * * * * psql -c 'REFRESH MATERIALIZED VIEW balance_snapshot'

Query patterns and performance

A common query is: "List all token transfers for a user in the last 7 days."

SELECT
  t.from_address,
  t.to_address,
  t.token_address,
  t.value,
  t.block_number,
  t.timestamp
FROM transfers t
JOIN accounts a ON t.from_address = a.address
WHERE a.address = '\x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b'
  AND t.timestamp >= NOW() - INTERVAL '7 days'
ORDER BY t.timestamp DESC
LIMIT 100;

The key performance bottleneck is indexing on timestamp and from_address. Without a composite index, this query scans the entire transfers table.

Use EXPLAIN ANALYZE to diagnose:

EXPLAIN ANALYZE
SELECT ... -- above query

Expected output:

Sort  (cost=15000.00..15050.00 rows=100 width=128)
  Sort Key: t.timestamp DESC
  ->  Bitmap Heap Scan on transfers t  (cost=10000.00..14500.00 rows=100 width=128)
        Recheck Cond: (timestamp >= '2023-05-03 12:00:00'::timestamp with time zone)
        Filter: (from_address = '0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b'::bytea)
        ->  Bitmap Index Scan on transfers_timestamp  (cost=0.00..1000.00 rows=100000 width=0)
              Index Cond: (timestamp >= '2023-05-03 12:00:00'::timestamp with time zone)

If the Bitmap Index Scan is missing, the query becomes slow. The fix is to add the index:

CREATE INDEX idx_transfers_from_timestamp ON transfers(from_address, timestamp);

Handling schema evolution

As the dApp evolves, new events and fields are added. The indexer must handle schema drift without breaking existing queries.

When a new event Deposit(address indexed, uint256 amount, uint256 fee) is added to a Vault contract, the indexer must:

  1. Read the event log with signature 0x9b7c163d8f1b4e2c5a6e7b8c9d0e1f2a3b4c5d6e7a8b9c0d1e2f3a4b5c6d7e8f
  2. Parse the amount and fee fields
  3. Insert into a new deposits table, or append to events with metadata

The events table schema should be flexible:

CREATE TABLE events (
  id SERIAL PRIMARY KEY,
  contract_address BYTEA NOT NULL,
  event_signature BYTEA NOT NULL,
  block_number BIGINT NOT NULL,
  transaction_hash BYTEA NOT NULL,
  log_index INT NOT NULL,
  data JSONB NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  UNIQUE(contract_address, block_number, log_index)
);

CREATE INDEX idx_events_signature ON events(event_signature);
CREATE INDEX idx_events_block_number ON events(block_number);
CREATE INDEX idx_events_contract_block ON events(contract_address, block_number);

The data column stores the decoded event values as a JSON object, enabling ad-hoc queries:

SELECT
  e.data->>'amount' AS amount,
  e.data->>'fee' AS fee,
  e.created_at
FROM events e
WHERE e.contract_address = '\x0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b'
  AND e.event_signature = '\x9b7c163d8f1b4e2c5a6e7b8c9d0e1f2a3b4c5d6e7a8b9c0d1e2f3a4b5c6d7e8f'
ORDER BY e.block_number DESC
LIMIT 10;

Handling reorgs

Blockchain reorganizations (reorgs) are a silent failure mode. When a new block is added, the chain may reorganize, shifting the canonical path. The indexer must detect and handle reorgs to keep data consistent.

The indexer tracks the canonical chain using a canonical_blocks table:

CREATE TABLE canonical_blocks (
  block_number BIGINT PRIMARY KEY,
  block_hash BYTEA NOT NULL,
  parent_hash BYTEA NOT NULL,
  timestamp TIMESTAMPTZ NOT NULL,
  difficulty NUMERIC(78, 18),
  total_difficulty NUMERIC(78, 18)
);

After processing a new block, the indexer updates canonical_blocks and checks for reorgs:

-- Check if the last 10 blocks are canonical
WITH recent AS (
  SELECT block_number, block_hash, parent_hash
  FROM canonical_blocks
  ORDER BY block_number DESC
  LIMIT 10
)
SELECT
  r1.block_number,
  r1.block_hash,
  r1.parent_hash,
  r2.block_number AS prev_block,
  r2.block_hash AS prev_hash
FROM recent r1
JOIN recent r2 ON r1.block_number = r2.block_number + 1
WHERE r1.parent_hash != r2.block_hash;

If the parent_hash does not match, a reorg has occurred. The indexer must:

  1. Identify the reorg depth (how many blocks changed)
  2. Mark all blocks in the reorg range as non-canonical
  3. Update all tables (e.g., balances, events) to reflect the new state
  4. Trigger a reindexing job for the affected blocks

The reindexing job can be implemented as a background task:

indexer reindex \
  --from-block 15000100 \
  --to-block 15000150 \
  --mode "reorg"

During reorg handling, the indexer must ensure idempotency: reprocessing the same block does not cause duplicate data.

Synchronizing Indexers and Clients

Indexers are not standalone; they serve applications via APIs. A common pattern is to expose a GraphQL API over the indexed data.

GraphQL schema for common queries

type Query {
  account(address: Bytes!): Account
  accountHistory(address: Bytes!, fromBlock: Int, toBlock: Int): [Event]
  tokenTransfers(token: Bytes!, fromBlock: Int, toBlock: Int): [Transfer]
  balanceAt(account: Bytes!, blockNumber: Int!): Balance
}

type Account {
  address: Bytes!
  created: DateTime!
  transactions: [Transaction!]!
  balances: [Balance!]!
}

type Balance {
  token: Token!
  amount: String!
  blockNumber: Int!
}

Clients call:

query {
  account(address: "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b") {
    address
    created
    balances {
      token {
        symbol
        name
      }
      amount
      blockNumber
    }
  }
}

The response includes the account’s balance history, with each balance tied to a block number. The client can use blockNumber to reconstruct the state at any point.

Indexer health and monitoring

The indexer service must report its health via HTTP endpoints. The /health endpoint returns:

{
  "status": "healthy",
  "lastIndexedBlock": 15000020,
  "lastProcessedBlock": 15000020,
  "lag": 12.3,
  "reorgsDetected": 2,
  "errors": [
    {
      "timestamp": "2023-05-10T12:34:56Z",
      "message": "Failed to process block 15000015: RPC error: 503 Service Unavailable",
      "blockNumber": 15000015
    }
  ]
}

The lag is the difference between the latest block on the chain and the block the indexer has processed. A high lag indicates RPC or database bottlenecks.

Use curl to monitor:

curl -s http://indexer.example.com/health | jq '.lag'

A lag > 30 seconds triggers an alert. The indexer also logs to stdout in JSON format:

{
  "timestamp": "2023-05-10T12:34:56.123Z",
  "level": "info",
  "message": "Processing block 15000010",
  "blockNumber": 15000010,
  "durationMs": 124,
  "events": 47,
  "transactions": 15
}

This log enables tracing from a single block through the entire indexing pipeline.

Summary

Blockchain data indexing transforms raw blockchain data into a performant, structured dataset. It requires careful design of the data schema, robust handling of reorgs and gaps, and consistent monitoring. The indexer is not a one-off service but a continuous, fault-tolerant pipeline that must survive network outages, RPC failures, and schema changes. The result is a system where dApps can answer complex, time-based questions over blockchain state with low latency and high availability.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.