Use Durable Objects with WebSockets
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.
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 . The Durable Object can then send messages to each client over the WebSocket connection.
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 ) to be removed from memory while keeping its WebSockets connected (“hibernation”).
The WebSocket Hibernation API includes:
- Cloudflare-specific extensions to the web standard WebSocket API.
- Related methods on the of the Durable Object.
- 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 , HTTP fetches to external services, and/or data stored in and .
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.