Durable Objects with WebSockets
WebSockets allow real time communication between a client and server. Both Cloudflare Durable Objects and Workers can act as WebSocket endpoints – either as a client or as a server.
If your application needs to coordinate among multiple WebSocket connections, such as a chat room or game match, you will need clients to send messages to a single-point-of-coordination on a server.
Durable Objects provide a single-point-of-coordination for Cloudflare Workers, and are often used in parallel with WebSockets to persist state over multiple clients and connections.
While there are other use cases for using Workers exclusively with WebSockets, WebSockets are most useful when combined with Durable Objects.
When a client connects to your application using a WebSocket, you need a way for server-generated messages to be sent using the existing socket connection. Multiple clients can establish a WebSocket connection with a specific Durable Object addressed by its unique ID. The Durable Object can then send messages to each client over the WebSocket connection.
Durable Objects can use the web standard APIs described in WebSockets API. Refer to Cloudflare Edge Chat Demo ↗ for an example of using Durable Objects with WebSockets.
The WebSocket Hibernation 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”).
A Durable Object with WebSockets created via the Hibernation API will not incur billable Duration (GB-s) charges during periods of inactivity, unlike Durable Objects using the regular WebSockets API.
The WebSocket Hibernation API includes:
- Cloudflare-specific extensions to the web standard WebSocket API.
- Related methods on the
state
of the Durable Object. - Handler methods that a Durable Object can implement for processing WebSocket events.
The WebSocket Hibernation 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 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.
- Refer to Build a WebSocket server with WebSocket Hibernation to learn more about building a WebSocket server using WebSocket Hibernation on Durable Objects and Workers.