Overview
Durable Objects provide:- Strong consistency guarantees
- Transactional storage with the Storage API
- Persistent state across requests
- Real-time coordination via WebSockets
- Alarms for scheduled execution
- Optional hibernation for cost efficiency
src/workerd/api/actor-state.h and actor-state.c++
Defining a Durable Object
Create a Durable Object class:Accessing Durable Objects
Access Durable Objects through namespace bindings:Durable Object IDs
ID from name
Derive a deterministic ID from a name:ID from string
Parse an ID from its string representation:New unique ID
Generate a new unique ID:src/workerd/api/samples/durable-objects-chat/chat.js:147
Storage API
The storage API provides transactional key-value storage:Get
Retrieve values:src/workerd/api/actor-state.h:54
Put
Store values:Delete
Remove values:List
List stored keys:src/workerd/api/actor-state.h:67
Transactions
Perform atomic operations:Alarms
Schedule future execution:Get alarm
Check current alarm time:src/workerd/api/actor-state.h:65
Delete alarm
Cancel a scheduled alarm:WebSocket coordination
Coordinate real-time communication:src/workerd/api/samples/durable-objects-chat/chat.js:213
Hibernatable WebSockets
Reduce memory usage with hibernation:Patterns
Singleton coordination
Use a single Durable Object for global state:Per-user state
Store state for each user:Rate limiting
Implement distributed rate limiting:src/workerd/api/samples/durable-objects-chat/chat.js:451
Best practices
Keep state small
Keep state small
Durable Objects are designed for coordination, not bulk storage:
Use transactions for atomic updates
Use transactions for atomic updates
Ensure consistency with transactions:
Handle WebSocket cleanup
Handle WebSocket cleanup
Clean up resources when connections close:
Use hibernation for many connections
Use hibernation for many connections
Reduce memory usage with hibernatable WebSockets:
Storage options
Control caching and consistency:src/workerd/api/actor-state.h:42
Implementation details
Durable Objects are implemented in:src/workerd/api/actor-state.h/.c++- Storage API (1800+ lines)src/workerd/api/actor.h/.c++- Durable Object infrastructuresrc/workerd/io/actor-cache.h/.c++- LRU cache layer over storagesrc/workerd/io/actor-sqlite.h/.c++- SQLite-backed storage
Related APIs
- WebSocket API - Real-time communication
- KV storage - Global key-value storage
- SQL API - SQL database for Durable Objects