DEV Community

Alex Spinov
Alex Spinov

Posted on

Cloudflare Durable Objects Has a Free API You Should Know About

Cloudflare Durable Objects provide strongly consistent, stateful storage at the edge. Each object has its own storage and can handle WebSocket connections — perfect for real-time collaboration.

Why Durable Objects for Real-Time

A team building collaborative document editing needed strong consistency — multiple users editing the same document simultaneously. Traditional databases added latency. Durable Objects run at the edge with built-in WebSocket support and transactional storage.

Key Features:

  • Strong Consistency — Single-threaded execution per object
  • WebSocket Support — Built-in real-time connections
  • Transactional Storage — ACID transactions per object
  • Global Placement — Object migrates near its users
  • Hibernation — Objects sleep when idle, wake on request

Quick Start

export class ChatRoom {
  state: DurableObjectState
  sessions: WebSocket[] = []

  constructor(state: DurableObjectState) {
    this.state = state
  }

  async fetch(request: Request) {
    const [client, server] = Object.values(new WebSocketPair())
    server.accept()
    this.sessions.push(server)

    server.addEventListener("message", (event) => {
      for (const ws of this.sessions) {
        ws.send(event.data)
      }
    })

    return new Response(null, { status: 101, webSocket: client })
  }
}
Enter fullscreen mode Exit fullscreen mode

Persistent Storage

await this.state.storage.put("count", currentCount + 1)
const count = await this.state.storage.get("count")
Enter fullscreen mode Exit fullscreen mode

Why Choose Durable Objects

  1. Real-time — built-in WebSocket support
  2. Consistent — no race conditions
  3. Edge-native — low latency globally

Check out Durable Objects docs to get started.


Building real-time apps? Check out my Apify actors or email spinov001@gmail.com for custom solutions.

Top comments (0)