> ## Documentation Index
> Fetch the complete documentation index at: https://sonar-cf3aeac7.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cursors and resuming

> Track your position in the stream and resume after a disconnect without missing or repeating trades.

Every non-sampled subscription has a position in its chain's trade stream, called a cursor. If you store the latest cursor and send it back as `since` when you resubscribe, the server replays everything you missed and then continues live, with no duplicates and no holes.

## Cursor format

Cursors are strings in one of two forms:

| Form | Example | Where you see it | Meaning |
| - | - | - | - |
| `<block>-0:<index>` | `38123457-0:4` | `event.cursor` | One item inside a block |
| `<block>-0` | `38123457-0` | `subscribed.cursor`, `cursor` checkpoints | A whole block |

* `<block>` is the block number. Each block is one entry in the stream.
* `<index>` is the item's position in that block's list of swaps. That list includes swaps your subscription doesn't receive, so indices on your events can skip numbers.
* A stream with no entries yet reports `0-0`.

Treat cursors as opaque strings: store them and send them back unchanged. They are ordered, though: first by block, then by index, and a whole-block cursor `N-0` comes after every item cursor `N-0:i` of the same block. The server sends cursors for a subscription in increasing order, so the most recent one you received is always the latest.

Cursors are per chain. A cursor from one chain is meaningless on another.

## Resuming with since

Pass the cursor as `since` in a `subscribe` message, with the same channel and params as before:

```json theme={null}
-> {"op":"subscribe","id":"weth-trades","channel":"fast-trade","params":{"chain":"evm:8453","token":"0x4200000000000000000000000000000000000006"},"since":"38123457-0:4"}
<- {"type":"subscribed","id":"weth-trades","channel":"fast-trade","cursor":"38123457-0:4"}
<- {"type":"event","id":"weth-trades","channel":"fast-trade","cursor":"38123457-0:9","data":{"...":"..."}}
<- {"type":"event","id":"weth-trades","channel":"fast-trade","cursor":"38123460-0:1","data":{"...":"..."}}
```

* With an item cursor (`N-0:i`), replay continues inside block `N` after item `i`.
* With a whole-block cursor (`N-0`), replay starts at the block after `N`.
* Replayed events come after `subscribed`, in order. New trades that arrive during the replay are held back and sent after it, so live events never overtake replayed ones and nothing is sent twice.
* Without `since`, a subscription starts live from the current position. Nothing is backfilled.

### since as a map

Each subscription on `/v1/ws` reads exactly one stream, identified by a pair `<channel>|<chain>`, for example `fast-trade|evm:8453`. Instead of a plain cursor you can send a map with that single pair:

```json theme={null}
"since": {"fast-trade|evm:8453": "38123457-0:4"}
```

Both forms are equivalent here. A map that names any other pair is rejected:

```json theme={null}
<- {"type":"error","id":"weth-trades","code":"INVALID_PARAMETERS","message":"Unknown pairs in since","details":{"pairs":["fast-trade|evm:1"]}}
```

A `since` value that is not a valid cursor or map fails envelope validation, and that error has no `id`. See [error](https://sonar-cf3aeac7.mintlify.site/websocket/messages.md#error).

### Sampled subscriptions can't resume

Subscriptions with `maxUpdatesPerMinute` drop trades on purpose, so they have no cursors and reject `since`. See [Sampling](https://sonar-cf3aeac7.mintlify.site/websocket/messages.md#sampling-with-maxupdatesperminute).

## Checkpoints

About every 30 seconds, the server sends a `cursor` message to each live, non-sampled subscription whose position has moved:

```json theme={null}
<- {"type":"cursor","id":"weth-trades","cursor":"38123610-0"}
```

It means every block up to and including `38123610` has been processed for this subscription, even if none of its trades matched. Quiet subscriptions get checkpoints too. A token that trades once an hour still has a recent cursor, so you can resume it after a disconnect.

**What to store:** for each subscription, keep the most recent cursor from any of these messages:

* `subscribed.cursor`
* `event.cursor`
* `cursor.cursor`

Send it as `since` when you resubscribe.

## History retention

The stream keeps about **10 minutes** of blocks per chain. This is a current default and may change. The window is converted to a number of blocks using the chain's average block time, so it covers more blocks on fast chains.

If your cursor is older than the retained history, the subscription is not created:

```json theme={null}
<- {"type":"error","id":"weth-trades","code":"RESUME_EXPIRED","message":"Cursor is older than the stream history","details":{"retainedFrom":"38120111"}}
```

`details.retainedFrom` is the oldest block still retained, as a string. To recover:

1. Subscribe again **without** `since`. The subscription starts live.
2. Backfill the time you missed from REST:
   * Trades: [`GET /trades`](https://sonar-cf3aeac7.mintlify.site/api-reference/trades/get-trades). Its trade objects include every field of the WebSocket trade event.
   * Candles: [`GET /market/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/market/get-market-ohlcv) or [`GET /token/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token-ohlcv).
   * Token or market snapshots: [`GET /token`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token) or [`GET /market/details`](https://sonar-cf3aeac7.mintlify.site/api-reference/market/get-market-details).

The REST endpoints filter by time (`from` and `to` in Unix milliseconds), not by block. Use the `date` of the last event you processed as `from`.

## Gaps

Blocks are released in order. If a block is missing upstream for about 15 seconds, the stream skips past it and tells every subscriber:

```json theme={null}
<- {"type":"gap","id":"weth-trades","channel":"fast-trade","fromBlock":38123457,"toBlock":38123459}
```

* `fromBlock` and `toBlock` are inclusive. Trades in those blocks were not, and will not be, sent on this stream, including on replay.
* The subscription's position moves past the gap, and delivery continues normally.
* Sampled subscriptions get gap messages too.

If you need complete data, backfill the range from [`GET /trades`](https://sonar-cf3aeac7.mintlify.site/api-reference/trades/get-trades). Use the `date` of the last event before the gap and the first event after it as the `from` and `to` window, then keep only trades whose `blockNumber` is between `fromBlock` and `toBlock`.

## Reconnect loop

A robust client:

1. Keeps the channel, params and latest cursor of every subscription.
2. On every new connection, after `welcome`, resubscribes with `since` set to the stored cursor.
3. Reconnects with exponential backoff and jitter after any close.
4. Paces its subscribe messages, because the [message limit](https://sonar-cf3aeac7.mintlify.site/websocket/limits-and-errors.md#limits) of 20 per second also applies to resubscribes.
5. Handles `RESUME_EXPIRED` by dropping the cursor, resubscribing live and backfilling from REST.

```javascript JavaScript (browser, Node 22+) theme={null}
const WS_URL = "wss://api.example.com/v1/ws";

// What we want to be subscribed to, and how far we got.
const subs = new Map([
  ["weth-trades", {
    channel: "fast-trade",
    params: { chain: "evm:8453", token: "0x4200000000000000000000000000000000000006" },
    cursor: null,
  }],
]);

let attempt = 0;

function subscribe(ws, id, delayMs) {
  const sub = subs.get(id);
  const msg = { op: "subscribe", id, channel: sub.channel, params: sub.params };
  if (sub.cursor) msg.since = sub.cursor;
  // Stay well under 20 messages per second.
  setTimeout(() => ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify(msg)), delayMs);
}

function connect() {
  const ws = new WebSocket(WS_URL);

  ws.onmessage = (frame) => {
    const msg = JSON.parse(frame.data);
    const sub = msg.id ? subs.get(msg.id) : undefined;

    switch (msg.type) {
      case "welcome":
        [...subs.keys()].forEach((id, i) => subscribe(ws, id, i * 100));
        break;
      case "subscribed":
        attempt = 0;
        if (sub && msg.cursor) sub.cursor = msg.cursor;
        break;
      case "event":
        if (sub && msg.cursor) sub.cursor = msg.cursor;
        handleEvent(msg);
        break;
      case "cursor":
        if (sub) sub.cursor = msg.cursor;
        break;
      case "gap":
        backfillBlocks(msg.id, msg.fromBlock, msg.toBlock);
        break;
      case "error":
        if (msg.code === "RESUME_EXPIRED" && sub) {
          sub.cursor = null;
          backfillFromRest(msg.id);
          subscribe(ws, msg.id, 0);
        } else {
          console.error(msg.id ?? "(no id)", msg.code, msg.message);
        }
        break;
      case "reconnect":
        // The server is restarting. Move now instead of waiting for close code 1012.
        ws.close(1000);
        break;
    }
  };

  ws.onclose = (event) => {
    // Back off harder if we were rate limited (4029).
    const base = event.code === 4029 ? 5000 : 1000;
    const delay = Math.min(30000, base * 2 ** attempt) + Math.random() * 1000;
    attempt += 1;
    setTimeout(connect, delay);
  };
}

function handleEvent(msg) { /* your logic */ }
function backfillBlocks(id, fromBlock, toBlock) { /* GET /trades, keep fromBlock..toBlock */ }
function backfillFromRest(id) { /* GET /trades or /market/ohlcv since your last event */ }

connect();
```

```python Python (websockets) theme={null}
import asyncio
import json
import random

import websockets

URL = "wss://api.example.com/v1/ws"

subs = {
    "weth-trades": {
        "channel": "fast-trade",
        "params": {"chain": "evm:8453", "token": "0x4200000000000000000000000000000000000006"},
        "cursor": None,
    },
}

async def subscribe(ws, sub_id):
    sub = subs[sub_id]
    msg = {"op": "subscribe", "id": sub_id, "channel": sub["channel"], "params": sub["params"]}
    if sub["cursor"]:
        msg["since"] = sub["cursor"]
    await ws.send(json.dumps(msg))
    await asyncio.sleep(0.1)  # stay well under 20 messages per second

async def session():
    async with websockets.connect(URL) as ws:
        async for raw in ws:
            msg = json.loads(raw)
            sub = subs.get(msg.get("id"))
            kind = msg["type"]

            if kind == "welcome":
                for sub_id in subs:
                    await subscribe(ws, sub_id)
            elif kind in ("subscribed", "event", "cursor"):
                if sub and msg.get("cursor"):
                    sub["cursor"] = msg["cursor"]
                if kind == "event":
                    handle_event(msg)
            elif kind == "gap":
                backfill_blocks(msg["id"], msg["fromBlock"], msg["toBlock"])
            elif kind == "error":
                if msg["code"] == "RESUME_EXPIRED" and sub:
                    sub["cursor"] = None
                    backfill_from_rest(msg["id"])
                    await subscribe(ws, msg["id"])
                else:
                    print("error", msg.get("id"), msg["code"], msg["message"])
            elif kind == "reconnect":
                return  # leave the context, which closes the socket, then reconnect

async def main():
    attempt = 0
    while True:
        try:
            await session()
            attempt = 0
        except (OSError, websockets.WebSocketException) as exc:
            print("disconnected:", exc)
            attempt += 1
        await asyncio.sleep(min(30, 2 ** attempt) + random.random())

def handle_event(msg): ...
def backfill_blocks(sub_id, from_block, to_block): ...
def backfill_from_rest(sub_id): ...

asyncio.run(main())
```

> [!TIP]
>
> If you resubscribe within about 10 minutes, the replay fills the whole disconnect window. You only need REST backfill for `gap` messages and `RESUME_EXPIRED`, and to reload recent candles for [`ohlcv`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/ohlcv), which does not resend trades already counted into its live candle.


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