Skip to content
Development
Command

/do-patterns

Interactive Durable Objects pattern selection wizard. Helps choose the right DO pattern for your use case and generates implementation code with best practices.

From plugin
secondsky-claude-skills
20466 skills46 agents66 commands
Install
$ npx -y skills add secondsky/claude-skills --agent claude-code

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/do-patterns

Context preview

What this command does when you run it.

Interactive Durable Objects pattern selection wizard. Helps choose the right DO pattern for your use case and generates implementation code with best practices.

Command definition

do-patterns.md
name: cloudflare-durable-objects:patterns
description: Interactive Durable Objects pattern selection wizard. Helps choose the right DO pattern for your use case and generates implementation code with best practices.

/do-patterns - Pattern Selection Wizard

Interactive wizard to help select and implement the optimal Durable Objects pattern for your specific use case.

Overview

This command guides you through: 1. Understanding your requirements 2. Recommending appropriate DO patterns 3. Generating pattern-specific implementation 4. Providing testing and deployment guidance

Step 1: Understand Use Case

Use AskUserQuestion tool:

Question 1: Primary Use Case

**header**: "Use Case" **question**: "What is your primary use case for Durable Objects?" **multiSelect**: false **options**:

  • label: "Real-time communication (WebSocket)"

description: "Chat rooms, collaborative editing, multiplayer games, live updates"

  • label: "State coordination"

description: "Leader election, distributed locking, workflow orchestration"

  • label: "Per-user/per-entity state"

description: "User sessions, shopping carts, user profiles, device state"

  • label: "Rate limiting / throttling"

description: "API rate limiting, DDoS prevention, quota management"

  • label: "Data aggregation"

description: "Analytics, counters, leaderboards, metrics collection"

  • label: "Caching with consistency"

description: "Distributed cache, cache-aside pattern, write-through cache"

Question 2: Scale Requirements

**header**: "Scale" **question**: "What scale do you expect?" **multiSelect**: false **options**:

  • label: "Small (<1K instances)"

description: "Prototype, small app, specific use case"

  • label: "Medium (1K-100K instances)"

description: "Growing app, moderate traffic"

  • label: "Large (100K-1M instances)"

description: "High traffic app, many users"

  • label: "Very Large (>1M instances)"

description: "Enterprise scale, global application"

Question 3: Data Persistence

**header**: "Persistence" **question**: "What are your data persistence requirements?" **multiSelect**: false **options**:

  • label: "Ephemeral (in-memory only)"

description: "Data can be lost, rebuilt from external sources"

  • label: "Session-based (TTL cleanup)"

description: "Data expires after period of inactivity"

  • label: "Permanent (long-term storage)"

description: "Data must persist indefinitely"

  • label: "Hybrid (mix of ephemeral and permanent)"

description: "Some data temporary, some permanent"

Question 4: Query Complexity

**header**: "Queries" **question**: "What type of data queries do you need?" **multiSelect**: false **options**:

  • label: "Simple key-value lookups"

description: "Get/set by key, no complex queries"

  • label: "Basic filtering and sorting"

description: "Filter by single field, simple WHERE clauses"

  • label: "Complex queries with joins"

description: "Multi-table queries, aggregations, GROUP BY"

  • label: "Full-text search"

description: "Search across text fields"

Step 2: Pattern Recommendation

Based on answers, recommend appropriate pattern:

WebSocket Chat Room Pattern

**When**: Real-time communication + Medium-Large scale **Storage**: Hybrid (connection state ephemeral, messages permanent) **Queries**: Basic filtering

**Key Features**:

  • WebSocket Hibernation API for cost efficiency
  • Broadcast to all connected clients
  • Message history with SQL storage
  • Automatic connection cleanup

**Template**: Load `templates/websocket-hibernation-do.ts`

**Implementation**:

import { DurableObject } from 'cloudflare:workers';

export class ChatRoom extends DurableObject {
  private sessions: Map<WebSocket, { userId: string }> = new Map();

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);

    // Initialize SQL schema
    this.ctx.blockConcurrencyWhile(async () => {
      await this.ctx.storage.sql.exec(`
        CREATE TABLE IF NOT EXISTS messages (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          user_id TEXT NOT NULL,
          content TEXT NOT NULL,
          created_at INTEGER NOT NULL
        )
      `);

      await this.ctx.storage.sql.exec(`
        CREATE INDEX IF NOT EXISTS idx_created
        ON messages(created_at DESC)
      `);
    });
  }

  async fetch(request: Request): Promise<Response> {
    // Handle WebSocket upgrade
    if (request.headers.get('Upgrade') === 'websocket') {
      const pair = new WebSocketPair();
      this.ctx.acceptWebSocket(pair[1]);
      return new Response(null, { status: 101, webSocket: pair[0] });
    }

    // Handle HTTP requests (message history, etc.)
    const url = new URL(request.url);

    if (url.pathname === '/messages') {
      const messages = await this.ctx.storage.sql.exec(
        'SELECT * FROM messages ORDER BY created_at DESC LIMIT 50'
      );
      return Response.json(messages.rows);
    }

    return new Response('Not found', { status: 404 });
  }

  async webSocketMessage(ws: WebSocket, message: string) {
    const data = JSON.parse(message);
    const session = this.sessions.get(ws);

    if (!session) return;

    // Store message
    await this.ctx.storage.sql.exec(
      'INSERT INTO messages (user_id, content, created_at) VALUES (?, ?, ?)',
      session.userId,
      data.content,
      Date.now()
    );

    // Broadcast to all connections
    const broadcast = JSON.stringify({
      userId: session.userId,
      content: data.content,
      timestamp: Date.now()
    });

    for (const [client] of this.sessions) {
      client.send(broadcast);
    }
  }

  async webSocketOpen(ws: WebSocket) {
    const userId = crypto.randomUUID(); // Or from auth
    this.sessions.set(ws, { userId });
  }

  async webSocketClose(ws: WebSocket) {
    this.sessions.delete(ws);
  }
}

**wrangler.jsonc**:

{
  "durable_objects": {
    "bindings": [
      {
        "name": "CHAT_ROOM",
        "class_name": "ChatRoom"
      }
    ]
  },
  "migrations": [
    {
      "ta
Read more
Ships withsecondsky-claude-skills

142 production-ready skills for Claude Code CLI ๐Ÿ”Œ Platform / Harness Support These plugins ship as Claude Code marketplace plugins (.claude-plugin/ manifests) and Codex CLI plugins (.codex-plugin/ manifests).

Get the whole plugin, auto-invoked