Overview
Durable Objects provide low-latency coordination and consistent storage for stateful applications. Each Durable Object has a unique ID and guaranteed single-instance execution.What are Durable Objects?
Durable Objects are:- Stateful - Maintain in-memory state and persistent storage
- Single-threaded - One instance per ID, no concurrency within an object
- Globally distributed - Automatically placed close to users
- Strongly consistent - All requests to an object see the same state
Use Cases
Real-time Collaboration
- Collaborative editing (docs, whiteboards)
- Multiplayer games
- Chat rooms and messaging
- Live cursors and presence
Coordination
- Distributed locks
- Leader election
- Rate limiting per user
- Sequential processing
State Management
- User sessions
- Shopping carts
- Connection pooling
- Cached aggregations
Real-time Features
- WebSocket connections
- Server-sent events
- Live updates and notifications
- Presence tracking
Migrations
Durable Objects use migrations to track class bindings and lifecycle.Configuration
Define Durable Objects in your wrangler.json:wrangler.json
Migration Types
- New Classes
- Rename Classes
- Delete Classes
- Transfer
Add a new Durable Object class:Creates new classes that can be instantiated.
Implementation
Basic Durable Object
Create a simple counter:Worker Integration
Access Durable Objects from your Worker:ID Generation
- Named IDs
- Random IDs
- String IDs
Create deterministic IDs from strings:Use Cases:
- User-specific objects
- Room/channel IDs
- Resource-based routing
Storage API
Key-Value Operations
Transactions
Use transactions for atomic operations:Alarms
Schedule future work:WebSockets
Handle real-time connections:Lifecycle Handlers
Best Practices
State Management
- Keep in-memory state small
- Persist critical data to storage
- Use blockConcurrencyWhile() for initialization
- Clean up unused data regularly
Performance
- Batch storage operations
- Use transactions for atomicity
- Minimize state.storage calls
- Cache frequently accessed data
Migrations
- Always add migration tags
- Test migrations in preview first
- Use renamed_classes to preserve data
- Never skip migration tags
WebSockets
- Enable hibernation for efficiency
- Handle errors gracefully
- Track connection state
- Implement heartbeat/ping
Concurrency Control
Block Concurrency
Input Gates
Limits
- Storage per object: 50 GB
- CPU time per request: 30 seconds
- Concurrent requests: Serialized (one at a time)
- WebSockets per object: Unlimited
- Alarm frequency: Minimum 30 seconds
Common Patterns
Rate Limiting
Rate Limiting
Distributed Lock
Distributed Lock
Connection Pool
Connection Pool
Related Commands
- Queues - Asynchronous messaging
- KV Storage - Global key-value storage
- D1 Database - SQL database