chat-state-cloudflare-do
Cloudflare Durable Objects state adapter for Chat SDK. Uses a SQLite-backed Durable Object for persistent subscriptions, distributed locking, and caching — with zero external dependencies beyond the Workers runtime.
Installation
Usage
Wrangler configuration
Add the Durable Object binding and migration to your wrangler.jsonc (recommended) or wrangler.toml:
wrangler.jsonc (recommended)
wrangler.toml
Environment type
Configuration
Sharding
A single Durable Object handles approximately 500-1,000 requests per second. For high-traffic bots, use shardKey to distribute load across multiple DO instances:
Locks and subscriptions are per-thread, so sharding by any prefix of the thread ID is safe. Cache operations (get/set/delete) always route to the default shard since their keys are not thread-scoped.
Architecture
The adapter uses a single Durable Object class (ChatStateDO) with three SQLite tables:
subscriptions— thread IDs the bot is subscribed tolocks— distributed locks with token-based ownership and TTLcache— key-value pairs with optional TTL
All operations are single-threaded within a DO instance, providing distributed locking via DO atomicity rather than Lua scripts. Expired entries are cleaned up automatically via the Alarms API.
Each method call creates a fresh DO stub. Stubs are cheap (just a JS object) and the Cloudflare docs recommend creating new stubs rather than reusing them after errors.
Features
- Persistent subscriptions across deployments
- Distributed locking via single-threaded DO atomicity
- Key-value caching with TTL
- Automatic TTL cleanup via Alarms
- Optional sharding for high-traffic bots
- Location hints for latency optimization
- Zero external dependencies (no Redis, no database)
Production recommendations
- Use Smart Placement to co-locate your Worker with the DO
- Monitor DO metrics in the Cloudflare dashboard
- Enable sharding if you expect >500 req/s to a single DO instance
- Use
locationHintto place the DO near your primary user base
Documentation
License
MIT