Skip to content

DurabilitySocketClient

Browser-side RPC, reconnects, replay, and resynchronization.

Import DurabilitySocketClient from durability/client. This browser-safe entry point has no Workers runtime import. Connect it to a DurabilitySocket server.

How it uses your Durable Object

DurabilitySocketClient runs in the browser and stores nothing. Everything durable lives in the one Durable Object a connection talks to:

  • One object per connection. connect(id) builds the URL for one object; your Worker forwards the upgrade, and the object’s fetch(), webSocketMessage(), and webSocketClose() must delegate to its DurabilitySocket. In the example, alarm() also delegates to durability.alarm() so the durable createTodo operations run.
  • The object’s ctx.storage.sql holds the outbound events with their sequence numbers. The client only remembers the last sequence it saw, so a reconnect replays from the object’s table. After a gap the client only fires resync; your handler must reload a snapshot from your own tables, as the example does with list(). The example’s created events come from a best-effort lifecycle hook: if the hook fails or the object crashes after the operation completes, no event is stored, so there is nothing to replay and no gap to trigger resync.
  • The hibernatable WebSocket keeps the subscribed names in its attachment, and the runtime answers keep-alive pings itself, so the object can be evicted while the tab stays connected without the client noticing.
  • The browser tab holds everything else: pending calls, handlers, timers, and the last sequence. A sent call that loses its connection is rejected, never replayed, and a page reload starts from nothing.

How DurabilitySocketClient uses your Durable Object

Shows Your page, Connection, Worker, TodoList, WebSocket, DurabilitySocket, socket events, todos. Focuses on Connection.One Durable ObjectYour pageopenList()Connectionbrowser memoryWorkerauthenticatesTodoListyour Durable ObjectWebSocketattachmentDurabilitySocketin memorysocket eventsctx.storage.sqltodosyour tablerpcupgradestub.fetch()fetch()framesmessageresults, eventsseq rowslist()

1/12 · One connection per object name

connect(listId) builds the URL for that list’s object and returns typed rpc and on proxies. Nothing opens yet: the connection is lazy.

Durable state
Nothing. The client has no storage.
In memory
The connection, its handlers, and its pending calls, in browser memory.
Open source ↗
import { reportFailure, type SerializedError } from '../errors.js';
import { isString } from '../predicates.js';
import {
  parseServerFrame,
  socketProtocolErrorCode,
  socketProtocolVersion,
  type AnyDurabilitySocket,
  type InboundOf,
  type OutboundOf,
  type SocketClientFrame,
  type SocketInboundInput,
  type SocketInboundOutput,
  type SocketOutboundPayload,
  type SocketServerFrame,
} from './protocol.js';
import { SharedTimer } from '../shared-timer.js';
import { exponential, jitter } from '../utils.js';

/** Rejection for calls still waiting when `close()` was called. */
export class SocketClosedError extends Error {
  constructor() {
    super('Socket connection was closed');
    this.name = 'SocketClosedError';
  }
}

/**
 * Rejection for calls that were sent but unanswered when the connection
 * dropped. They are never replayed: the server may or may not have run them.
 */
export class SocketConnectionLostError extends Error {
  constructor(method: string) {
    super(`Connection lost while "${method}" was in flight`);
    this.name = 'SocketConnectionLostError';
  }
}

/** Rejection for calls unanswered within the configured timeout. */
export class SocketTimeoutError extends Error {
  constructor(method: string, timeoutMs: number) {
    super(`"${method}" timed out after ${timeoutMs}ms`);
    this.name = 'SocketTimeoutError';
  }
}

/** The server sent a frame this client cannot interpret; the connection is abandoned. */
export class SocketProtocolError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SocketProtocolError';
  }
}

/** A handler on the server threw; `name` and `message` are the server's. */
export class SocketRemoteError extends Error {
  constructor(error: SerializedError) {
    super(error.message);
    this.name = error.name;
  }
}

export type SocketStatus =
  | 'connecting'
  | 'connected'
  | 'disconnected'
  | 'closed';

/** Wraps every `rpc` call; `next` forwards with the same or a replaced input. */
export type SocketTransform = (call: {
  method: string;
  input: unknown;
  next: (input?: unknown) => Promise<unknown>;
}) => Promise<unknown>;

/** The part of a `WebSocket` the client uses. */
type SocketClientWebSocket = Pick<
  WebSocket,
  'addEventListener' | 'close' | 'send'
>;

export type DurabilitySocketClientConfig = {
  /** Builds the WebSocket URL for one Durable Object. */
  url: (id: string) => string;
  /** Rejects unanswered calls after this long. Defaults to 2 minutes. */
  timeoutMs?: number;
  /** Interval between keep-alive pings; a silent connection is dropped after two. Defaults to 30 seconds. */
  pingIntervalMs?: number;
  /** WebSocket implementation. Defaults to the global `WebSocket`. */
  webSocket?: new (url: string) => SocketClientWebSocket;
};

type RpcMethod<Input, Output> = [Input] extends [void]
  ? () => Promise<Output>
  : (input: Input) => Promise<Output>;

type RpcMethods<Inbound> = {
  [Method in keyof Inbound]: RpcMethod<
    SocketInboundInput<Inbound[Method]>,
    SocketInboundOutput<Inbound[Method]>
  >;
};

type EventHandlers<Outbound> = {
  [Name in keyof Outbound]: (
    handler: (payload: SocketOutboundPayload<Outbound[Name]>) => void
  ) => () => void;
} & {
  /** Observes connection status; the handler runs immediately with the current value. */
  status: (handler: (status: SocketStatus) => void) => () => void;
  /**
   * Fires when subscribers to `names` have no continuous history: on their
   * first subscription, and whenever missed events could not be replayed.
   * Rebuild their state from a snapshot.
   */
  resync: (handler: (info: SocketResync) => void) => () => void;
};

export type SocketResync = { names: string[] };

/** One connection to one Durable Object. */
export type SocketConnection<Socket extends AnyDurabilitySocket> = {
  rpc: RpcMethods<InboundOf<Socket>>;
  on: EventHandlers<OutboundOf<Socket>>;
  readonly status: SocketStatus;
  /** Permanently closes the connection and rejects outstanding calls. */
  close(): void;
};

type PendingCall = {
  method: string;
  text: string;
  sent: boolean;
  resolve: (output: unknown) => void;
  reject: (error: Error) => void;
  cancelTimeout: () => void;
};

const pingText = JSON.stringify({ v: socketProtocolVersion, type: 'ping' });
const pongText = JSON.stringify({ v: socketProtocolVersion, type: 'pong' });

class Connection {
  readonly #config: Required<DurabilitySocketClientConfig>;
  readonly #url: string;
  readonly #transforms: readonly SocketTransform[];
  readonly #pending = new Map<string, PendingCall>();
  readonly #handlers = new Map<string, Set<(payload: unknown) => void>>();
  readonly #statusHandlers = new Set<(status: SocketStatus) => void>();
  readonly #resyncHandlers = new Set<(info: SocketResync) => void>();
  readonly #subscribes = new Map<string, string[]>();
  #acknowledged = new Set<string>();

  #status: SocketStatus = 'disconnected';
  #ws: SocketClientWebSocket | undefined;
  #generation = 0;
  #nextId = 0;
  #lastSeq: number | undefined;
  #attempt = 0;
  // Every pending call holds a timeout, and nothing limits how many are pending.
  readonly #timer = new SharedTimer();
  #cancelRetry: (() => void) | undefined;
  #cancelPing: (() => void) | undefined;
  #lastReceivedAt = 0;

  constructor(
    config: Required<DurabilitySocketClientConfig>,
    id: string,
    transforms: readonly SocketTransform[]
  ) {
    this.#config = config;
    this.#url = config.url(id);
    this.#transforms = transforms;
  }

  get status(): SocketStatus {
    return this.#status;
  }

  call(method: string, input: unknown): Promise<unknown> {
    const run = (index: number, currentInput: unknown): Promise<unknown> => {
      const transform = this.#transforms[index];

      if (!transform) {
        return this.#send(method, currentInput);
      }

      return transform({
        method,
        input: currentInput,
        next: (nextInput = currentInput) => run(index + 1, nextInput),
      });
    };

    return run(0, input);
  }

  on(name: string, handler: (payload: unknown) => void): () => void {
    let handlers = this.#handlers.get(name);

    if (!handlers) {
      handlers = new Set();
      this.#handlers.set(name, handlers);
      this.#subscribe();
    }

    handlers.add(handler);

    return () => {
      handlers.delete(handler);

      if (handlers.size === 0 && this.#handlers.get(name) === handlers) {
        this.#handlers.delete(name);
        this.#subscribe();
      }
    };
  }

  onStatus(handler: (status: SocketStatus) => void): () => void {
    this.#statusHandlers.add(handler);
    handler(this.#status);

    return () => {
      this.#statusHandlers.delete(handler);
    };
  }

  onResync(handler: (info: SocketResync) => void): () => void {
    this.#resyncHandlers.add(handler);

    return () => {
      this.#resyncHandlers.delete(handler);
    };
  }

  close(): void {
    if (this.#status === 'closed') {
      return;
    }

    this.#setStatus('closed');
    this.#stopTimers();
    this.#generation += 1;

    for (const pending of this.#pending.values()) {
      pending.cancelTimeout();
      pending.reject(new SocketClosedError());
    }

    this.#pending.clear();
    this.#handlers.clear();
    this.#statusHandlers.clear();
    this.#resyncHandlers.clear();
    this.#ws?.close(1000, 'Client closed');
    this.#ws = undefined;
  }

  #send(method: string, input: unknown): Promise<unknown> {
    if (this.#status === 'closed') {
      return Promise.reject(new SocketClosedError());
    }

    const id = String(++this.#nextId);

    const frame: SocketClientFrame = {
      v: socketProtocolVersion,
      type: 'call',
      id,
      method,
      input,
    };

    return new Promise((resolve, reject) => {
      const pending: PendingCall = {
        method,
        text: JSON.stringify(frame),
        sent: false,
        resolve,
        reject,
        cancelTimeout: this.#timer.schedule(
          () => {
            this.#pending.delete(id);
            reject(new SocketTimeoutError(method, this.#config.timeoutMs));
          },
          this.#config.timeoutMs
        ),
      };

      this.#pending.set(id, pending);
      this.#flush();
    });
  }

  #subscribe(): void {
    if (this.#status !== 'connected') {
      this.#connect();

      return;
    }

    const names = [...this.#handlers.keys()];

    const frame: Extract<SocketClientFrame, { type: 'subscribe' }> = {
      v: socketProtocolVersion,
      type: 'subscribe',
      id: `subscribe:${++this.#nextId}`,
      names,
    };

    if (this.#lastSeq !== undefined) {
      frame.since = this.#lastSeq;
    }

    this.#subscribes.set(frame.id, names);
    this.#ws?.send(JSON.stringify(frame));
  }

  /** Names whose subscribers start without history: new ones, or all when replay failed. */
  #subscribed(frame: Extract<SocketServerFrame, { type: 'subscribed' }>): void {
    this.#lastSeq = frame.seq;
    const names = this.#subscribes.get(frame.id) ?? [];
    this.#subscribes.delete(frame.id);

    const fresh = frame.replayed
      ? names.filter((name) => !this.#acknowledged.has(name))
      : names;

    this.#acknowledged = new Set(names);

    if (fresh.length === 0) {
      return;
    }

    for (const handler of this.#resyncHandlers) {
      this.#invoke(handler, { names: fresh }, 'resync');
    }
  }

  /** Sends unsent calls; opens the connection first when needed. */
  #flush(): void {
    if (this.#status !== 'connected' || !this.#ws) {
      this.#connect();

      return;
    }

    for (const pending of this.#pending.values()) {
      if (pending.sent) {
        continue;
      }

      pending.sent = true;
      this.#ws.send(pending.text);
    }
  }

  /** Opens a socket unless one is open, opening, or already scheduled by backoff. */
  #connect(): void {
    if (this.#status !== 'disconnected' || this.#cancelRetry !== undefined) {
      return;
    }

    this.#setStatus('connecting');
    const generation = ++this.#generation;
    const ws = new this.#config.webSocket(this.#url);
    this.#ws = ws;
    const current = () => generation === this.#generation;

    ws.addEventListener('open', () => {
      if (!current()) {
        return;
      }

      this.#attempt = 0;
      this.#lastReceivedAt = Date.now();
      this.#setStatus('connected');

      if (this.#handlers.size > 0) {
        this.#subscribe();
      }

      this.#flush();
      this.#startPing();
    });
    ws.addEventListener('message', (message) => {
      if (!current()) {
        return;
      }

      this.#receive(isString(message.data) ? message.data : '');
    });
    ws.addEventListener('close', (closed) => {
      if (!current()) {
        return;
      }

      this.#disconnected(closed.code);
    });
    ws.addEventListener('error', () => {
      if (current()) {
        ws.close();
      }
    });
  }

  #receive(text: string): void {
    this.#lastReceivedAt = Date.now();

    if (text === pongText) {
      return;
    }

    const frame = parseServerFrame(text);

    if (!frame) {
      this.#abandon(new SocketProtocolError('Received an invalid frame'));

      return;
    }

    switch (frame.type) {
      case 'event':
        this.#lastSeq = frame.seq;
        this.#dispatch(frame.name, frame.payload);

        return;
      case 'subscribed':
        this.#subscribed(frame);

        return;
      case 'result':
        this.#settle(frame, (pending) => pending.resolve(frame.output));

        return;
      case 'error':
        if (this.#subscribes.delete(frame.id)) {
          reportFailure('durability.socket.subscribe_failed', {}, frame.error);

          return;
        }

        this.#settle(frame, (pending) =>
          pending.reject(new SocketRemoteError(frame.error))
        );

        return;
    }
  }

  #settle(
    frame: Extract<SocketServerFrame, { id: string }>,
    settle: (pending: PendingCall) => void
  ): void {
    const pending = this.#pending.get(frame.id);

    if (!pending) {
      return;
    }

    this.#pending.delete(frame.id);
    pending.cancelTimeout();
    settle(pending);
  }

  #dispatch(name: string, payload: unknown): void {
    for (const handler of this.#handlers.get(name) ?? []) {
      this.#invoke(handler, payload, name);
    }
  }

  #invoke<Payload>(
    handler: (payload: Payload) => void,
    payload: Payload,
    name: string
  ): void {
    try {
      handler(payload);
    } catch (error) {
      reportFailure('durability.socket.handler_failed', { name }, error);
    }
  }

  #disconnected(code: number): void {
    this.#stopTimers();
    this.#ws = undefined;
    this.#subscribes.clear();

    for (const [id, pending] of this.#pending) {
      if (!pending.sent) {
        continue;
      }

      this.#pending.delete(id);
      pending.cancelTimeout();
      pending.reject(new SocketConnectionLostError(pending.method));
    }

    if (code === socketProtocolErrorCode) {
      this.#abandon(new SocketProtocolError('Server rejected the protocol'));

      return;
    }

    this.#setStatus('disconnected');
    this.#attempt += 1;
    this.#cancelRetry = this.#timer.schedule(
      () => {
        this.#cancelRetry = undefined;
        this.#connect();
      },
      jitter(exponential(this.#attempt, 250, 60_000))
    );
  }

  /** Stops reconnecting after a protocol failure, which a retry cannot fix. */
  #abandon(error: SocketProtocolError): void {
    reportFailure('durability.socket.protocol_error', {}, error);

    for (const pending of this.#pending.values()) {
      pending.cancelTimeout();
      pending.reject(error);
    }

    this.#pending.clear();
    this.close();
  }

  #startPing(): void {
    const interval = this.#config.pingIntervalMs;

    const ping = (): void => {
      // Scheduled before the socket is used, so a close that stops the timers
      // also stops the next ping.
      this.#cancelPing = this.#timer.schedule(ping, interval);

      if (Date.now() - this.#lastReceivedAt > interval * 2) {
        this.#ws?.close(4000, 'Keep-alive timeout');

        return;
      }

      this.#ws?.send(pingText);
    };

    this.#cancelPing = this.#timer.schedule(ping, interval);
  }

  #stopTimers(): void {
    this.#cancelPing?.();
    this.#cancelPing = undefined;
    this.#cancelRetry?.();
    this.#cancelRetry = undefined;
  }

  #setStatus(status: SocketStatus): void {
    if (this.#status === status) {
      return;
    }

    this.#status = status;

    for (const handler of this.#statusHandlers) {
      this.#invoke(handler, status, 'status');
    }
  }
}

const defaultWebSocket = (): (new (url: string) => WebSocket) => {
  if (typeof WebSocket === 'undefined') {
    throw new Error(
      'No WebSocket implementation; pass `webSocket` in the client config'
    );
  }

  return WebSocket;
};

/**
 * Browser client for a {@link DurabilitySocket}. Connections open lazily,
 * reconnect with jittered backoff, and resubscribe from the last seen event.
 *
 * @example
 * ```ts
 * const client = new DurabilitySocketClient<TodoList['socket']>({
 *   url: (id) => `wss://example.com/todos/${id}`,
 * });
 * const conn = client.connect('personal');
 * const todos = await conn.rpc.list();
 * conn.on.created((todo) => render(todo));
 * conn.on.resync(() => reload());
 * ```
 */
export class DurabilitySocketClient<Socket extends AnyDurabilitySocket> {
  readonly #config: Required<DurabilitySocketClientConfig>;
  readonly #transforms: readonly SocketTransform[];

  constructor(
    config: DurabilitySocketClientConfig,
    transforms: readonly SocketTransform[] = []
  ) {
    this.#config = {
      url: config.url,
      timeoutMs: config.timeoutMs ?? 120_000,
      pingIntervalMs: config.pingIntervalMs ?? 30_000,
      webSocket: config.webSocket ?? defaultWebSocket(),
    };
    this.#transforms = transforms;
  }

  /** Returns a client that also applies `transform` around every call. */
  with(transform: SocketTransform): DurabilitySocketClient<Socket> {
    return new DurabilitySocketClient(this.#config, [
      ...this.#transforms,
      transform,
    ]);
  }

  connect(id: string): SocketConnection<Socket> {
    const connection = new Connection(this.#config, id, this.#transforms);

    // SAFETY: the get trap returns a method for every string key, so the
    // empty target is never read.
    const rpc = new Proxy({} as RpcMethods<InboundOf<Socket>>, {
      get: (_target, method) =>
        isString(method)
          ? (input?: unknown) => connection.call(method, input)
          : undefined,
    });

    // SAFETY: the get trap returns a subscriber for every string key, so the
    // empty target is never read.
    const on = new Proxy({} as EventHandlers<OutboundOf<Socket>>, {
      get: (_target, name) => {
        if (name === 'status') {
          return (handler: (status: SocketStatus) => void) =>
            connection.onStatus(handler);
        }

        if (name === 'resync') {
          return (handler: (info: SocketResync) => void) =>
            connection.onResync(handler);
        }

        return isString(name)
          ? (handler: (payload: unknown) => void) =>
              connection.on(name, handler)
          : undefined;
      },
    });

    return {
      rpc,
      on,
      get status() {
        return connection.status;
      },
      close: () => connection.close(),
    };
  }
}

/** One call recorded by {@link logging}: its output if it resolved, or its error. */
export type SocketCallLog =
  | {
      method: string;
      input: unknown;
      output: unknown;
      durationMs: number;
    }
  | {
      method: string;
      input: unknown;
      error: unknown;
      durationMs: number;
    };

/** Logs every call's input, output or error, and duration. */
export const logging =
  (log: (entry: SocketCallLog) => void = console.log): SocketTransform =>
  async ({ method, input, next }) => {
    const startedAt = Date.now();

    try {
      const output = await next();
      log({ method, input, output, durationMs: Date.now() - startedAt });

      return output;
    } catch (error) {
      log({ method, input, error, durationMs: Date.now() - startedAt });
      throw error;
    }
  };

export {
  socketMessageMaps,
  type AnyDurabilitySocket,
  type InboundOf,
  type OutboundOf,
  type SocketInboundInput,
  type SocketInboundOutput,
  type SocketMessageMaps,
  type SocketOutboundPayload,
} from './protocol.js';

Behind the scenes

Durable state: none. A connection keeps its handlers, pending RPCs, subscriptions, and last observed sequence in browser memory. It opens lazily on the first call/subscription, reconnects with jittered backoff, and resubscribes from that in-memory sequence. A page reload loses it.

On disconnect: sent unanswered calls reject with SocketConnectionLostError rather than being replayed; the server may already have performed them. Unsent calls can wait for connection until their local timeout. The default RPC timeout is two minutes, not remote cancellation.

Recovery belongs to the application: on.resync must rebuild affected state from an authoritative snapshot. A snapshot of an already-stale projection cannot repair an event lost before it reached that projection. Explicit close() ends reconnection, removes handlers, and rejects remaining calls.

See live job dashboards for push, replay, snapshots, and the difference between transport recovery and projection reconciliation.

Implementation: socket/client.ts (Connection, DurabilitySocketClient).

Browser client

The browser client derives every method and event type from the socket:

import { DurabilitySocketClient, logging } from 'durability/client';
import type { TodoList } from '../worker'; // type-only: nothing from the Worker is bundled

const client = new DurabilitySocketClient<TodoList['socket']>({
  url: (listId) => `wss://example.com/lists/${listId}/ws`,
}).with(logging());

const conn = client.connect('personal');
const todos = await conn.rpc.list();
await conn.rpc.createTodo({
  id: crypto.randomUUID(),
  payload: { id: 'todo-1', title: 'Ship it', done: false },
});
await conn.rpc.toggle('todo-1');

conn.on.updated((todo) => render(todo));
conn.on.lifecycle((e) => {
  if (e.entityKind === 'operation' && e.type === 'attempt_settled') {
    markSettled(e.id);
  }
});
conn.on.resync(({ names }) => reload(names)); // first subscription, and after an unreplayable gap
conn.on.status((status) => showStatus(status)); // connecting | connected | disconnected | closed
conn.close();

on.resync reports the outbound events whose subscribers have no continuous history: every mapped name on their first subscription, newly added names on a live connection, and all names after an unreplayable gap. Rebuild the affected state from an inbound snapshot call; @durability/tanstack-db does this for collections.

Connections open lazily on the first call or subscription and reconnect with jittered exponential backoff. Calls queued before the socket opens are sent once; calls already sent when the connection drops reject with SocketConnectionLostError and are never replayed, because the server may have run them. Route retried mutations through Durability with a stable idempotency key rather than re-calling. Calls reject with SocketTimeoutError after timeoutMs (default 2 minutes). Server-side handler failures reject with SocketRemoteError, carrying the server error’s name and message. with(transform) returns a new client that wraps every call; transforms receive { method, input, next } and may replace the input.

The client has no channel option. When an object has sockets on several channels, a connection talks to the socket whose fetch accepted its upgrade, so point url at the endpoint your Worker and the object’s fetch() route to that socket. If no socket on that channel is attached, the object closes the connection with code 1011 and the client reconnects with backoff, as after any drop.

durability/client imports nothing from cloudflare:workers and is typechecked against DOM types only. The complete, typechecked version of this example lives in examples/realtime-todos.

Type to search…

↑↓ navigate↵ selectEsc close