skip to content

With Durable Object WebSocket Hibernation, how do you answer clients' application-level "ping" heartbeats without waking the object?

level: middleimportance: nice to knowfreq 14%

answer

  1. a fixed request, a fixed reply
  2. set once, for every socket
  3. exact text match only
  4. a timestamp kept per socket

basics

~10 s

Call this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")). The runtime then answers any text message exactly equal to "ping" with "pong" on every hibernation-accepted socket, without waking the object or adding duration charges.

solid answer

~40 s

`this.ctx.setWebSocketAutoResponse()` takes a `WebSocketRequestResponsePair(request, response)` and applies it to every socket the object accepted with `ctx.acceptWebSocket()`. When a text message equals the request string exactly (case-sensitive, and never a binary message), the runtime sends the response itself: a hibernated object stays hibernated, and auto-responses add no wall-clock duration. Each string may be at most 2,048 characters. The constructor is the usual place to set it. To find dead clients, `this.ctx.getWebSocketAutoResponseTimestamp(ws)` returns when that socket was last auto-answered, or `null`. Calling `setWebSocketAutoResponse()` with no argument removes the pair. Protocol-level Ping frames are a separate matter: the runtime answers those automatically, they never reach `webSocketMessage()`, and they don't interrupt hibernation either.

code

javascript · 41 lines
javascript
import { DurableObject } from "cloudflare:workers";

export class ChatRoom extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env);
    this.ctx.setWebSocketAutoResponse(
      new WebSocketRequestResponsePair("ping", "pong"),
    );
  }

  async fetch(request) {
    const [client, server] = Object.values(new WebSocketPair());
    this.ctx.acceptWebSocket(server);
    return new Response(null, { status: 101, webSocket: client });
  }

  async webSocketMessage(ws, message) {
    const cutoff = Date.now() - 60_000;
    for (const peer of this.ctx.getWebSockets()) {
      const last = this.ctx.getWebSocketAutoResponseTimestamp(peer);
      if (peer !== ws && last !== null && last.getTime() < cutoff) {
        peer.close(4000, "heartbeat timeout");
      }
    }
    ws.send(`ok: ${message}`);
  }

  async webSocketClose(ws, code, reason) {
    ws.close(code, reason);
  }
}

export default {
  async fetch(request, env) {
    if (request.headers.get("Upgrade") !== "websocket") {
      return new Response("Expected Upgrade: websocket", { status: 426 });
    }
    const room = new URL(request.url).searchParams.get("room") ?? "lobby";
    return env.CHAT_ROOM.getByName(room).fetch(request);
  },
};

go deeper

for a junior

Recall the call: setWebSocketAutoResponse() with a WebSocketRequestResponsePair, usually set in the constructor.

for a middle

Explain exact text matching, the 2,048-character limit on each string, and how a protocol Ping frame differs from an application "ping" message.

for a senior

Show how getWebSocketAutoResponseTimestamp() lets the object close silent clients on its next wake without ever running a timer.

for a principal

Weigh client-driven heartbeats answered by the runtime against server-driven ones, which would keep every room awake and billed.

## Two kinds of heartbeat Long-lived WebSockets need some proof of life, and two quite different mechanisms go by the name "ping". | | Protocol Ping frame | Application "ping" message | |---|---|---| | What it is | a WebSocket control frame | an ordinary text message the client sends | | Who answers in a Durable Object | the runtime, automatically | your code, unless an auto-response is set | | Reaches `webSocketMessage()` | never | yes, unless it matches the auto-response | | Wakes a hibernated object | no | yes, unless it matches the auto-response | Browser scripts cannot send protocol Ping frames, so many clients send an application message such as `"ping"` on a timer instead. Without help, each of those messages would wake a hibernated room, run its constructor and then the handler, and bill duration, all to send back `"pong"`. Across thousands of clients pinging every 30 seconds, the heartbeats alone would keep the room awake. ## Setting up an auto-response 1. Create the pair: `new WebSocketRequestResponsePair("ping", "pong")`. 2. Pass it to `this.ctx.setWebSocketAutoResponse(pair)`, usually in the constructor, next to other setup. 3. From then on, every socket the object accepted with `this.ctx.acceptWebSocket()` gets `"pong"` back for a `"ping"`, whether the object is hibernated or awake. 4. To remove it, call `this.ctx.setWebSocketAutoResponse()` with no argument. `this.ctx.getWebSocketAutoResponse()` returns the current pair, or `null` when none is set, and the pair's `getRequest()` and `getResponse()` methods read its two strings. The client side is a plain timer: send `"ping"` every so often, and treat a missing `"pong"` within a few seconds as a dead connection that needs a reconnect. ## Matching rules and limits - The comparison is an **exact** match against a **text** message. `"PING"`, `"ping "` and a binary frame holding the bytes of `ping` all go to `webSocketMessage()` instead. - There is one pair per object, applied to all of its hibernation-accepted sockets. - The request and the response are each limited to 2,048 characters; a longer one makes the call throw a `RangeError`. - The reply goes only to the socket that sent the request. - Auto-responses add no wall-clock time to the object, so they add no duration charges. - Sockets accepted with the standard `ws.accept()` get no auto-response at all. ## Detecting dead clients The runtime records, for each socket, when it last sent an auto-response, and it records it even while the object is hibernated. `this.ctx.getWebSocketAutoResponseTimestamp(ws)` returns that `Date`, or `null` if the socket never received one. That lets the object find silent clients without running anything on a schedule: - On the next handler run, loop over `this.ctx.getWebSockets()`. - Compare each socket's timestamp against a cutoff, such as one minute ago. - Close the ones that have gone quiet, for example with `peer.close(4000, "heartbeat timeout")`. Close codes from 4000 to 4999 are left to applications, so the client can tell this close from a server error. A socket that has never sent a heartbeat returns `null`; decide explicitly whether that means "just connected" or "dead", because the sweep treats them differently. The sweep piggybacks on whatever wakes the object next, so a completely silent room is never swept. That is harmless: a room nobody writes to costs nothing in duration while it hibernates, and its silent sockets are swept by the first real message. ## Why not a server-side timer The obvious alternative, a `setInterval()` in the object that pings every client, defeats hibernation. A pending timer callback cannot be recreated after eviction, so the runtime keeps the object in memory and bills duration around the clock. Client-sent heartbeats answered by the auto-response invert that: the clients keep the connection warm, the runtime answers them, and the object wakes only for messages that need code. The auto-response is deliberately narrow. It cannot inspect a payload, count anything or reply differently per client. Anything smarter, such as a heartbeat that carries a sequence number or a presence update, is a real message and belongs in `webSocketMessage()`. Because there is one pair per object, the heartbeat string is part of the contract between client and server. If a release changes it, clients still running the old build send heartbeats that no longer match, and each of those wakes the object until the tab reloads.

  • Why not run a setInterval() in the object that pings every client instead?
    A pending `setTimeout()` or `setInterval()` callback keeps a Durable Object from hibernating, because the runtime cannot recreate the timer after eviction. The room would stay in memory and billed for duration around the clock. Let the clients send the heartbeat and let the auto-response answer it.
  • Can the object learn when a heartbeat was answered, given that its code never ran?
    Yes, per socket. `this.ctx.getWebSocketAutoResponseTimestamp(ws)` returns the `Date` of the last auto-response on that socket, or `null`. The runtime records it even while the object is hibernated, so the next handler run can compare it with a cutoff and close silent clients.

  • Expects the auto-response to match "PING" or "ping " as well as "ping".
  • Runs a setInterval() in the object to ping every client and still expects hibernation.
  • Thinks protocol Ping frames reach webSocketMessage() and need code to answer them.
  • Believes every auto-answered heartbeat wakes the object and bills duration.