Cloudflare WorkersDurable ObjectsReal-TimeStateful

Cloudflare Workers: Durable Objects for Real-Time State

Build real-time, stateful applications with Cloudflare Durable Objects, covering coordination, WebSocket management, and transactional state.

Alex Chen
Alex Chen
June 8, 202613 min read

TL;DR: Durable Objects are single-instance JavaScript classes that maintain state and coordinate across requests. Unlike stateless Workers, Durable Objects have guaranteed uniqueness -- only one instance exists globally for a given ID. This guide covers use cases (WebSocket rooms, rate limiting, distributed counters), the Durable Object lifecycle, and integration with TanStack Start. For a deeper look at WebSocket connections in Workers, see our Cloudflare Workers WebSocket Guide. Full guide at tanstackship.com.


Introduction

Workers are stateless by design. Each request can go to a different data center. For applications that need coordination -- chat rooms, collaborative editing, distributed counters -- you need a single point of coordination. Durable Objects solve this by providing globally unique, stateful instances. If you're new to Workers, our Cloudflare Workers Introduction provides the foundation needed to understand DO architecture.


Basic Durable Object

ts
export class ChatRoom implements DurableObject {
  private sessions: Map<string, WebSocket> = new Map()

  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url)

    if (url.pathname === '/websocket') {
      const pair = new WebSocketPair()
      const [client, server] = Object.values(pair)

      this.sessions.set(crypto.randomUUID(), server)

      server.accept()
      server.addEventListener('message', (event) => {
        // Broadcast to all connected clients
        this.sessions.forEach((ws) => {
          ws.send(event.data as string)
        })
      })

      return new Response(null, { status: 101, webSocket: client })
    }

    return new Response('Not found', { status: 404 })
  }
}

Durable Object Use Cases

Use CaseState Per ObjectCoordination Pattern
Chat roomConnected WebSocketsBroadcast to all
Rate limiterRequest countersReject on threshold
Game lobbyPlayer listMatchmaking
Document syncOperation logCRDT/OT merge
Distributed counterCounter valueAtomic increment

Conclusion

Durable Objects fill the gap between stateless Workers and traditional databases. They provide single-instance coordination for real-time applications. Use them when you need guaranteed uniqueness and transactional state.

For a step-by-step implementation, check out the Real-Time Chat Application Tutorial. To connect real-time DO data to your frontend, TanStack Query WebSocket Integration shows how to keep your UI in sync with live data.