Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/durable-objects/README.md
1# Cloudflare Durable Objects23Expert guidance for building stateful applications with Cloudflare Durable Objects.45## Reading Order671. **First time?** Read this overview + Quick Start82. **Setting up?** See [Configuration](./configuration.md)93. **Building features?** Use decision trees below → [Patterns](./patterns.md)104. **Debugging issues?** Check [Gotchas](./gotchas.md)115. **Deep dive?** [API](./api.md) and [DO Storage](../do-storage/README.md)1213## Overview1415Durable Objects combine compute with storage in globally-unique, strongly-consistent packages:16- **Globally unique instances**: Each DO has unique ID for multi-client coordination17- **Co-located storage**: Fast, strongly-consistent storage with compute18- **Automatic placement**: Objects spawn near first request location19- **Stateful serverless**: In-memory state + persistent storage20- **Single-threaded**: Serial request processing (no race conditions)2122## Rules of Durable Objects2324Critical rules preventing most production issues:25261. **One alarm per DO** - Schedule multiple events via queue pattern272. **~1K req/s per DO max** - Shard for higher throughput283. **Constructor runs every wake** - Keep initialization light; use lazy loading294. **Hibernation clears memory** - In-memory state lost; persist critical data305. **Use `ctx.waitUntil()` for cleanup** - Ensures completion after response sent316. **No setTimeout for persistence** - Use `setAlarm()` for reliable scheduling3233## Core Concepts3435### Class Structure36All DOs extend `DurableObject` base class with constructor receiving `DurableObjectState` (storage, WebSockets, alarms) and `Env` (bindings).3738### Lifecycle States3940```41[Not Created] → [Active] ⇄ [Hibernated] → [Evicted]42↓43[Destroyed]44```4546- **Not Created**: DO ID exists but instance never spawned47- **Active**: Processing requests, in-memory state valid, billed per GB-hour48- **Hibernated**: WebSocket connections open but zero compute, zero cost49- **Evicted**: Removed from memory; next request triggers cold start50- **Destroyed**: Data deleted via migration or manual deletion5152### Accessing from Workers53Workers use bindings to get stubs, then call RPC methods directly (recommended) or use fetch handler (legacy).5455**RPC vs fetch() decision:**56```57├─ New project + compat ≥2024-04-03 → RPC (type-safe, simpler)58├─ Need HTTP semantics (headers, status) → fetch()59├─ Proxying requests to DO → fetch()60└─ Legacy compatibility → fetch()61```6263See [Patterns: RPC vs fetch()](./patterns.md) for examples.6465### ID Generation66- `idFromName()`: Deterministic, named coordination (rate limiting, locks)67- `newUniqueId()`: Random IDs for sharding high-throughput workloads68- `idFromString()`: Derive from existing IDs69- Jurisdiction option: Data locality compliance7071### Storage Options7273**Which storage API?**74```75├─ Structured data, relations, transactions → SQLite (recommended)76├─ Simple KV on SQLite DO → ctx.storage.kv (sync KV)77└─ Legacy KV-only DO → ctx.storage (async KV)78```7980- **SQLite** (recommended): Structured data, transactions, 10GB/DO81- **Synchronous KV API**: Simple key-value on SQLite objects82- **Asynchronous KV API**: Legacy/advanced use cases8384See [DO Storage](../do-storage/README.md) for deep dive.8586### Special Features87- **Alarms**: Schedule future execution per-DO (1 per DO - use queue pattern for multiple)88- **WebSocket Hibernation**: Zero-cost idle connections (memory cleared on hibernation)89- **Point-in-Time Recovery**: Restore to any point in 30 days (SQLite only)9091## Quick Start9293```typescript94import { DurableObject } from "cloudflare:workers";9596export class Counter extends DurableObject<Env> {97async increment(): Promise<number> {98const result = this.ctx.storage.sql.exec(99`INSERT INTO counters (id, value) VALUES (1, 1)100ON CONFLICT(id) DO UPDATE SET value = value + 1101RETURNING value`102).one();103return result.value;104}105}106107// Worker access108export default {109async fetch(request: Request, env: Env): Promise<Response> {110const id = env.COUNTER.idFromName("global");111const stub = env.COUNTER.get(id);112const count = await stub.increment();113return new Response(`Count: ${count}`);114}115};116```117118## Decision Trees119120### What do you need?121122```123├─ Coordinate requests (rate limit, lock, session)124│ → idFromName(identifier) → [Patterns: Rate Limiting/Locks](./patterns.md)125│126├─ High throughput (>1K req/s)127│ → Sharding with newUniqueId() or hash → [Patterns: Sharding](./patterns.md)128│129├─ Real-time updates (WebSocket, chat, collab)130│ → WebSocket hibernation + room pattern → [Patterns: Real-time](./patterns.md)131│132├─ Background work (cleanup, notifications, scheduled tasks)133│ → Alarms + queue pattern (1 alarm/DO) → [Patterns: Multiple Events](./patterns.md)134│135└─ User sessions with expiration136→ Session pattern + alarm cleanup → [Patterns: Session Management](./patterns.md)137```138139### Which access pattern?140141```142├─ New project + typed methods → RPC (compat ≥2024-04-03)143├─ Need HTTP semantics → fetch()144├─ Proxying to DO → fetch()145└─ Legacy compat → fetch()146```147148See [Patterns: RPC vs fetch()](./patterns.md) for examples.149150### Which storage?151152```153├─ Structured data, SQL queries, transactions → SQLite (recommended)154├─ Simple KV on SQLite DO → ctx.storage.kv (sync API)155└─ Legacy KV-only DO → ctx.storage (async API)156```157158See [DO Storage](../do-storage/README.md) for complete guide.159160## Essential Commands161162```bash163npx wrangler dev # Local dev with DOs164npx wrangler dev --remote # Test against prod DOs165npx wrangler deploy # Deploy + auto-apply migrations166```167168## Resources169170**Docs**: https://developers.cloudflare.com/durable-objects/171**API Reference**: https://developers.cloudflare.com/durable-objects/api/172**Examples**: https://developers.cloudflare.com/durable-objects/examples/173174## In This Reference175176- **[Configuration](./configuration.md)** - wrangler.jsonc setup, migrations, bindings, environments177- **[API](./api.md)** - Class structure, ctx methods, alarms, WebSocket hibernation178- **[Patterns](./patterns.md)** - Sharding, rate limiting, locks, real-time, sessions179- **[Gotchas](./gotchas.md)** - Limits, hibernation caveats, common errors180181## See Also182183- **[DO Storage](../do-storage/README.md)** - SQLite, KV, transactions (detailed storage guide)184- **[Workers](../workers/README.md)** - Core Workers runtime features185- **[WebSockets](../websockets/README.md)** - WebSocket APIs and patterns186