Hibernatable WebSockets API
The Hibernatable WebSockets API allows a Durable Object that is not currently running an event handler (such as handling a WebSocket message, HTTP request, or alarms) to be removed from memory while keeping its WebSockets connected (“hibernation”).
Durable Objects WebSockets support includes:
- Cloudflare-specific extensions to the standard WebSocket interface.
- Related methods on the
state
of the Durable Object. - Handler methods that a Durable Object can implement for processing WebSocket events.
The Hibernatable WebSocket API enables you to terminate (not proxy) WebSocket connections within a Durable Object, and push messages to all connected clients based on state stored within the Transactional Storage API, HTTP fetches to external services, and/or data stored in R2 and Workers KV.
For WebSocket proxy use-cases, refer to the standard WebSocket API documentation.
If an event occurs for a hibernated Durable Object’s corresponding handler method, it will return to memory. This will call the Durable Object’s constructor, so it is best to minimize work in the constructor when using WebSocket hibernation.
WebSocket extensions
-
WebSocket.serializeAttachment(valueany)
:void
-
Keeps a copy of
value
in memory (not on disk) to survive hibernation. The value can be any type supported by the structured clone algorithm, which is true of most types. -
If you modify
value
after calling this method, those changes will not be retained unless you call this method again. The serialized size ofvalue
is limited to 2,048 bytes, otherwise this method will throw an error. If you need larger values to survive hibernation, use the Transactional Storage API and pass the corresponding key to this method so it can be retrieved later.
-
-
WebSocket.deserializeAttachment()
:any
- Retrieves the most recent value passed to
serializeAttachment
, ornull
if none exists.
- Retrieves the most recent value passed to
state
methods for WebSockets
-
state.acceptWebSocket(wsWebSocket, tagsArray<string> )
:void
-
Adds a WebSocket to the set attached to this Durable Object.
ws.accept()
must not have been called separately. Once called, any incoming messages will be delivered by calling the Durable Object’swebSocketMessage()
handler, andwebSocketClose()
will be invoked upon disconnect. -
After calling
ws.accept()
, the WebSocket is accepted. Therefore, you can use itssend()
andclose()
methods to send messages. ItsaddEventListener()
method will not ever receive any events as they will be delivered to the Durable Object. -
tags
are optional string tags used to look up the WebSocket withgetWebSockets()
. Each tag is limited to 256 characters, and each WebSocket is limited to 10 tags associated with it. -
The Hibernatable WebSockets API permits a maximum of 32,768 WebSocket connections per Durable Object instance, but the CPU and memory usage of a given workload may further limit the practical number of simultaneous connections.
-
-
state.getWebSockets(tagstring )
:Array<WebSocket>
-
Gets an array of accepted WebSockets matching the given tag. Disconnected WebSockets 1 are automatically removed from the list. Calling
getWebSockets()
with notag
argument will return all WebSockets. -
1
getWebSockets()
may still return websockets even afterws.close()
has been called. For example, if your server-side WebSocket (the Durable Object) sends a close, but does not receive one back (and has not detected a disconnect from the client), then the connection is in theCLOSING
“readyState”. The client might send more messages, so the WebSocket is technically not disconnected.
-
-
state.setWebSocketAutoResponse(webSocketRequestResponsePairWebSocketRequestResponsePair )
:void
-
Sets an application level auto response that does not wake hibernated WebSockets.
-
state.setWebSocketAutoResponse
receivesWebSocketRequestResponsePair(requeststring, responsestring)
as an argument, enabling any WebSocket that was accepted viastate.acceptWebSocket()
belonging to this Object to automatically reply withresponse
when it receives the specifiedrequest
. -
setWebSocketAutoResponse()
is preferable to setting up a server for static ping/pong messages becausesetWebSocketAutoResponse()
handles application level ping/pongs without waking the WebSocket from hibernation, preventing unnecessary duration charges. -
Both
request
andresponse
are limited to 2,048 characters each. -
If
state.setWebSocketAutoResponse()
is set without any argument, it will remove any previously set auto-response configuration. Settingstate.setWebSocketAutoResponse()
without any argument will stop a Durable Object from replying withresponse
for arequest
. It will also stop updating the last timestamp of arequest
, but if there was any auto-response timestamp set, it will remain accessible withstate.getWebSocketAutoResponseTimestamp()
.
-
-
state.getWebSocketAutoResponse()
:Object | null
-
Gets the
WebSocketRequestResponsePair(requeststring, responsestring)
currently set, ornull
if there is none. -
Each
WebSocketRequestResponsePair(requeststring, responsestring)
Object provides methods forgetRequest()
andgetResponse()
.
-
-
state.getWebSocketAutoResponseTimestamp(wsWebSocket)
:Date | null
- Gets the most recent
Date
when the WebSocket received an auto-response request, ornull
if the given WebSocket never received an auto-response request.
- Gets the most recent
webSocketMessage()
handler method
The system calls the webSocketMessage()
method when an accepted WebSocket receives a message.
The method is not called for WebSocket control frames. The system will respond to an incoming
WebSocket protocol ping automatically without interrupting hibernation. The method takes (ws: WebSocket, message: String | ArrayBuffer)
as parameters. It does not return a result and can be async
.
webSocketClose()
handler method
The system calls the webSocketClose()
method when a WebSocket is closed. The method takes (ws: WebSocket, code: number, reason: string, wasClean: boolean)
as parameters. wasClean()
is true if the connection closed cleanly, false otherwise. The method does not return a result and can be async
.
webSocketError()
handler method
The system calls the webSocketError()
method for any non-disconnection related errors. The method takes (ws: WebSocket, error: any)
as parameters. It does not return a result and can be async
.