# Hyperliquid userFills in Node.js: snapshots, reconnects and missing fills

If you track your own trades over WebSocket, the Hyperliquid userFills subscription is the obvious feed. It is also easy to get subtly wrong. The first message is a snapshot, the same snapshot comes back after every reconnect, and the snapshot is a short recent window rather than a record of everything you missed while the socket was down. Get that wrong and you either count fills twice or quietly lose them. This guide shows a small, tested pattern for Node.js and TypeScript with `@siebly/hyperliquid-api`: treat the snapshot as a cue, dedupe fills by `tid`, and backfill gaps over REST.

## What the Hyperliquid userFills stream sends

Install the SDK with `npm install @siebly/hyperliquid-api`. Account streams need only the account address, not a private key, so this part is read-only.

```typescript
import { WebsocketClient } from '@siebly/hyperliquid-api';

const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS ?? '';
const ws = new WebsocketClient({});

ws.on('message', (event) => {
  if (event.channel !== 'userFills') {
    return;
  }
  const { isSnapshot, fills } = event.data;
  console.log(isSnapshot ? 'snapshot' : 'live', fills.length, 'fills');
});

await ws.subscribe({ type: 'userFills', user });
```

Checking `event.channel` narrows `event.data` to the SDK’s `UserFillsEvent` type: `{ user, fills, isSnapshot? }`, where each fill is a `UserFill` with `coin`, `px`, `sz`, `side` (`"B"` for buy, `"A"` for sell), `time`, `oid`, `tid`, `hash`, `dir`, `closedPnl` and `fee`.

We ran this against a busy mainnet account on 25 November 2026 and saw three things worth designing around:

- The snapshot is small. The first message had `isSnapshot: true` and 30 fills. Over REST, the same account had 120 fills in the previous two minutes alone.
- Reconnects repeat it. After we forced the socket closed, the SDK reconnected and resubscribed by itself, and the server sent a second snapshot with exactly the same 30 `tid` values.
- Live messages carry no flag. On live updates `isSnapshot` was absent, not `false`, and one message held 177 fills. Test with `!event.data.isSnapshot`, never `=== false`.

## Why Hyperliquid userFills double counts or loses fills

Two naive handlers cause most of the bugs:

| Handler | What goes wrong |
| --- | --- |
| Process every message, snapshot included | Every reconnect replays the snapshot, so the same fills are booked again. Position or PnL totals drift upwards. |
| Skip snapshots, process live fills only | Fills that happen while the socket is down never arrive as live messages, and the short snapshot may not cover the gap. They are simply missing. |

The fix for both is the same: use a stable ID to make processing idempotent, and use REST, which can page through history, to fill any gap.

## Dedupe Hyperliquid userFills by tid and backfill over REST

`tid` is the trade ID of the fill, so it is a natural key. Keep a checkpoint (the newest fill time you have processed, ideally persisted), and whenever a snapshot arrives, ask REST for everything since that checkpoint with `getUserFillsByTime()`. The SDK notes that this method returns at most 2,000 fills per call and only the 10,000 most recent fills are available, and that you paginate by using the last `time` as the next `startTime`. Those pages overlap by design, which the `tid` check absorbs.

```typescript
import {
  RestClient,
  WebsocketClient,
  type UserFill,
} from '@siebly/hyperliquid-api';

const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS ?? '';
const rest = new RestClient({});
const ws = new WebsocketClient({});

const MAX_PAGE = 2000;
const KEEP_TIDS_MS = 60 * 60_000; // remember tids for an hour

const seen = new Map<number, number>(); // tid -> fill time
let checkpoint = Number(process.env.FILLS_SINCE ?? Date.now());
let backfilling: Promise<void> | undefined;

function handleFill(fill: UserFill): void {
  if (seen.has(fill.tid)) {
    return; // already processed
  }
  seen.set(fill.tid, fill.time);
  checkpoint = Math.max(checkpoint, fill.time);

  const side = fill.side === 'B' ? 'buy' : 'sell';
  console.log(fill.coin, side, fill.sz, '@', fill.px, 'oid', fill.oid);
}

function pruneSeen(): void {
  const cutoff = checkpoint - KEEP_TIDS_MS;
  for (const [tid, time] of seen) {
    if (time < cutoff) {
      seen.delete(tid);
    }
  }
}

async function backfill(): Promise<void> {
  let startTime = checkpoint;
  for (;;) {
    const page = await rest.getUserFillsByTime({ user, startTime });
    page.forEach(handleFill);

    const last = page.at(-1);
    if (page.length < MAX_PAGE || !last || last.time === startTime) {
      break;
    }
    startTime = last.time; // pages overlap on purpose; tids dedupe them
  }
  pruneSeen();
}

function scheduleBackfill(): void {
  // One backfill at a time; live fills keep flowing meanwhile.
  backfilling ??= backfill()
    .catch((error: unknown) => {
      console.error('Fill backfill failed', error);
    })
    .finally(() => {
      backfilling = undefined;
    });
}

ws.on('message', (event) => {
  if (event.channel !== 'userFills') {
    return;
  }
  if (event.data.isSnapshot) {
    // Sent after every (re)subscribe: treat it as a cue, not as data.
    scheduleBackfill();
    return;
  }
  event.data.fills.forEach(handleFill);
});

ws.on('reconnecting', (event) => {
  console.warn('Reconnecting', event.wsKey);
});

ws.on('exception', (event) => {
  console.error('WebSocket exception', event);
});

await ws.subscribe({ type: 'userFills', user });
```

A few notes on the design:

- Snapshots are ignored as data. After a process restart your in-memory `seen` map is empty, so booking snapshot fills directly would repeat fills you stored before the restart. The REST backfill from your persisted checkpoint covers the same ground safely.
- Live fills and the backfill can overlap. A live message may arrive while the REST call is in flight. Both paths go through `handleFill()`, so each `tid` is processed once.
- The `seen` map is pruned. Only recent IDs matter for overlap, so an hour is plenty. Keep it longer if your own downtime can be longer, and persist the checkpoint, not the map.
- `aggregateByTime` stays off. The subscription and `getUserFillsByTime()` both accept it. Leave it off on both if you dedupe by `tid`, so the two paths return the same per-fill records.

We checked the pattern live: starting from a checkpoint one minute in the past, the tracker processed 339 fills, then the socket was forced closed and the SDK reconnected. The repeated snapshot triggered a backfill, nothing was processed twice, and a final REST query over the same window returned the same 339 fills, none missing.

## Connections and reconnect events

`WebsocketClient` reconnects and resubscribes on its own (with heartbeats and a backoff you can tune through `reconnectTimeout`, `maxReconnectTimeout`, `pingInterval` and `pongTimeout`), and emits `reconnecting` and `reconnected` with a `wsKey`. Which key you see depends on the subscription. `userFills` messages include the user address, so they share the `public` connection with market data. `orderUpdates`, `userEvents` and `notification` messages don’t, so the SDK opens one connection per address for them, keyed `user:0x...`.

```typescript
const client = new WebsocketClient({});
client.on('reconnected', (event) => {
  // 'public' for userFills, 'user:0x...' for orderUpdates
  console.log('Reconnected', event.wsKey);
});

await client.subscribe([
  { type: 'userFills', user },
  { type: 'orderUpdates', user },
]);
```

If you track orders and fills together, run the same idea for both: on a reconnect of either connection, reconcile from REST rather than trusting the stream to have been complete.

## Hyperliquid userFills checklist

- Subscribe with the account address (for an API wallet setup, the main account or sub-account address, not the API wallet address).
- Test for snapshots with `event.data.isSnapshot`; live messages don’t carry the field.
- Expect a fresh snapshot after every reconnect, with fills you have already seen.
- Dedupe on `tid` and persist a time checkpoint.
- Backfill with `getUserFillsByTime()` from the checkpoint, paging by the last `time`.
- Keep `aggregateByTime` the same (off) on the stream and in REST.
- If downtime could exceed the 10,000 most recent fills, reconcile positions from account state rather than fills.

---

Originally published on the [Siebly blog](https://blog.siebly.io/hyperliquid-userfills-snapshot-reconnect-nodejs/). The SDK is open source on [GitHub](https://github.com/sieblyio/hyperliquid-api), and the [account streams guide](https://sieblyio.github.io/docs/hyperliquid/guides/private-streams.html) in the docs covers the same subscription.
