Detecting and Filling the Gap After a WebSocket Drop

By John Sullivan · November 29, 2026 · 9 min read · #websocket #missed blocks #backfill #indexer #json-rpc

The socket dropped. You reconnected, the subscription is live, and you think you missed blocks but cannot name them. The stream cannot tell you what it did not deliver. Notifications arrive under the method eth_subscription, and each one carries a subscription id and a result and nothing else [1]. No sequence number, no cursor, no delivery index. A notification is not confirmable by definition, because it has no Response object to be returned [2]. So the gap is provable only from your own stored state: detect it from a persisted cursor, size it against the chain, fill it before the subscription resumes, verify the fill against the chain. The fourth step is the one most indexers skip. A subscription can also close while events are still arriving; the reconnect loop belongs to the subscription lifecycle.

Why the stream cannot tell you what you missed

Neither specification defines a recovery contract, and the silence is structural. The JSON-RPC 2.0 specification has no publish/subscribe section at all; it reserves method names beginning rpc. for system extensions, defines those in other documents, and marks them optional [2]. It also reserves -32000 to -32099 for implementation-defined server errors [2]. execution-apis defines eth_subscribe, eth_unsubscribe, the notification shape and four subscription kinds, and stops there [1]. No replay, no cursor, no resumption, no delivery guarantee. Whatever recovery contract you have is the implementation's, which makes it yours to build.

The client's documentation states the same limit from the other end: notifications are sent for current events and not for past events [3]. It also states that subscriptions are coupled to a connection, and that closing the connection removes all of them [3]. The service's own guidance is blunt: the server forgets your subscriptions on a reconnect, so you re-issue them [4]. The WebSocket page documents eth_subscribe and eth_unsubscribe and stops there [5].

So you cannot ask the server what you missed. There is no per-client gap record, no delivery cursor and no replay of subscription events — neither specification defines one and neither docs page describes one. A silent gap is the common case: the service's docs note that one client library reconnects and re-subscribes transparently [4], which makes the gap invisible rather than absent.

Because the stream cannot tell you, the only evidence of a gap is your own stored state. A consumer with no persisted cursor cannot detect a gap; it can only suspect one. A gap you can name is a backfill. A gap you cannot name is a re-index.

Detect: the cursor is the whole mechanism

The cursor is the block or event number your consumer last durably processed, stored with the block hash. Advance it only after the write it describes is durable, never before. A notification has no Response object, so there is no acknowledgement to wait for [2]; the ordering is yours to get right. Advance the cursor first and a crash between the two moves it past data that was never stored, and the skip is invisible because the cursor has already moved past it.

At startup, load the cursor, compare it against the head, and log the range. Do not act on it in the same step; the fill has its own budget and retry policy. The rpc helper is a plain JSON-RPC request over the socket; the methods are the documented ones [6].

const cursor = await store.loadCursor();   // { number, hash } | null
const head = await rpc("eth_getBlockByNumber", ["latest", false]);

if (!cursor) {
  log.warn("no cursor stored: a gap can be suspected, not detected");
  return;                                  // reconcile instead
}
if (BigInt(head.number) <= BigInt(cursor.number)) return;

const from = BigInt(cursor.number) + 1n;
const to = BigInt(head.number);
log.warn("gap detected", {
  from: `0x${from.toString(16)}`,
  to: `0x${to.toString(16)}`,
  blocks: Number(to - from + 1n),
  fromHash: cursor.hash,   // last block we processed
  toHash: head.hash,       // head we measured against
});
// Log only. Sizing and filling are separate steps.

A cursor stored as a number and a hash is always available from one call: the Block object's required fields include hash, parentHash, number, transactions and uncles [7].

If the consumer has never persisted a cursor, the honest detection is a reconciliation against the chain: pick a block the consumer believes it processed, read that block's own state, and compare. That is a guess being tested, not a detection, and the result is a range to re-index rather than a gap to fill.

Either way, the handler has to tolerate redelivery, because the fill overlaps data the live stream already delivered.

Size: how big is the hole, and can it be filled in one call

Sizing is two questions, and the second bites: how many blocks, and will the endpoint accept them in one request. A large gap is not one eth_getLogs call. The per-chain caps decide whether the fill is one call, a chunked loop, or a job — see eth_getLogs limits across chains, measured and which chains cap your log queries. What the fill costs in log ranges is its own budget: planning an indexer backfill.

Record three things before the first call: the range, the block hashes at both ends, and the timestamp. The hashes matter more than the numbers. A latest tag can be re-orged out of the canonical chain under ordinary, healthy conditions [7], so a fill that resumes from a number rather than a hash can skip the replacement block.

The range also has to be legal. eth_getLogs bounds an inclusive range with fromBlock and toBlock, and clients MUST return -32602: Invalid params if either bound resolves past the current head, or if fromBlock exceeds toBlock [8]. A fill that asks past the head gets an error, not a short result.

Fill: backfill before you resubscribe, not after

The service's reconnect guidance tells you to re-issue every subscription and optionally backfill missed blocks via HTTP eth_getBlockByNumber [4]. It stops there: no cursor, no way to size the gap, no way to know the gap exists, no way to verify the fill. The mechanism is what you supply.

The rule: the backfill runs to completion before the subscription resumes. A fill alongside a live subscription is not wrong, but it guarantees overlap, overlap means redelivery, and redelivery means the handler has to be idempotent.

When the consumer cannot stop, use buffer-then-drain: resubscribe immediately, hold live events in a buffer, run the backfill, then drain the buffer through the same handler. It costs two things — the buffer has to be bounded, and the drain ordered against the fill, so a buffered event is never written before the fill has passed its block.

The fill loop reads the range in chunks the endpoint will accept, writes each block or event through the same handler the live stream uses, advances the cursor only after the write is durable, and stops on a chunk that fails rather than skipping it. A fill that skips a failed chunk is worse than no fill: it produces a consumer that looks complete and is not. The endpoint will not skip for you: a client must not clamp the range to the head or hand back a partial result [8].

A fill can also fail because the history is pruned, not because the request was wrong. Error 4444 Pruned history unavailable is declared on eth_getLogs [8]. That range is no longer servable; the answer is a different source, not a retry.

Redelivery is documented: reorged logs are re-sent with removed set to true [1]. A backfill that overlaps the live stream re-delivers the same log by construction. The dedupe key is (block number, log index) or (transaction hash, log index), both log fields [8]; the general pattern is gap detection after a drop.

The fill's calls fail in different ways. Some are worth retrying on a schedule with a cap and jitter — 429, backoff and jitter — and some should not be retried at all: which JSON-RPC errors are retryable.

Verify: the step that turns a fill into a proof

A completed fill is not a verified fill.

The usual verification is a test harness: kill the socket, inject an event, assert exactly-once recovery. That proves the code path works. It does not prove the data is right, because it never compares what you stored against what the chain holds. Reconciliation does, and it catches the fill that ran to completion and wrote the wrong thing.

For a sample of blocks across the filled range, compare three values: the block hash, the transaction count, and one derived value your consumer computes — the block's log count, from eth_getLogs with fromBlock and toBlock both set to that block number [8]. eth_getBlockByNumber returns a Block object whose required fields include hash, number, transactions and uncles [6][7]; with hydrated transactions false, transactions is an array of hashes, so the count is its length.

async function reconcile(blockNumber: string) {
  const chain = await rpc("eth_getBlockByNumber", [blockNumber, false]);
  if (chain === null) return { blockNumber, status: "notFound" };  // handle, do not throw

  const stored = await store.loadBlock(blockNumber);
  const chainLogs = await rpc("eth_getLogs", [{ fromBlock: blockNumber, toBlock: blockNumber }]);

  const mismatches: string[] = [];
  if (!stored) mismatches.push("missing locally");
  if (stored && stored.hash !== chain.hash) mismatches.push("hash");
  if (stored && stored.txCount !== chain.transactions.length) mismatches.push("txCount");
  if (stored && stored.logCount !== chainLogs.length) mismatches.push("logCount");

  return { blockNumber, status: mismatches.length ? "mismatch" : "ok", mismatches };
}
// Callers must also handle error 4444 Pruned history unavailable without throwing.

A mismatch means one of two things: the fill missed something, or a reorg moved the block. You can tell them apart. Re-read the block at that number: if the chain's hash has changed since you recorded it, a reorg moved the block and the fill was working from a stale range. If the hash matches what you stored and the counts still differ, the fill wrote the wrong data. Both are actionable, and neither is detectable from the stream.

Do not re-run the fill blindly on a mismatch. Widen the sample first: one disagreement in ten blocks tells you something different from nine, and the difference is whether the fill failed at a boundary or throughout the range.

What the sample cannot do is prove the range. Ten blocks across a 50,000-block gap is evidence, not proof: the reconciliation bounds the risk rather than eliminating it. Sample across the whole range rather than the first ten blocks, and record which blocks you sampled and the result, so the next run is comparable and a slow drift shows up.

What this does not cover

Why the socket closed and what the reconnect loop looks like belong to the subscription lifecycle piece; this starts after the reconnect. Keeping a quiet connection open — heartbeats and zombie connections — is its own problem, covered separately. Whether to run a subscription at all, or poll instead, is the lifecycle piece's decision. And these behaviours are this service's: another provider may retain a cursor or replay events, and we claim nothing otherwise.

Check one thing in your own consumer before you write any backfill code: is the cursor advanced only after the write it describes is durable, or before? If it is before, a crash between the two loses the gap, and no amount of backfilling will find it.

Read the WebSocket guide

Sources

  1. execution-apis — eth_subscribe — ethereum/execution-apis (Ethereum Foundation)
  2. JSON-RPC 2.0 Specification — jsonrpc.org (JSON-RPC Working Group)
  3. Go-Ethereum docs — Real-time Events — Go-Ethereum, 2023-08-16
  4. SwiftNodes docs — How to Use Ethereum WebSocket RPC — SwiftNodes
  5. SwiftNodes docs — WebSocket (subscriptions section; page carries no backfill, replay or cursor text) — SwiftNodes
  6. execution-apis — eth_getBlockByNumber signature (src/eth/block.yaml) — ethereum/execution-apis (Ethereum Foundation)
  7. execution-apis — Block object schema, required fields (src/schemas/block.yaml) — ethereum/execution-apis (Ethereum Foundation)
  8. execution-apis — eth_getLogs — ethereum/execution-apis (Ethereum Foundation)

This article was researched, written and edited by AI under human supervision, and checked against Rankwrite's public editorial rubric.

J
John Sullivan
Infrastructure Writer, SwiftNodes

John Sullivan covers RPC infrastructure, node operations, and multi-chain development at SwiftNodes — what it actually takes to keep endpoints fast, fresh, and reliable across EVM and non-EVM networks.

Related posts

Try SwiftNodes free — multi-chain RPC across 144 networks, flat-rate pricing, pay by card or crypto, no KYC. Get an API key in 30 seconds →