> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xarchive.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshoot order book sequencing

> Fix a local order book that drifts from 0xArchive: anchor at a checkpoint, apply L4 or full-depth L2 diffs in block order, detect a mismatch, and re-anchor.

Bring a local order book back in line with the venue: start from a checkpoint, apply diffs after its block in block order, and re-anchor at a checkpoint when the book stops matching. A Hyperliquid L4 or full-depth L2 book is a baseline plus ordered changes, so one skipped, repeated, or reordered diff corrupts every later state.

## Symptoms

* The best bid is at or above the best ask in your local book.
* Order or level counts drift away from the server's snapshot for the same time.
* An `update` or `remove` diff names an order your book does not hold.
* The book goes wrong after a reconnect, a lag notice, or a `gap_detected` event.

## Match the symptom to the cause

| Symptom | Cause and fix |
| - | - |
| Drift right after the start | Diffs from the anchor block were applied again. Apply only diffs whose block number is greater than the checkpoint's `last_block_number` |
| Drift that grows over time | Diffs were applied out of order, for example sorted by timestamp. Apply them in `(block_number, seq)` order, as the server sends them |
| Unknown order in `update` or `remove` | A page or batch was skipped, or the baseline is wrong. Re-anchor at a checkpoint |
| Wrong after a reconnect or lag notice | Messages were missed. Mark the book unsafe and rebuild from a checkpoint |
| Crossed book in a historical snapshot | The response carries `is_crossed: true` when a reconstructed historical book has best bid at or above best ask. Record it with the output |

## How the records are ordered

* **L4 snapshots** (`/l4`, `/l4/history`) carry `last_block_number`, the chain block the book is current to, plus `checkpoint_timestamp` and `diffs_applied`. `diffs_applied: 0` is a clean checkpoint; a higher number means the server rolled the last checkpoint forward to your time.
* **L4 diffs** (`/l4/diffs`) carry `block_number`, `seq`, `oid`, `side`, `price`, `diff_type` and `new_size`. `diff_type` is `new`, `update` or `remove`, and `new_size` is null on a remove. The REST diffs come back in `(block_number, seq)` order.
* **L4 WebSocket batches** (`l4_batch`) carry the same events with short names: `bn` for the block, `dt` for the diff type, `px` and `sz`. Items are ordered by block number, then by their order within the block. A new order can carry `insert_before`: insert it ahead of that order ID within its price level, or append it at the tail when the key is absent.
* **Full-depth L2 diffs** (`/l2/diffs`) are price-level changes derived from L4: `block_number`, `side`, `price`, and the level's `size` and `count` after the diff. Set the level to those values.

Never sort book events by timestamp alone. Many events share one block time.

## Rebuild and verify a book over REST

This script anchors a Hyperliquid SOL book at 23:00 UTC yesterday, applies one minute of L4 diffs after the anchor block, and compares the result with the server's book at the end of that minute:

```python theme={"theme":"github-dark"}
import os
from datetime import datetime, timezone
import requests

API = "https://api.0xarchive.io/v1/hyperliquid/orderbook/SOL"
HEADERS = {"X-API-Key": os.environ["OXARCHIVE_API_KEY"], "0xArchive-Version": "2026-10-01"}

def get(path, **params):
    r = requests.get(API + path, headers=HEADERS, params=params, timeout=60)
    r.raise_for_status()
    return r.json()

midnight = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
t0 = int(midnight.timestamp() * 1000) - 3_600_000   # 23:00 UTC yesterday; Free serves through yesterday
t1 = t0 + 60_000                           # one minute later

# 1. Anchor: the book at t0 and the block it is current to
anchor = get("/l4", timestamp=t0)["data"]
book = {o["oid"]: o for o in anchor["bids"] + anchor["asks"]}
last_block = anchor["last_block_number"]

# 2. Apply diffs after the anchor block, in (block_number, seq) order
params = {"start": t0, "end": t1, "limit": 10000}
prev = None
while True:
    page = get("/l4/diffs", **params)
    for d in page["data"]:
        key = (d["block_number"], d["seq"])
        if d["block_number"] <= last_block:
            continue                          # already in the anchor
        assert prev is None or key > prev, f"out of order at {key}"
        prev = key
        if d["diff_type"] == "remove":
            book.pop(d["oid"], None)
        elif d["diff_type"] == "new":
            book[d["oid"]] = {"oid": d["oid"], "side": d["side"], "price": d["price"], "size": d["new_size"]}
        else:                                 # update
            book[d["oid"]]["size"] = d["new_size"]
    if not page["meta"]["has_more"]:
        break
    params["cursor"] = page["meta"]["next_cursor"]

# 3. Verify against the server's book at the last applied block
check = get("/l4", timestamp=t1)["data"]
print("local block", prev[0] if prev else last_block, "server block", check["last_block_number"])
bids = sum(1 for o in book.values() if o["side"] == "B")
print("bids", bids, check["bid_count"], "asks", len(book) - bids, check["ask_count"])
```

A correct rebuild prints the same block on both sides and the same bid and ask counts, for example `local block 1232392518 server block 1232392518` and `bids 4809 4809 asks 6323 6323`. The diff window overlaps the anchor on purpose; the block filter drops what the anchor already holds. Apply `insert_before` as well when queue position matters.

## Re-anchor after a mismatch

A mismatch means the local book is no longer a valid state. Do not patch it level by level.

1. Mark the book unsafe and stop publishing from it.
2. Fetch a checkpoint at or before the last time you trust: `/l4` with `timestamp`, or the nearest entry from `/l4/history` for a window. Over the WebSocket, unsubscribe and subscribe again: a new L4 subscription opens with a fresh `l4_snapshot`. For history, start a new replay, which anchors at the latest checkpoint at or before `start`.
3. Apply diffs whose block number is greater than the new `last_block_number`, in order.
4. Record the mismatch, the checkpoint you re-anchored at, and the gap in the run manifest.

## Lighter books

Lighter books do not need diff sequencing on the live stream. Every `lighter_orderbook` message is a full book of up to 20 levels per side, not a diff, and a newer book is never replaced with an older one. Replace your local book with each message. For Lighter tick history on `/v1/lighter/orderbook/{symbol}/history` with `granularity=tick`, each item holds a checkpoint plus its ordered deltas. Keep the checkpoint, follow the returned cursor without resetting it, and order deltas by `sequence`. Sequence values order deltas but are not a consecutive counter within one market, so a jump in `sequence` is not a gap by itself.

## Verify the fix

* Your book's block and order counts match a server snapshot at the same block.
* No diff with a block number at or below the anchor's `last_block_number` was applied.
* Every reconnect, lag notice and `gap_detected` event led to a re-anchor, recorded with the output.

## Related

* [L4 order book](https://docs.0xarchive.io/rest-api/order-books-l4.md): snapshot, history and diff routes
* [WebSocket L4 order book](https://docs.0xarchive.io/websocket/l4-orderbook.md): live channels and book rules
* [SDK reconstruction](https://docs.0xarchive.io/sdks/reconstruction.md): helpers that apply snapshots and diffs
* [Order book depth](https://docs.0xarchive.io/core-concepts/order-book-depth.md): L2, L3 and L4 compared

## Next step

**Check whether the data itself has a gap**

When the book still breaks at the same place after a clean re-anchor, check coverage and incidents for that window.

[Check for a gap](https://docs.0xarchive.io/troubleshooting/gaps.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.