WebSocket Hibernation Servers: Coordination, Messaging, and Close Handshake
How to run long-lived WebSocket servers on stateful edge actors: hibernation vs pinned connections, upgrades, broadcast, billing, and runtime close behavior.
This page summarizes Cloudflare documentation on building real-time apps with WebSockets on Workers and Durable Objects. The platform treats WebSockets as long-lived TCP sessions for bidirectional communication—typical for chat, live dashboards, multiplayer games, and agent RPC. When many clients must share one room or match, a single Durable Object instance acts as the coordination point; the Hibernation WebSocket API is the recommended way to keep connections open without paying full duration while idle.
WebSocket upgrade: how clients open a real-time connection
Section titled “WebSocket upgrade: how clients open a real-time connection”A WebSocket session starts as an HTTP GET with Upgrade: websocket. A successful handshake returns HTTP status 101 Switching Protocols and a Response that includes the client leg of a WebSocketPair.
Cloudflare supports WebSocket connections, which often involve the 101 Switching Protocols status code. The protocol switch allows clients to establish a WebSocket connection for real-time, bidirectional communication.
— Cloudflare, 1xx Informational
Workers adds a webSocket property to the Response object to support WebSocket connections. This property is present in successful WebSocket handshake responses.
— Cloudflare, Response
On the edge network, proxied WebSocket connections are supported without extra origin configuration; the initial HTTP 101 request can still pass through WAF rules, but after the upgrade, the WAF does not re-inspect traffic (WebSockets network). WebSocket upgrade requests bypass Workers cache (Cache limitations).
Worker routing: validate upgrade before calling a Durable Object
Section titled “Worker routing: validate upgrade before calling a Durable Object”Both Workers and Durable Objects are billed per request. Validate method and headers in the parent Worker so invalid traffic is not charged against a Durable Object (Use WebSockets).
Typical checks:
request.method === "GET"request.headers.get("Upgrade") === "websocket"(otherwise respond with 426)
Then obtain a Durable Object stub (for example getByName("foo")) and return stub.fetch(request). The Durable Object accepts the server socket and returns the client socket in the 101 response. Examples: Build a WebSocket server, Build a seat booking app with SQLite in Durable Objects.
Hibernation WebSocket API vs Web Standard API: which accept method to use
Section titled “Hibernation WebSocket API vs Web Standard API: which accept method to use”Durable Objects expose two patterns (Use WebSockets):
| API | Accept call | Events | Idle cost |
|---|---|---|---|
| Hibernation WebSocket API (recommended for servers) | this.ctx.acceptWebSocket(server) |
webSocketMessage, webSocketClose, webSocketError on the class |
Object can leave memory; connections stay open |
| Web Standard WebSocket API | server.accept() |
addEventListener("message" | "close") on the socket |
Connection pins the object in memory |
WebSocket connections pin your Durable Object to memory, and so duration charges will be incurred so long as the WebSocket is connected (regardless of activity). To avoid duration charges during periods of inactivity, use the WebSocket Hibernation API, which only charges for duration when JavaScript is actively executing.
— Cloudflare, Build a WebSocket server
The WebSocket Hibernation API should be preferred for WebSocket server applications built on Durable Objects, since it significantly decreases duration charge, and provides additional features that pair well with WebSocket applications.
— Cloudflare, Build a WebSocket server with WebSocket Hibernation
Important constraint: hibernation applies when the Durable Object is the server. Outgoing client WebSockets do not hibernate (Build a WebSocket server with WebSocket Hibernation, Use WebSockets).
With hibernation, you must not call ws.accept() separately or rely on addEventListener on that socket—messages go to the Durable Object handlers instead (Durable Object State acceptWebSocket).
How hibernation works after acceptWebSocket
Section titled “How hibernation works after acceptWebSocket”Unlike
ws.accept(),this.ctx.acceptWebSocket(ws)informs the Workers Runtime that the WebSocket is “hibernatable”, so the runtime does not need to pin this Durable Object to memory while the connection is open. During periods of inactivity, the Durable Object can be evicted from memory, but the WebSocket connection will remain open. If at some later point the WebSocket receives a message, the runtime will recreate the Durable Object (run theconstructor) and deliver the message to the appropriate handler.— Cloudflare, Build a WebSocket server with WebSocket Hibernation
After eviction, in-memory fields are lost. Restore per-connection data with serializeAttachment / deserializeAttachment, and reload shared state from the Storage API when needed (Rules of Durable Objects, Use WebSockets). The constructor should rehydrate sessions from this.ctx.getWebSockets() as in the hibernation server example.
Protocol ping frames get automatic pong responses and do not call webSocketMessage or break hibernation (Durable Object Base Class webSocketMessage, Use WebSockets). For application-level heartbeats, setWebSocketAutoResponse can answer fixed request/response pairs without waking the object (Durable Object State, Workers Best Practices).
webSocketMessage and broadcast: chat-style real-time updates
Section titled “webSocketMessage and broadcast: chat-style real-time updates”Hibernatable handlers receive text as string and binary as ArrayBuffer (Durable Object Base Class). List connected peers with this.ctx.getWebSockets()—optionally filtered by tags set in acceptWebSocket(ws, tags) (Durable Object State).
The seat-booking tutorial pattern: after state changes, broadcast JSON to every socket (Build a seat booking app):
private broadcastSeats() { this.ctx.getWebSockets().forEach((ws) => ws.send(this.getSeats()));}The Agents Server class wraps the same idea with onConnect, onMessage, onClose, onError, and broadcast over getConnections() (Agent class internals).
Limits and billing that affect design
Section titled “Limits and billing that affect design”- Up to 32,768 WebSocket connections per Durable Object via hibernation API; practical limits may be lower due to CPU/memory (Durable Object State).
- Incoming Worker WebSocket messages are capped at 32 MiB; larger frames close with code 1009 (WebSockets runtime API).
- Durable Objects bill WebSocket messages at a 20:1 ratio vs ordinary requests (Release notes).
- Pricing examples contrast pinned sockets (high duration) vs hibernation (duration only while JS runs) (Pricing).
Plain Workers can terminate WebSockets but lose them on isolate eviction; long-lived, reliable servers should use Durable Objects with hibernation (Workers Best Practices, What are Durable Objects?).
Close handshake and binaryType: Workers runtime behavior (2026 compatibility)
Section titled “Close handshake and binaryType: Workers runtime behavior (2026 compatibility)”Automatic reciprocal Close frames
Section titled “Automatic reciprocal Close frames”From compatibility date 2026-04-07 (web_socket_auto_reply_to_close), the runtime sends a reciprocal Close frame and sets readyState to CLOSED before the close event (Compatibility flags, WebSockets runtime API).
The Workers runtime now automatically sends a reciprocal Close frame when it receives a Close frame from the peer. The readyState transitions to CLOSED before the close event fires.
— Cloudflare, WebSockets now automatically reply to Close frames
Calling ws.close() in webSocketClose remains safe but is often unnecessary. On older dates, failing to reciprocate close could yield client 1006 abnormal closure (Durable Object Base Class webSocketClose, Errors and exceptions).
allowHalfOpen for WebSocket proxying
Section titled “allowHalfOpen for WebSocket proxying”When a Worker relays between client and backend, automatic close can race. Use server.accept({ allowHalfOpen: true }) so readyState stays CLOSING until you coordinate (Compatibility flags, Preview a web application bridge pattern).
new WebSocket(url) client sockets auto-accept and cannot pass allowHalfOpen; use fetch with Upgrade: websocket, then resp.webSocket.accept({ allowHalfOpen: true }) (Using the WebSockets API).
Binary frames: Blob default vs ArrayBuffer
Section titled “Binary frames: Blob default vs ArrayBuffer”From 2026-03-17 (websocket_standard_binary_type), event-based Worker WebSockets deliver binary frames as Blob by default. Set ws.binaryType = "arraybuffer" before accept() to keep synchronous ArrayBuffer handling, or set no_websocket_standard_binary_type in Wrangler (WebSocket binary messages now delivered as Blob by default).
Hibernatable webSocketMessage on Durable Objects continues to receive binary as ArrayBuffer, unaffected by that flag (WebSockets runtime API).
WebSockets vs SSE and cross-domain auth
Section titled “WebSockets vs SSE and cross-domain auth”For Agents and similar apps, Cloudflare compares transports in HTTP and Server-Sent Events:
| Feature | WebSockets | SSE |
|---|---|---|
| Direction | Bi-directional | Server → client |
| Protocol | ws:// / wss:// |
HTTP |
| Binary | Yes | Text only |
| Best for | Interactive chat, games | Streaming AI responses, notifications |
Recommendation there: WebSockets for interactive apps; SSE for one-way streaming.
Cross-domain WebSocket handshakes cannot send custom headers or Authorization: Bearer on connect (Cross-domain authentication). Use short-lived signed tokens in the URL query and verify in fetch / onConnect; never put raw secrets in URLs. Same-origin clients may use cookies on the handshake.
Clients should use wss:// in production; HTTP 301 on WebSocket connect often means the wrong scheme (Instant Logs FAQ).
Common mistakes
Section titled “Common mistakes”- Using
server.accept()andaddEventListenerfor a multi-client Durable Object server that should hibernate—switches toacceptWebSocketand class handlers (Use WebSockets). - Storing connection-only state only in instance fields—lost on hibernation; use
serializeAttachment(max 16,384 bytes) or Storage (Use WebSockets). - Assuming
instanceof ArrayBufferon Worker event listeners after updating compatibility date—binary may beBlob(WebSocket binary messages now delivered as Blob by default). - Deploying code without expecting all WebSockets to drop—code updates restart Durable Objects and disconnect clients (Use WebSockets); design reconnect and state recovery (WebSockets runtime API).
- Testing hibernation with Vitest per-file isolation—use shared storage (
--max-workers=1 --no-isolate) (Known issues).
How to check this on your site
Section titled “How to check this on your site”-
Run the Worker and Durable Object locally with Wrangler (
wrangler dev) or follow Build a WebSocket server with WebSocket Hibernation. -
Open a client using
wss://(orws://locally) to your/websocketpath with a standards-compliant WebSocket library; confirm the handshake returns 101 and messages echo or broadcast as implemented (Using the WebSockets API). -
Send
ping/pongor yoursetWebSocketAutoResponsepair and verify the object does not need custom handler code for protocol pings (Use WebSockets). -
Close from the client and confirm clean close (
wasClean, code 1000) under your Wrangler compatibility date; if proxying, retest withallowHalfOpen(Compatibility flags). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.