Indexers and data pipelines: reorg handling, backfills, idempotency, and lag as an SLI

The source can rewrite its own recent history. Key every row by block hash, make writes idempotent, isolate backfill, and treat lag as the user-facing SLI.

Read the briefing
About 3 min to read 7 drills

What to remember

  1. Block numbers repeat across branches; hashes do not. Key by (chain, block hash, log index) or you cannot find the orphaned rows.
  2. Track the parent hash chain to detect reorgs. On mismatch, walk back to the common ancestor, invalidate, re-apply.
  3. Idempotent upserts, keyed on a stable identity. Replays and restarts are routine, not exceptional.
  4. Never share a node pool between backfill and live indexing. A catch-up job will starve the live path and make the product stale.
  5. Lag in blocks and in seconds is the SLI. 'The process is running' catches none of the real incidents.

The big picture

An indexer turns a chain into a queryable database, and it lives with a property no ordinary ETL pipeline has: the source can rewrite its own recent history. Reorg handling, idempotent writes, isolated backfills, lag-as-an-SLI, and decoders that survive contract and fork changes are what separate a demo indexer from one you can put customers on.

The mental model

Two clocks: the chain's head, which is provisional and can rewind, and finality, which is stable. Everything you publish is either "fast and revocable" or "slow and final", and you must choose per data product. Every write is keyed by something that survives replay, and lag is the number your users feel.

In depth

Reorgs: the defining problem

A reorg replaces recent blocks with a different branch. An indexer that tracks only block numbers will happily keep writing on top of history that no longer exists, and its data silently diverges from the chain. Two valid strategies: wait for finality (index only blocks that are finalized or N confirmations deep, simple and correct, at the cost of latency), or track block hashes and roll back (store the parent hash chain, detect a mismatch at the head, delete or invalidate the affected rows, and re-apply the new branch, low latency at the cost of real complexity). Most production systems do both: a fast, revocable view for the UI and a finalized view for anything that matters, clearly labelled.

Whichever you choose, the invariant is that every row can be traced to a block hash, so "which rows came from the orphaned branch?" is a query, not an archaeology project.

Idempotency, backfills, and isolation

Indexers restart, replay, and receive duplicates constantly. Writes must be idempotent: keyed on a stable identity, typically (chain_id, block_hash, log_index) or the transaction hash plus an index, applied as upserts. Side effects, notifications, webhooks, payouts, need the same treatment through a dedup table on that key, because "we processed the block twice" is a routine event, not an exception.

Backfill and live indexing are different workloads. Backfill is throughput-bound: parallelize by block range, checkpoint each range so a crash resumes rather than restarts, and run it against a pool sized for heavy queries. Live indexing is latency-bound and small. Running both against the same nodes without isolation is the classic self-inflicted incident: a backfill saturates the nodes, live indexing falls behind, and the product looks broken. Separate pools, separate rate limits, and a backfill that can be paused are the mechanisms.

Lag as an SLI, and schema evolution

The user-visible SLI is lag: how many blocks (and seconds) behind head the served data is, plus correctness after reorgs. Alert on lag thresholds and on rollback failures; "the process is running" catches none of the real incidents. Publish freshness so consumers can decide what to trust, and expose the block number and hash your data corresponds to.

Schema evolution happens without your consent: contracts are upgraded behind proxies, new event signatures appear, forks change semantics. Pipelines need versioned decoders keyed by address and block range, a policy of storing the raw log for anything unknown (never drop: you cannot re-derive what you did not keep), and migrations that can be re-derived from raw data or from a checkpoint instead of demanding a multi-week full re-index. Keeping raw and derived data separate is what makes a decoder bug a re-processing job rather than a data loss.

Myths and facts

Myth: Reorgs are rare enough to ignore.

Fact: Single-block reorgs are routine on most chains; ignoring them means occasionally serving data from an orphaned branch with no way to detect it.

Myth: Waiting for finality is always the right answer.

Fact: It is the simplest correct answer, but it costs latency; many products need a fast revocable view alongside the finalized one.

Myth: Indexing keyed on block number is fine if you also store the timestamp.

Fact: Neither survives a reorg; the block hash is the identity that does.

Myth: A backfill can share the node pool with live indexing if it is rate limited.

Fact: Rate limits help, but heavy historical queries still evict caches and saturate disks; isolate the pools.

Myth: If a decoder does not recognize an event, skipping it is safe.

Fact: You lose data you cannot recover without re-fetching; store raw logs and decode later.

How pros do it

  • Key every row to (chain, block hash, log index) and make writes upserts; dedup side effects on the same key.
  • Choose a reorg strategy per data product (finality-only vs hash-tracked rollback) and label freshness for consumers.
  • Isolate backfill from live indexing: separate pools, checkpoints per range, pausable, with its own limits.
  • Alert on lag (blocks and seconds) and on rollback failures; publish the block number and hash behind your data.
  • Store raw logs, version decoders by address and block range, and make re-processing a routine job.

Questions people ask

How do you handle a reorg?

Give the two strategies and pick per product: wait for finality (simple, correct, slower) or track the parent-hash chain and roll back on mismatch (fast, complex). Either way say that every row carries the block hash, because block numbers repeat across branches and hashes do not.

How deep should we wait before treating data as final?

Use the chain's own finality where it exists (Ethereum's finalized tag); otherwise pick a confirmation depth from the observed reorg-depth distribution and say what it is. State the number rather than 'a few blocks'.

What do we alert on?

Lag in blocks and in seconds, reorg rollback errors, decode failure rate, and write errors. Say explicitly that process uptime is not on the list, because 'the process is running' catches none of the real incidents.

Our indexer is 40,000 blocks behind after an outage. What is the fastest safe recovery?

A parallel range backfill against the heavy pool with per-range checkpoints, while live indexing keeps following the head, then reconcile. The point to make is that you never serialize the catch-up through the live path.

How do we handle a contract upgrade that changes an event?

Version the decoder by address and block range, keep the raw logs, and re-derive the affected rows. Say you never mutate historical decoded data in place without the raw source to re-derive it from.

Should the indexer read from our own nodes or a provider?

Both, with reasons: providers for burst capacity and cross-checking, own nodes for cost and control. Whichever you choose, say that backfill traffic is isolated from the live path.

Further reading

Drills · 7

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

Your indexer keys its rows by block number and transaction index, and the chain has a two-block reorg. What happens to your data?

  1. Nothing: the numbers are the same, so the data is equivalent. Different branch, different transactions and events at the same numbers.
  2. The indexer automatically re-processes affected blocks. Only if it tracks hashes and implements rollback.
  3. The database rejects the writes because of the primary key. A conflict may occur, but the underlying problem is stale rows from the orphan, which no constraint detects.
  4. Rows from the orphaned blocks stay in the database and new rows for the same numbers may conflict or be missed; without block hashes there is no way to identify which rows came from the discarded branch. Block number is not a stable identity across reorgs; block hash is.
In short

Rows from the orphaned blocks stay in the database, and without block hashes you cannot tell which rows they are.

Why

Track the parent-hash chain: on each new head, verify its parent matches the hash you stored; on mismatch, walk back to the common ancestor, invalidate rows for the orphaned hashes, and re-apply the new branch. Alternatively, index only finalized blocks.

The common mistake

Assuming a primary key or a timestamp will catch it. Neither identifies rows from an orphaned branch, so the stale rows sit there silently and the data diverges from the chain.

Read the docs

2 Scenario: what do you do next?

A customer reports that their dashboard showed a large transfer that "never happened". Your indexer is at head with no errors. The transaction hash they quote is not on chain, but your database has a row for it from 40 minutes ago.

Step 1. First step?

  1. Check whether that row's block hash is on the canonical chain (query the node for the block by hash and by number) and look for a reorg at that height in your own reorg metrics or the node's logs. The signature of serving orphaned data; the block hash makes it a two-query check.
  2. Ask the customer to refresh. The data is wrong at the source.
  3. Restart the indexer to force a re-sync. Does not identify or repair orphaned rows, and loses the state you need.
  4. Delete the row and tell the customer it was a display bug. Destroys evidence and misrepresents a correctness incident.

Step 2. Confirmed: a 3-block reorg at that height; your indexer tracks block numbers only, so orphaned rows were never removed. Immediate action?

  1. Add a note in the API docs that data may be revised. Does not repair the data or prevent recurrence.
  2. Switch to a provider's indexed API and abandon your pipeline. A strategic change proposed as an incident fix.
  3. Quarantine: identify affected height ranges, re-fetch those blocks by canonical hash, correct the rows, notify affected customers with the specifics, and add a temporary confirmation delay before publishing so new data cannot repeat the fault while the fix ships. Repairs the data, communicates honestly, and blocks recurrence during remediation.
  4. Re-index everything from genesis. Days of work for a bounded problem; target the affected ranges.

Step 3. Permanent fix?

  1. Only index finalized blocks from now on. Correct but may be unacceptable for the product; offer both views rather than removing the fast one silently.
  2. Key rows by (chain, block hash, log index) with upserts, track the parent-hash chain to detect and roll back reorgs, publish a finalized view alongside a labelled fast view, and alert on rollback failures and lag. Makes reorg handling structural and gives consumers an explicit freshness contract.
  3. Add a reconciliation job that compares to a provider's data nightly. Useful as a check, but it detects rather than prevents, and a night is too long.
In short

First check whether that row's block hash is still on the canonical chain; if not, you served data from a reorged branch.

Why

This is the canonical indexer incident. Interviewers listen for the block-hash check, targeted repair, honest customer communication, and a permanent design where reorg rollback is a first-class operation with its own alerts.

The common mistake

Deleting the row and calling it a display bug, or re-indexing from genesis. The first hides a correctness incident; the second turns a bounded repair into days of work.

Read the docs

3 Pick the strongest answer

Your indexer sends a webhook when it sees a Transfer event. After a restart it replays the last 200 blocks and customers get duplicate notifications. What is the right fix?

  1. Send webhooks only for finalized blocks. Helps with reorgs, not with replay duplicates, which can still occur after finality.
  2. Deduplicate side effects on a stable key such as (chain_id, block_hash, log_index): record the key before sending, and skip sends whose key is already recorded, so replay is safe by construction. At-least-once processing plus idempotent effects is the only workable model.
  3. Ask customers to deduplicate on their side. Reasonable to document, but the pipeline must not depend on it.
  4. Make the indexer never replay by writing its checkpoint before processing. That trades duplicates for lost events on crash; replay must remain safe.
In short

Record a stable key like (chain, block hash, log index) before sending, and skip any send whose key is already recorded.

Why

Exactly-once delivery is not achievable; exactly-once effects are, through a stable identity plus a dedup record written before the effect. The same key handles reorg invalidation, which is why block hash belongs in it.

Read the docs

4 Read the output

Talk me through what is happening here, and what you would change first.

# dashboards, 09:00-09:30
indexer_head_lag_blocks       12 -> 480 (climbing)
indexer_write_errors           0
rpc_pool_shared_p99_ms       210 -> 4,100
rpc_pool_shared_getlogs_rps   14 -> 260
backfill_job_status          "running: ranges 4,200,000-5,000,000, 24 workers"
alert fired                  none (only 'indexer process up' is alerted)
  1. The backfill is saturating the shared RPC pool, so live indexing cannot keep up and lag is climbing; no alert exists because only process liveness is monitored. Pause or throttle the backfill, then isolate it onto its own pool and alert on lag. Backfill getLogs rate and pool latency rise together while writes are healthy; the missing alert is the second finding.
  2. Add more indexer workers to catch up. More readers against the same saturated pool makes it worse.
  3. The database is the bottleneck; scale writes. Write errors are zero and nothing indicates database saturation.
  4. The chain is producing blocks faster than usual. Block production is steady; the RPC pool latency explains the lag.
In short

The backfill is saturating the shared RPC pool, so live indexing falls behind; pause it, give it its own pool, then alert on lag.

Why

Two lessons: backfill and live indexing must not share a node pool, and lag is the SLI. Alerting on process uptime is exactly why nobody was paged while the product went stale.

Read the docs

5 Answer out loud

Design an indexing pipeline for two chains that serves both a low-latency product view and a financially trustworthy view. Cover reorg handling, storage keys, backfill, freshness contracts, and monitoring. Five to seven sentences.

In short

A strong answer publishes a fast provisional view and a finalized view, each labelled with the block number and hash it reflects.

What a strong answer does
  • correctness: Raw-then-derived storage keyed by (chain, block hash, log index), hash-chain tracking with rollback for the fast view, finalized view for trust, upserts and dedup for effects, versioned decoders with raw retention.
  • operations: Backfill isolated with checkpoints and pause control, lag SLIs in blocks and seconds, rollback-failure alerts, published freshness (block number and hash) per view.
  • judgment: Two explicitly labelled views with a stated contract, and a rationale for which products use which.
  • communication: Data model → ingestion → reorg policy → backfill → contracts → monitoring, with tradeoffs stated.
Why

Strong answers separate raw from derived, make reorg rollback explicit, publish freshness contracts, and isolate backfill; the willingness to delete complexity if the product does not need it reads as senior.

6 Quick recall

What must every row in an indexer carry so that data from a reorged block can be found and removed?

In short

The block hash.

Accepted

block hash · the block hash · hash

Why

Block numbers repeat across branches; the block hash is the stable identity that lets you detect and roll back an orphaned branch.

7 Find what's broken

Three design decisions in this schema and loop will corrupt the dataset. Which lines?

CREATE TABLE transfers (
  id            BIGSERIAL PRIMARY KEY,
  block_number  BIGINT NOT NULL,
  tx_index      INT NOT NULL,
  log_index     INT NOT NULL,
  token         BYTEA NOT NULL,
  from_addr     BYTEA NOT NULL,
  to_addr       BYTEA NOT NULL,
  amount        NUMERIC NOT NULL
);
-- indexer pseudocode
-- for block in range(checkpoint, head):
--     logs = eth_getLogs(fromBlock=block, toBlock=block, topics=[TRANSFER_SIG])
--     for log in logs:
--         if decode_fails(log): continue
--         INSERT INTO transfers (...) VALUES (...)
--     checkpoint = block
In short

Line 3 keys rows by block number with no hash, line 16 does a plain insert that duplicates on replay, and line 15 throws away logs it cannot decode.

What's broken
  • Line 3: Rows are keyed by block number with no block hash and no chain id, so reorged blocks cannot be identified or removed, and two chains cannot share the table safely.
  • Line 16: A plain INSERT is not idempotent: nothing makes (chain, block hash, log index) unique, so every replay creates duplicate rows.
  • Line 15: Undecodable logs are skipped and discarded, so an unknown or upgraded event signature is lost permanently.
Why

A surrogate id is fine as long as a natural key is also unique; BYTEA addresses and NUMERIC amounts are sensible; querying one block at a time is slow but not corrupting. The three flagged lines each produce wrong data that is expensive to detect and expensive to repair.

Read the docs

Next lesson Key custody and operational security for chain infrastructure
Drill · Indexers and data pipelines
0:00

Loading…