advanced
Durable Objects
Coordinate per-key stateful edge logic for sessions, collaboration, rate limiting, or strongly ordered operations.
Durable Objects (DO) provide single-threaded, strongly consistent state keyed by an ID — ideal for WebSocket rooms, collaborative editing, per-user rate limiters, or ordered job processing at the edge. Each DO instance serializes requests, giving you in-memory state plus optional SQLite storage without race conditions.
export class ChatRoom {
async fetch(request: Request) {
// single instance per roomId — ordered message handling
const msg = await request.json();
this.messages.push(msg);
return Response.json({ ok: true });
}
}
// wrangler: new ChatRoom() bound to env.ROOM
| Use case | Why DO | |----------|--------| | WebSocket hub | One coordinator per room | | Rate limiter | Accurate per-key counters | | Leader election | Single writer per shard | | Strong ordering | No lost updates vs KV |
Route requests with `idFromName(roomId)` so the same key always hits the same object. DOs hibernate when idle; rehydrate state from storage on wake.
On interviews: DO vs KV vs origin Redis, hibernation, scaling limits per object, WebSocket architecture, and failure recovery.
Common pitfalls: one DO as global bottleneck; CPU-heavy work inside a hot object; forgetting persistence on hibernate; treating DO as general database.
The trade-off is strong per-key consistency and simple coordination versus horizontal scale limits per object and operational complexity.
Checklist:
- Shard hot keys across many DO IDs.
- Persist critical state to DO storage.
- Keep object logic fast and I/O aware.
- Use WebSocket API for real-time fan-out.