|
|
před 3 dny | |
|---|---|---|
| .. | ||
| README.md | před 3 dny | |
| api.md | před 3 dny | |
| configuration.md | před 3 dny | |
| gotchas.md | před 3 dny | |
| patterns.md | před 3 dny | |
Expert guidance for building stateful applications with Cloudflare Durable Objects.
Durable Objects combine compute with storage in globally-unique, strongly-consistent packages:
Critical rules preventing most production issues:
ctx.waitUntil() for cleanup - Ensures completion after response sentsetAlarm() for reliable schedulingAll DOs extend DurableObject base class with constructor receiving DurableObjectState (storage, WebSockets, alarms) and Env (bindings).
[Not Created] → [Active] ⇄ [Hibernated] → [Evicted]
↓
[Destroyed]
Workers use bindings to get stubs, then call RPC methods directly (recommended) or use fetch handler (legacy).
RPC vs fetch() decision:
├─ New project + compat ≥2024-04-03 → RPC (type-safe, simpler)
├─ Need HTTP semantics (headers, status) → fetch()
├─ Proxying requests to DO → fetch()
└─ Legacy compatibility → fetch()
See Patterns: RPC vs fetch() for examples.
idFromName(): Deterministic, named coordination (rate limiting, locks)newUniqueId(): Random IDs for sharding high-throughput workloadsidFromString(): Derive from existing IDsWhich storage API?
├─ Structured data, relations, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync KV)
└─ Legacy KV-only DO → ctx.storage (async KV)
See DO Storage for deep dive.
import { DurableObject } from "cloudflare:workers";
export class Counter extends DurableObject<Env> {
async increment(): Promise<number> {
const result = this.ctx.storage.sql.exec(
`INSERT INTO counters (id, value) VALUES (1, 1)
ON CONFLICT(id) DO UPDATE SET value = value + 1
RETURNING value`
).one();
return result.value;
}
}
// Worker access
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const id = env.COUNTER.idFromName("global");
const stub = env.COUNTER.get(id);
const count = await stub.increment();
return new Response(`Count: ${count}`);
}
};
├─ Coordinate requests (rate limit, lock, session)
│ → idFromName(identifier) → [Patterns: Rate Limiting/Locks](./patterns.md)
│
├─ High throughput (>1K req/s)
│ → Sharding with newUniqueId() or hash → [Patterns: Sharding](./patterns.md)
│
├─ Real-time updates (WebSocket, chat, collab)
│ → WebSocket hibernation + room pattern → [Patterns: Real-time](./patterns.md)
│
├─ Background work (cleanup, notifications, scheduled tasks)
│ → Alarms + queue pattern (1 alarm/DO) → [Patterns: Multiple Events](./patterns.md)
│
└─ User sessions with expiration
→ Session pattern + alarm cleanup → [Patterns: Session Management](./patterns.md)
├─ New project + typed methods → RPC (compat ≥2024-04-03)
├─ Need HTTP semantics → fetch()
├─ Proxying to DO → fetch()
└─ Legacy compat → fetch()
See Patterns: RPC vs fetch() for examples.
├─ Structured data, SQL queries, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync API)
└─ Legacy KV-only DO → ctx.storage (async API)
See DO Storage for complete guide.
npx wrangler dev # Local dev with DOs
npx wrangler dev --remote # Test against prod DOs
npx wrangler deploy # Deploy + auto-apply migrations
Docs: https://developers.cloudflare.com/durable-objects/
API Reference: https://developers.cloudflare.com/durable-objects/api/
Examples: https://developers.cloudflare.com/durable-objects/examples/