Agent skill

Durable Objects

by butterbase-ai in butterbase-ai/butterbase-skills

A skill your agent uses when building stateful per-key actors — chat rooms, multiplayer rooms, rate limiters, long-running agents, leaderboards — that need persistent in-memory + storage state…

MITAuto-check passedBackend & APIs

Install Durable Objects

skills CLI
$ npx skills add butterbase-ai/butterbase-skills --skill durable-objects -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install butterbase-ai/butterbase-skills durable-objects --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/butterbase-ai/butterbase-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/durable-objects .claude/skills/durable-objects && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
durable-objects
GitHub stars
534
Token cost
~2.8k tokens
SKILL.md length
744 words
Files
1
Skills in repo
39
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when building stateful per-key actors — chat rooms, multiplayer rooms, rate limiters, long-running agents, leaderboards — that need persistent in-memory + storage state…

  • Works in 10 steps: The mental model → Constraints (read these first) → The class skeleton → …
  • Building stateful per-key actors — chat rooms
  • SKILL.md covers 1. The mental model, 2. Constraints (read these…, 3. The class skeleton and 4. Deploy, plus 6 more sections
  • Needs AI_API_KEY

What it does

Durable Objects is an agent skill from butterbase-ai/butterbase-skills. Use when building stateful per-key actors — chat rooms, multiplayer rooms, rate limiters, long-running agents, leaderboards — that need persistent in-memory + storage state across requests

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Autonomous loops. It works with Cloudflare Durable Objects. The repository describes itself as: Plugin for Butterbase.ai. The licence is MIT.

When your agent uses it

  • Building stateful per-key actors — chat rooms
  • Multiplayer rooms
  • Long-running agents
  • Leaderboards — that need persistent in-memory + storage state across requests

Example prompts

  • “/durable-objects”

Requirements

  • A credential in AI_API_KEY

Workflow steps

10 steps, taken from the step headings in SKILL.md.

  1. The mental model
  2. Constraints (read these first)
  3. The class skeleton
  4. Deploy
  5. Address an instance
  6. Env vars
  7. Lifecycle, listing, deletion
  8. Patterns
  9. Errors
  10. Anti-patterns

What it can do on your machine

Read from SKILL.md and the folder at commit aa8ae69. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript and javascript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • AI_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Durable Objects loads about 2.8k tokens when it runs. Until then it costs about 51 tokens; SKILL.md has 744 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~51
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from butterbase-ai/butterbase-skills at commit aa8ae69, republished under its MIT licence (© butterbase-ai). 744 words, ~2,804 tokens.

Download SKILL.mdSave it as .claude/skills/durable-objects/SKILL.md (or your agent's skills folder).
name
durable-objects
description
Use when building stateful per-key actors — chat rooms, multiplayer rooms, rate limiters, long-running agents, leaderboards — that need persistent in-memory + storage state across requests

Butterbase Durable Objects

Durable Objects (DOs) are stateful per-key actors running on Cloudflare Workers. Each instance has its own in-memory state and a built-in transactional KV store. Use one when state must survive across requests for a single room/user/agent. For stateless work, use a serverless function instead (butterbase-skills:function-dev).

One tool: manage_durable_objects.


1. The mental model

Class: ChatRoom (deployed once)
   │
   ├── instance "lobby"      ─►  in-memory state + state.storage  +  WebSockets
   ├── instance "general"    ─►  separate state, separate sockets
   └── instance "user-123"   ─►  separate again

Each URL  https://<app>.butterbase.dev/_do/chat-room/<instance-id>
gets routed to the instance with that id. State is isolated per id.

A class is shared code; an instance is a unique key (/lobby, /general, /user-123). Different ids = different state. There is no shared cross-instance state.


2. Constraints (read these first)

  • One TypeScript file per class. No npm imports. Only import { ... } from 'cloudflare:workers' is allowed.
  • Exactly one exported class. export class Foo { ... } — no extra exports, no helpers re-exported.
  • PascalCase class name in source; kebab-case for the URL name (e.g. ChatRoom ↔ chat-room).
  • File size: ≤ 5 MB. Total of all DO classes per app: ≤ 10 MB compressed.
  • ≤ 5 DO classes per app (v1).
  • No service bindings yet. Functions reach DOs over HTTP, not via env binding.
  • state.storage keys/values capped at 128 KB. Larger blobs → Butterbase Storage.
  • Browser WebSockets need access_mode: "public". Browsers can't set custom headers on WS upgrade, and the _do/ dispatcher reads auth only from Authorization — ?token= and Sec-WebSocket-Protocol are silently ignored at the dispatcher (unlike the /realtime route, which does accept ?token=). Set the DO public, then read the token from ?token= (or Sec-WebSocket-Protocol) inside fetch() and verify it yourself before accepting the upgrade. Server-to-server callers can still use authenticated/service_key.

3. The class skeleton

typescript
export class ChatRoom {
  constructor(public state: DurableObjectState, public env: Env) {}

  async fetch(req: Request): Promise<Response> {
    if (req.headers.get("Upgrade") === "websocket") {
      const pair = new WebSocketPair();
      this.state.acceptWebSocket(pair[1]);
      return new Response(null, { status: 101, webSocket: pair[0] });
    }

    if (req.method === "POST") {
      // handle plain HTTP
    }

    return Response.json({ ok: true });
  }

  // Optional WebSocket lifecycle hooks — called by the runtime
  async webSocketMessage(ws: WebSocket, msg: string | ArrayBuffer) {
    if (typeof msg !== "string") return;             // guard binary
    for (const peer of this.state.getWebSockets()) {
      try { peer.send(msg); } catch {}
    }
  }

  async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) {}
  async webSocketError(ws: WebSocket, err: Error) {}
}

Key APIs:

APIPurpose
state.storage.get/put/delete/deleteAll/listAsync transactional KV store
state.acceptWebSocket(ws)Hold a WS connection; runtime routes messages to webSocketMessage
state.getWebSockets()All active WS connections for this instance
new WebSocketPair()Returns [client, server] — return client to browser, accept server
this.env.KEYRead DO env vars (set via set_env)

4. Deploy

js
manage_durable_objects({
  app_id: "app_abc123",
  action: "deploy",
  name: "chat-room",                  // kebab-case URL name
  code: "<single TypeScript file>",
  access_mode: "authenticated"        // "public" | "authenticated" (default) | "service_key"
})
// → { id, name, class_name, status: "READY", access_mode, last_deployed_at }

Re-deploying with the same name updates the class; old in-memory state is evicted on next request. Storage persists across redeploys (same instance id = same state.storage).

Access modes
ModeAuth required
publicNone — validate tokens inside fetch() if you need any
authenticated (default)End-user JWT in Authorization: Bearer <token>
service_keyButterbase service key — backend-to-backend

The dispatcher only checks header shape, not validity. For real auth on production DOs, validate the token inside fetch().


5. Address an instance

https://<your-subdomain>.butterbase.dev/_do/<name>/<instance-id>
  • <name> = kebab-case DO name from deploy
  • <instance-id> = anything you choose (/lobby, /user-123, /main)

Both HTTP and WebSocket upgrade work on the same URL.

js
// HTTP
fetch("https://app.butterbase.dev/_do/chat-room/lobby", {
  method: "POST",
  body: JSON.stringify({ user: "alice", text: "hi" })
});

// WebSocket
const ws = new WebSocket("wss://app.butterbase.dev/_do/chat-room/lobby");

Different instance ids → completely separate state. There is no shared global view; if you need one, build it yourself (e.g. a /registry instance that other instances report into).


6. Env vars

Env vars are app-wide across all DO classes. Setting one redeploys the DO Worker — existing in-memory state is evicted, active WS connections drop.

js
manage_durable_objects({ app_id, action: "list_env" })                                  // keys only, never values
manage_durable_objects({ app_id, action: "set_env", key: "AI_API_KEY", value: "sk-..." })
manage_durable_objects({ app_id, action: "delete_env", key: "AI_API_KEY" })
  • Keys must match ^[A-Z_][A-Z0-9_]*$ (UPPER_SNAKE).
  • A key can't collide with a DO class binding (e.g. chat-room reserves CHAT_ROOM).
  • Read in code as this.env.KEY_NAME.

Show full SKILL.md (282 more words)Show less

7. Lifecycle, listing, deletion

js
manage_durable_objects({ app_id, action: "list" })
manage_durable_objects({ app_id, action: "get", name: "chat-room" })             // includes full source + status + error_message
manage_durable_objects({ app_id, action: "delete", name: "chat-room" })          // IRREVERSIBLE: purges all instances + storage
manage_durable_objects({ app_id, action: "usage", name: "chat-room" })           // do_requests, do_cpu_ms (refreshed every 15 min)

Status transitions: PENDING → BUILDING → READY or ERROR (with error_message).


8. Patterns

Chat room (broadcast)
typescript
export class ChatRoom {
  constructor(public state: DurableObjectState, public env: any) {}

  async fetch(req: Request): Promise<Response> {
    if (req.headers.get("Upgrade") === "websocket") {
      const pair = new WebSocketPair();
      this.state.acceptWebSocket(pair[1]);
      const history = (await this.state.storage.get("messages")) ?? [];
      pair[1].send(JSON.stringify({ type: "init", messages: history }));
      return new Response(null, { status: 101, webSocket: pair[0] });
    }
    return Response.json(await this.state.storage.get("messages") ?? []);
  }

  async webSocketMessage(ws: WebSocket, msg: string | ArrayBuffer) {
    if (typeof msg !== "string") return;
    const history: any[] = (await this.state.storage.get("messages")) ?? [];
    const parsed = JSON.parse(msg);
    history.push(parsed);
    await this.state.storage.put("messages", history.slice(-200));
    for (const peer of this.state.getWebSockets()) {
      try { peer.send(msg); } catch {}
    }
  }
}
Sliding-window rate limiter
typescript
export class RateLimiter {
  constructor(public state: DurableObjectState, public env: any) {}

  async fetch(req: Request): Promise<Response> {
    const now = Date.now();
    const window = 60_000;
    const limit = 100;
    const requests: number[] = (await this.state.storage.get("requests")) ?? [];
    const recent = requests.filter(t => now - t < window);
    if (recent.length >= limit) return new Response("rate limit", { status: 429 });
    recent.push(now);
    await this.state.storage.put("requests", recent);
    return Response.json({ ok: true, remaining: limit - recent.length });
  }
}

Address one instance per actor: /_do/rate-limiter/<user-id> or /_do/rate-limiter/<api-key-hash>.

Long-running AI agent
typescript
export class Agent {
  constructor(public state: DurableObjectState, public env: any) {}
  async fetch(req: Request): Promise<Response> {
    const { prompt } = await req.json();
    const r = await fetch(this.env.AI_API_ENDPOINT, {
      method: "POST",
      headers: { Authorization: `Bearer ${this.env.AI_API_KEY}` },
      body: JSON.stringify({ prompt })
    });
    const data = await r.json();
    await this.state.storage.put("last_response", data);
    return Response.json(data);
  }
}

One DO instance per conversation; storage holds the rolling history.

Counter / leaderboard

Each instance is its own counter. /_do/leaderboard/main and /_do/leaderboard/season-2 have independent state — no coordination needed in v1.


9. Errors

Build-time (rejected on deploy):

CodeCause
NO_EXPORTED_CLASSSource doesn't export a class
MULTIPLE_EXPORTSMore than one export, or export of non-class
INVALID_IMPORTImported anything other than cloudflare:workers
CLASS_NAME_PARSE_ERRORTS AST couldn't extract the class name
NAME_REGEX_VIOLATIONname doesn't match ^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$
QUOTA_DO_LIMITAlready 5 classes for this app
BUNDLE_SIZE_EXCEEDED / SOURCE_SIZE_EXCEEDEDOver the 10 MB / 5 MB limits

Runtime / async-deploy:

  • Status ERROR after a deploy → check manage_durable_objects (get) error_message.
  • WebSocket message handler only fires if you called state.acceptWebSocket(ws) — easy to forget.
  • webSocketMessage receives string | ArrayBuffer. Always guard before JSON.parse.

10. Anti-patterns

Don'tDo
Try to share state between instances directlyPick a single "registry" instance and have others fetch into it
Use a DO for stateless HTTP workUse a function — DOs cost more and have stricter constraints
Rely on dispatcher access_mode for real authValidate JWTs inside fetch() for production
Use access_mode: "authenticated" for browser WebSocketsUse public + token-in-query-string + manual validation; browsers can't set headers
Stuff > 128 KB blobs into state.storageUse Butterbase Storage and store the object_id in DO state
Update env vars in tight loopsEach set_env redeploys the Worker — drops connections
Forget redeploy semanticsCode change or env change evicts all instances; storage survives but in-memory caches don't

If a docs/butterbase/00-state.md exists in the working directory, prefer invoking via /butterbase-skills:journey-durable so the journey orchestrator stays in sync.

© butterbase-ai, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/durable-objects of butterbase-ai/butterbase-skills.

Open the folder on GitHubat commit aa8ae69

Compare with similar skills

Durable Objects next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Durable Objects compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Durable Objects this skillbutterbase-ai/butterbase-skills534—~2.8kAutomated safety check: PassMIT
Durable Objectscloudflare/skills3k2 repos~1.5kAutomated safety check: PassApache-2.0
Sandbox Claude InsidearbiterForge/codeArbiter147—~2.4kAutomated safety check: PassAGPL-3.0
Openclaw Agent ReputationLeoYeAI/openclaw-master-skills2.2k—~3.7kAutomated safety check: PassMIT-0
Durable Objectshodgef/apiker1274 repos~1.5kAutomated safety check: PassMIT
Openmaopenma-ai/open-managed-agents315—~854Automated safety check: PassApache-2.0

Similar skills

  • Durable Objects

    cloudflare/skills

    Official

    Build, debug, or review Cloudflare Durable Objects code for persistent state and coordination.

    3k GitHub starsUsed in 2 repos~1.5k tokens
    Backend & APIsAuto-check passed
  • Sandbox Claude Inside

    arbiterForge/codeArbiter

    Run Claude Code INSIDE a ca-sandbox box (--with-claude). An agent skill from arbiterForge/codeArbiter.

    147 GitHub stars~2.4k tokensUpdated 2 days ago
    Backend & APIsAuto-check passed
  • Openclaw Agent Reputation

    LeoYeAI/openclaw-master-skills

    On-chain credit scoring and soulbound identity for autonomous agents

    2.2k GitHub stars~3.7k tokensUpdated 2 mo ago
    Backend & APIsAuto-check passed
  • Durable Objects

    hodgef/apiker

    Create and review Cloudflare Durable Objects. An agent skill from hodgef/apiker.

    127 GitHub starsUsed in 4 repos~1.5k tokens
    Backend & APIsAuto-check passed
  • Openma

    openma-ai/open-managed-agents

    Use the openma platform to build, deploy, and manage AI agents.

    315 GitHub stars~854 tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • Sharehtml Collaboration

    jonesphillip/sharehtml

    A skill your agent uses when a user wants to deploy, update, diff, pull, or review feedback on documents managed with the sharehtml CLI.

    132 GitHub stars~902 tokensUpdated 6 mo ago
    Backend & APIsAuto-check passed

More from butterbase-ai/butterbase-skills

All 39 skills in this repo
  • AI

    butterbase-ai/butterbase-skills

    A skill your agent uses when calling the app's AI gateway from agent tools — chat completions, embeddings, listing models, configuring defaults or BYOK, reading token/cost usage

    534 GitHub stars~1.1k tokensUpdated 2 days ago
    Auto-check passed
  • Auth Setup

    butterbase-ai/butterbase-skills

    A skill your agent uses when configuring OAuth providers (Google/GitHub/Apple/X/etc.), setting up post-login auth hooks, tuning JWT lifetimes, or generating service API keys

    534 GitHub stars~2.2k tokensUpdated 2 days ago
    Auto-check passed
  • Build App

    butterbase-ai/butterbase-skills

    A skill your agent uses when building a new Butterbase app from scratch, creating a full-stack application, or when the user asks to set up a complete backend with database, auth, and deployment

    534 GitHub stars~4.9k tokensUpdated 2 days ago
    Auto-check passed
  • Contributing

    butterbase-ai/butterbase-skills

    A skill your agent uses when contributing to the Butterbase codebase, adding new MCP tools, creating API routes, writing migrations, or understanding the monorepo architecture

    534 GitHub stars~1.5k tokensUpdated 2 days ago
    Auto-check passed
  • Debug Rls

    butterbase-ai/butterbase-skills

    A skill your agent uses when users report access denied errors, see wrong data, RLS policies are not working, or when troubleshooting Row-Level Security issues in Butterbase

    534 GitHub stars~3.5k tokensUpdated 2 days ago
    Auto-check passed
  • Deploy Frontend

    butterbase-ai/butterbase-skills

    A skill your agent uses when deploying a frontend (React, Next.js, or static HTML) to a live URL on Butterbase, or when troubleshooting deployment issues like MIME type errors or blank pages

    534 GitHub stars~2.8k tokensUpdated 2 days ago
    Auto-check passed

Questions about Durable Objects

What does Durable Objects do?

A skill your agent uses when building stateful per-key actors — chat rooms, multiplayer rooms, rate limiters, long-running agents, leaderboards — that need persistent in-memory + storage state…. Durable Objects is an agent skill from butterbase-ai/butterbase-skills.

When should I use Durable Objects?

Durable Objects fits situations like: building stateful per-key actors — chat rooms; multiplayer rooms; long-running agents; leaderboards — that need persistent in-memory + storage state across requests.

How do I install Durable Objects in Claude Code?

Run `npx skills add butterbase-ai/butterbase-skills --skill durable-objects -a claude-code`. Or copy the skill folder (skills/durable-objects in butterbase-ai/butterbase-skills) into .claude/skills/durable-objects in your project. Claude Code loads it when a task matches its description.

How do I install Durable Objects in Codex?

Run `npx skills add butterbase-ai/butterbase-skills --skill durable-objects -a codex`. Or copy the skill folder (skills/durable-objects in butterbase-ai/butterbase-skills) into .agents/skills/durable-objects in your project. Codex loads it when a task matches its description.

Can I use Durable Objects in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add butterbase-ai/butterbase-skills --skill durable-objects -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/durable-objects, .gemini/skills/durable-objects, .github/skills/durable-objects and .opencode/skills/durable-objects in your project.

What does Durable Objects need to run?

Going by SKILL.md and its folder, Durable Objects needs credentials named AI_API_KEY. Our summary lists: A credential in AI_API_KEY.

Does Durable Objects access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Durable Objects safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Durable Objects use?

Durable Objects is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Durable Objects use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Durable Objects?

Skills that share tags, products or a category with Durable Objects: Durable Objects (cloudflare/skills, 3k stars), Sandbox Claude Inside (arbiterForge/codeArbiter, 147 stars), Openclaw Agent Reputation (LeoYeAI/openclaw-master-skills, 2.2k stars) and Durable Objects (hodgef/apiker, 127 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Durable Objects?

butterbase-ai (a GitHub organization) maintains it in butterbase-ai/butterbase-skills, which has 534 GitHub stars. The repository holds 39 skills in this directory. The repository was last updated on October 5, 2026.

Source: butterbase-ai/butterbase-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.