durable-objects
Create and review SQLite-backed Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC methods, SQLite storage API, PITR recovery, alarms, WebSocket hibernation, service bindings, or reviewing DO code for best practices. Comprehensive coverage of SQL queries, transactions, namespace API, and testing.
What this skill does
# Durable Objects
Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.
> **Important**: This guide focuses on **SQLite-backed Durable Objects** (recommended for all new projects). Configure with `new_sqlite_classes` in migrations. Legacy KV-backed Durable Objects exist for backwards compatibility but are not covered in detail here to avoid confusion.
## When to Use
- Creating new Durable Object classes for stateful coordination
- Implementing RPC methods, alarms, or WebSocket handlers
- Reviewing existing DO code for best practices
- Configuring wrangler.jsonc/toml for DO bindings and migrations
- Writing tests with `@cloudflare/vitest-pool-workers`
- Designing sharding strategies and parent-child relationships
## Reference Documentation
### Durable Objects Core
- `./references/sqlite-storage.md` - Complete SQLite API, PITR, KV methods, transactions, limits
- `./references/service-bindings.md` - Namespace API, stub creation, RPC methods, service bindings
- `./references/rules.md` - Core rules, storage patterns, concurrency, WebSockets
- `./references/testing.md` - Vitest setup, unit/integration tests, alarm testing
- `./references/workers.md` - Workers handlers, types, wrangler config, observability
### SQLite SQL Features
- `./references/json-functions.md` - Complete JSON API: extract, modify, arrays, objects, generated columns
- `./references/foreign-keys.md` - Foreign key constraints, CASCADE, RESTRICT, SET NULL, deferring constraints
- `./references/sql-statements.md` - SQLite extensions (FTS5, Math), PRAGMA statements, schema introspection
Search: `sql.exec`, `getByName`, `transactionSync`, `ctx.storage.sql`, `blockConcurrencyWhile`
## Core Principles
### Use Durable Objects For
| Need | Example |
|------|---------|
| Coordination | Chat rooms, multiplayer games, collaborative docs |
| Strong consistency | Inventory, booking systems, turn-based games |
| Per-entity storage | Multi-tenant SaaS, per-user data |
| Persistent connections | WebSockets, real-time notifications |
| Scheduled work per entity | Subscription renewals, game timeouts |
### Do NOT Use For
- Stateless request handling (use plain Workers)
- Maximum global distribution needs
- High fan-out independent requests
## Quick Reference
### Wrangler Configuration
```jsonc
// wrangler.jsonc
{
"durable_objects": {
"bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
}
```
### Basic Durable Object Pattern
```typescript
import { DurableObject } from "cloudflare:workers";
export interface Env {
MY_DO: DurableObjectNamespace<MyDurableObject>;
}
export class MyDurableObject extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
this.ctx.storage.sql.exec(`
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
data TEXT NOT NULL
)
`);
});
}
async addItem(data: string): Promise<number> {
const result = this.ctx.storage.sql.exec<{ id: number }>(
"INSERT INTO items (data) VALUES (?) RETURNING id",
data
);
return result.one().id;
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const stub = env.MY_DO.getByName("my-instance");
const id = await stub.addItem("hello");
return Response.json({ id });
},
};
```
## Concurrency Model: Request Queuing
### Single-Threaded Execution
Each Durable Object instance is **single-threaded** and processes requests **one at a time**:
- JavaScript execution is strictly serialized within a DO instance
- No two pieces of code run in parallel on the same DO
- Requests are automatically queued when the DO is busy
- **Soft limit: ~1,000 requests/second per DO instance**
### Input Gates (Automatic Protection)
**Input gates prevent race conditions** by blocking new events during storage operations:
```typescript
async getUniqueNumber(): Promise<number> {
// ✅ Safe from race conditions even without explicit locking
// Input gate blocks other requests during these storage operations
const val = this.ctx.storage.kv.get("counter") ?? 0;
this.ctx.storage.kv.put("counter", val + 1);
return val;
}
```
**While storage operations execute:**
- New incoming requests are queued (blocked from starting)
- No other events delivered except storage completion
- Prevents interleaving of concurrent requests
**Input gates do NOT block:**
- External I/O like `fetch()` (allows event delivery while waiting)
- Multiple storage ops initiated in same call without awaits
### Output Gates (Durability Guarantee)
**Output gates ensure data durability** by holding responses until writes complete:
```typescript
async addUser(name: string): Promise<void> {
// Write without awaiting (fast!)
this.ctx.storage.sql.exec("INSERT INTO users (name) VALUES (?)", name);
// Response held until write confirms
// If write fails, response is discarded and DO restarts
}
```
**While storage writes are in progress:**
- Outgoing responses are held back
- External `fetch()` calls are delayed
- Guarantees writes complete before confirmation sent
- On write failure: DO restarts, messages discarded
### Automatic Write Coalescing
Multiple writes without `await` between them execute atomically:
```typescript
// ✅ All three writes commit together atomically
this.ctx.storage.sql.exec("DELETE FROM temp");
this.ctx.storage.sql.exec("INSERT INTO logs VALUES (?)");
this.ctx.storage.sql.exec("UPDATE counts SET value = value + 1");
// Output gate waits for all writes to confirm
```
### Request Queue Limits
When too many requests arrive at one DO:
- Requests queue internally (bounded queue)
- **Overload errors** returned if queue exceeds limits:
- Too many requests queued (count)
- Too much data queued (bytes)
- Requests queued too long (time)
**Error example:**
```typescript
try {
await stub.doSomething();
} catch (error) {
if (error.overloaded) {
// DO is overloaded - back off and retry
return new Response("Service busy", { status: 429 });
}
}
```
### Automatic In-Memory Caching
Storage API includes automatic caching (several MB per DO):
- `get()` returns instantly if key is cached
- `put()` writes to cache immediately (persists asynchronously)
- Output gates ensure durability before responses sent
- Write coalescing minimizes network round trips
### Best Practices
1. **Don't create global singleton DOs** - Bottleneck at ~1k req/s
2. **Shard by natural keys** - One DO per user/room/game
3. **Minimize per-request work** - Keep operations fast
4. **Don't await between related writes** - Use write coalescing
5. **Avoid `blockConcurrencyWhile()` on every request** - Kills throughput
6. **Handle overload errors gracefully** - Return 429, exponential backoff
See `./references/rules.md` for detailed concurrency patterns.
## Critical Rules
1. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO
2. **Use `getByName()` for deterministic routing** - Same input = same DO instance
3. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations
4. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only
5. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03)
6. **Trust input/output gates** - Write naturally, gates prevent race conditions
7. **One alarm per DO** - `setAlarm()` replaces any existing alarm
## Anti-Patterns (NEVER)
- Single global DO handling all requests (bottleneck)
- Using `blockConcurrencyWhile()` on every request (kills throughput)
- Storing critical state only in memory (lost on eviction/crash)
- Using `await` between related storage writes (breaks atomicity)
- Holding `blockConcurrencyWhile()` across `fetch()` or external I/O
## Stub Creation and RPC Methods
### Get Stub by NRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.