An indexer reads blocks, transactions and event logs from a chain, transforms them, and stores the result in a database you can query, because a node's JSON-RPC API can only answer narrow questions such as "what is this balance now" or "which logs match this filter in this block range". The Graph gives you a hosted, declarative way to do that: you write a subgraph (a manifest of contracts and events, a GraphQL schema and AssemblyScript handlers), deploy it, and query it with GraphQL. A custom indexer is your own service that pulls logs over RPC (or uses a framework such as Ponder, Envio or SQD) and writes to Postgres or similar. Choose The Graph when event-driven data and GraphQL fit and you don't want to run infrastructure; build your own when you need SQL, joins with off-chain data, very low latency, chains The Graph doesn't support, or full control over correctness and cost.
Why can't I just query the node?
A node is optimised to execute and validate blocks, not to answer application questions. "All transfers to this address, newest first, with USD value at the time" needs:
- scanning history with
eth_getLogs, which most providers cap by block range or result count; - decoding and joining logs from several contracts;
- aggregating (balances, volumes, positions) across millions of events;
- pagination, sorting and filtering that RPC has no concept of.
Doing that live on every page load is slow and expensive. An indexer does it once, incrementally, and keeps the answer in a database. The shape of the work is always the same: backfill history from a start block, then follow the tip, while coping with reorgs and restarts.
How does a subgraph work?
A subgraph has three parts. The manifest says which contracts and events to watch on which network:
# subgraph.yaml
specVersion: 1.3.0
schema:
file: ./schema.graphql
indexerHints:
prune: auto
dataSources:
- kind: ethereum/contract
name: Token
network: mainnet
source:
address: "0xYourTokenAddress"
abi: Token
startBlock: 19000000 # the block the contract was deployed in
mapping:
kind: ethereum/events
apiVersion: 0.0.9
language: wasm/assemblyscript
entities: [Transfer, Account]
abis:
- name: Token
file: ./abis/Token.json
eventHandlers:
- event: Transfer(indexed address,indexed address,uint256)
handler: handleTransfer
file: ./src/mapping.ts
The schema defines the entities you'll query. Mark append-only records as immutable, which makes indexing faster:
type Transfer @entity(immutable: true) {
id: Bytes!
from: Bytes!
to: Bytes!
value: BigInt!
blockNumber: BigInt!
txHash: Bytes!
}
type Account @entity {
id: Bytes!
balance: BigInt!
}
The mappings are AssemblyScript handlers that run once per matching event and save entities:
import { Address, BigInt, Bytes } from "@graphprotocol/graph-ts";
import { Transfer as TransferEvent } from "../generated/Token/Token";
import { Account, Transfer } from "../generated/schema";
export function handleTransfer(event: TransferEvent): void {
const t = new Transfer(event.transaction.hash.concatI32(event.logIndex.toI32()));
t.from = event.params.from;
t.to = event.params.to;
t.value = event.params.value;
t.blockNumber = event.block.number;
t.txHash = event.transaction.hash;
t.save();
if (!event.params.from.equals(Address.zero())) {
const sender = loadAccount(event.params.from);
sender.balance = sender.balance.minus(event.params.value);
sender.save();
}
const receiver = loadAccount(event.params.to);
receiver.balance = receiver.balance.plus(event.params.value);
receiver.save();
}
function loadAccount(id: Bytes): Account {
let account = Account.load(id);
if (account == null) {
account = new Account(id);
account.balance = BigInt.zero();
}
return account as Account;
}
Then build and deploy with the Graph CLI:
npm install -g @graphprotocol/graph-cli@latest
graph init # scaffolds from a contract address and ABI
graph codegen && graph build
graph auth <DEPLOY_KEY>
graph deploy <SUBGRAPH_SLUG> # to Subgraph Studio (development, rate-limited)
Studio deployments are for development. Publishing to The Graph Network (from Studio or with graph publish, which defaults to Arbitrum One) lets independent indexers serve it, with queries paid in GRT after a free monthly allowance. Queries look like this, and _meta tells you how far the subgraph has indexed:
{
transfers(first: 10, orderBy: blockNumber, orderDirection: desc,
where: { to: "0xabc0000000000000000000000000000000000000" }) {
from
value
txHash
}
_meta { block { number } hasIndexingErrors }
}
Graph Node handles reorgs for you by reverting entity changes from orphaned blocks. For contracts created by a factory, use data source templates so new child contracts are indexed as they appear. For very high-throughput chains or heavy backfills, Substreams run parallelised Rust modules over block data and can feed a subgraph or a SQL database.
Subgraph pitfalls
- Handlers must be deterministic. No network calls, no randomness, no wall-clock time. Contract calls from a mapping (
eth_callvia generated bindings) are allowed but slow indexing considerably; prefer data in events. - Set
startBlock. Without it, indexing scans from genesis. - Proxies and ABI changes. Index the proxy address with the implementation's ABI, and include events from every implementation version. How upgradeable proxies work explains why the address and ABI live in different places. A verified contract on an explorer is the easiest source for the ABI; see how to verify a contract on Etherscan.
- Block handlers are expensive. Prefer event handlers, or add a filter.
- Use
BigIntandBigDecimal, and apply token decimals only for display.
How do I build a custom indexer?
A minimal custom indexer for Ethereum or any EVM chain has four parts: a cursor (last processed block), a backfill loop over finalised history, a tip follower that handles reorgs, and idempotent writes. Here is the backfill half with viem and Postgres:
import { createPublicClient, http, parseAbiItem } from "viem";
import { mainnet } from "viem/chains";
import pg from "pg";
const client = createPublicClient({ chain: mainnet, transport: http(process.env.RPC_URL) });
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const TOKEN = "0xYourTokenAddress";
const transferEvent = parseAbiItem("event Transfer(address indexed from, address indexed to, uint256 value)");
export async function backfill(fromBlock: bigint, step = 2_000n) {
const { number: finalized } = await client.getBlock({ blockTag: "finalized" });
for (let start = fromBlock; start <= finalized; start += step) {
const end = start + step - 1n < finalized ? start + step - 1n : finalized;
const logs = await client.getLogs({ address: TOKEN, event: transferEvent, fromBlock: start, toBlock: end });
const conn = await db.connect();
try {
await conn.query("BEGIN");
for (const log of logs) {
await conn.query(
`INSERT INTO transfers (chain_id, block_number, block_hash, tx_hash, log_index, sender, recipient, value)
VALUES (1, $1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (chain_id, tx_hash, log_index) DO NOTHING`,
[log.blockNumber.toString(), log.blockHash, log.transactionHash, log.logIndex,
log.args.from, log.args.to, log.args.value!.toString()],
);
}
await conn.query("UPDATE cursors SET last_block = $1 WHERE name = 'transfers'", [end.toString()]);
await conn.query("COMMIT");
} catch (err) {
await conn.query("ROLLBACK");
throw err;
} finally {
conn.release();
}
}
}
Three design choices make this safe to restart and re-run:
- Backfill only up to
finalized. Everything below that block won't change, so it can be written without reorg tracking. - Natural unique keys.
(chain_id, tx_hash, log_index)identifies a log, so replays are no-ops. Storeuint256values asNUMERIC, never as floats. - Data and cursor in one database transaction. A crash can't leave events without the cursor update or the reverse.
Above the finalised block you need hash tracking and rollback, which handling chain reorgs in an indexer covers step by step, along with when to trust safe versus finalized; how many confirmations to wait for has the per-chain view.
Practical limits to plan for
- Provider caps on
eth_getLogs. Many RPC providers limit the block range or return an error when a query matches too many logs (commonly around 10,000 results). Halve the range and retry when that happens, and grow it again when results are sparse. - Rate limits and archive access. Backfills need historical state only if you make
eth_calls at past blocks; logs alone usually work on full nodes, but check your provider. - Throughput. Fetch ranges concurrently but commit in order, and batch inserts rather than writing one row at a time.
- Non-EVM chains need different primitives: Solana indexers read transactions and account updates (often via Geyser or gRPC streams), and on chains with asynchronous messaging like TON's message model you index traces, not single transactions.
Frameworks such as Ponder (TypeScript, Postgres, viem-based), Envio HyperIndex and SQD give you this skeleton: config-driven contracts, typed handlers, reorg handling and a GraphQL or SQL API. They're a middle ground: your own database and deployment without writing the plumbing.
Which approach should I choose?
| The Graph (subgraph) | Indexing framework | Fully custom | |
|---|---|---|---|
| You write | Manifest, schema, AssemblyScript handlers | TypeScript handlers, schema | Everything |
| Hosting | Studio or decentralised network | Your servers | Your servers |
| Query interface | GraphQL | GraphQL and/or SQL | Whatever you build |
| Reorg handling | Built in | Built in | Your responsibility |
| Off-chain joins and SQL | No | Yes | Yes |
| Latency control | Limited | Good | Full |
| Best for | Public, event-driven protocol data | Product backends on EVM chains | Unusual chains, strict SLAs, custom pipelines |
A common pattern is to use both: a public subgraph so integrators can query your protocol, and a private indexer for your own app that joins on-chain data with user accounts and prices.
If your app only needs a few recent reads, you may not need an indexer at all: direct calls through a library such as ethers.js v6 or viem are enough.
Checklist
- Index from the contract's deployment block, with the ABI of every implementation version.
- Prefer events over contract calls; emit the fields you will need when you write the contract.
- Key rows by
(chain_id, tx_hash, log_index)and make every write idempotent. - Backfill to
finalized; track block hashes above it and roll back on reorgs. - Store the cursor in the same database transaction as the data.
- Handle provider range limits with adaptive block ranges.
- Expose indexing progress (
_metaon subgraphs, a cursor table on custom indexers) and alert when it lags the chain. - Reindex from scratch in staging regularly to prove your handlers are deterministic.
Get the weekly commit
New blockchain deep dives every week.