Skip to content
Development
Command

/do-optimize

Interactive Durable Objects performance optimization assistant. Analyzes existing DO code and provides specific optimization recommendations with implementation guidance.

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-optimize

Context preview

What this command does when you run it.

Interactive Durable Objects performance optimization assistant. Analyzes existing DO code and provides specific optimization recommendations with implementation guidance.

Command definition

do-optimize.md
name: cloudflare-durable-objects:optimize
description: Interactive Durable Objects performance optimization assistant. Analyzes existing DO code and provides specific optimization recommendations with implementation guidance.

/do-optimize - Performance Optimization Assistant

Interactive assistant that analyzes your Durable Objects code and provides targeted performance optimizations.

Overview

This command: 1. Analyzes existing DO implementations 2. Identifies performance bottlenecks 3. Provides specific optimization recommendations 4. Generates optimized code 5. Measures potential performance improvements

Step 1: Identify Optimization Area

Use AskUserQuestion tool:

Question 1: Performance Issue

**header**: "Issue Type" **question**: "What performance issue are you experiencing?" **multiSelect**: false **options**:

  • label: "Slow cold starts / initialization"

description: "DO takes too long to start up or respond to first request"

  • label: "Slow query performance"

description: "SQL queries are taking too long"

  • label: "High memory usage"

description: "DO is using too much memory or hitting limits"

  • label: "WebSocket latency"

description: "WebSocket messages have high latency or dropped connections"

  • label: "Alarm execution issues"

description: "Alarms are slow, failing, or not executing"

  • label: "General optimization"

description: "Want to improve overall performance"

Question 2: Current Scale

**header**: "Scale" **question**: "What is your current scale?" **multiSelect**: false **options**:

  • label: "Development / Testing"

description: "Local testing, small dataset"

  • label: "Small production (<1K DOs)"

description: "Early production, limited users"

  • label: "Medium production (1K-100K DOs)"

description: "Growing user base"

  • label: "Large production (>100K DOs)"

description: "High traffic, many active instances"

Question 3: Optimization Priority

**header**: "Priority" **question**: "What is most important to optimize?" **multiSelect**: false **options**:

  • label: "Latency (response time)"

description: "Reduce time to first response"

  • label: "Throughput (requests/second)"

description: "Handle more concurrent requests"

  • label: "Cost (compute time)"

description: "Reduce CPU time and costs"

  • label: "Memory efficiency"

description: "Reduce memory usage"

Step 2: Analyze Current Implementation

Read and analyze DO class files:

Constructor Analysis

Check for common anti-patterns:

❌ **Bad Pattern**: Expensive operations in constructor

constructor(ctx: DurableObjectState, env: Env) {
  super(ctx, env);
  this.ctx.blockConcurrencyWhile(async () => {
    // ❌ Multiple slow operations block all requests
    this.config = await this.loadConfigFromAPI();
    this.cache = await this.buildLargeCache();
    this.data = await this.loadAllData();
  });
}

✅ **Optimized Pattern**: Minimal constructor, lazy initialization

constructor(ctx: DurableObjectState, env: Env) {
  super(ctx, env);
  // ✅ Only initialize synchronously
  this.config = null;
  this.cache = new Map();
  this.initialized = false;
}

private async ensureInitialized() {
  if (!this.initialized) {
    // ✅ Load on demand, only once
    this.config = await this.loadConfig();
    this.initialized = true;
  }
}

async handleRequest(request: Request) {
  await this.ensureInitialized();
  // Process request...
}

SQL Query Analysis

Check for inefficient queries:

❌ **Bad Pattern**: Missing indexes, N+1 queries

// ❌ No index on user_id - full table scan
const messages = await this.ctx.storage.sql.exec(
  'SELECT * FROM messages WHERE user_id = ?',
  userId
);

// ❌ N+1 query pattern
for (const message of messages.rows) {
  const user = await this.ctx.storage.sql.exec(
    'SELECT * FROM users WHERE id = ?',
    message.user_id
  );
}

✅ **Optimized Pattern**: Proper indexes, batch queries

// ✅ Create index for common queries
await this.ctx.storage.sql.exec(`
  CREATE INDEX IF NOT EXISTS idx_user_messages
  ON messages(user_id, created_at DESC)
`);

// ✅ Single query with JOIN
const result = await this.ctx.storage.sql.exec(`
  SELECT
    m.*,
    u.username,
    u.avatar
  FROM messages m
  JOIN users u ON m.user_id = u.id
  WHERE m.user_id = ?
  ORDER BY m.created_at DESC
  LIMIT 50
`, userId);

WebSocket Optimization Analysis

Check for hibernation blockers:

❌ **Bad Pattern**: Synchronous processing, setTimeout usage

async webSocketMessage(ws: WebSocket, message: string) {
  // ❌ Blocks hibernation with heavy processing
  const result = await this.heavyProcessing(message);
  await this.saveToDatabase(result);
  ws.send(JSON.stringify(result));
}

// ❌ setTimeout prevents hibernation
setTimeout(() => {
  this.cleanup();
}, 60000);

✅ **Optimized Pattern**: Fast wake, async processing, alarms

async webSocketMessage(ws: WebSocket, message: string) {
  // ✅ Minimal processing, queue for async
  this.messageQueue.push({ ws, message });

  // ✅ Process asynchronously, doesn't block hibernation
  this.ctx.waitUntil(this.processQueue());
}

private async processQueue() {
  while (this.messageQueue.length > 0) {
    const { ws, message } = this.messageQueue.shift()!;
    const result = await this.heavyProcessing(message);
    await this.saveToDatabase(result);
    ws.send(JSON.stringify(result));
  }
}

// ✅ Use alarms instead of setTimeout
async alarm() {
  await this.cleanup();
  await this.ctx.storage.setAlarm(Date.now() + 60000);
}

Memory Usage Analysis

Check for memory leaks:

❌ **Bad Pattern**: Unbounded growth, large in-memory cache

class MyDO extends DurableObject {
  // ❌ Grows unbounded
  private allMessages: any[] = [];
  private userCache: Map<string, any> = new Map();

  async addMessage(message: any) {
    this.allMessages.push(message); // ❌ Never cleaned up
    this.userCache.set(message.userId, message.user); // ❌ Unbounded
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
Stats
204
Stars
0
Views
30
Forks
Active
Maintenance
TypeScript
Language
MIT
License
24m ago
Last commit
9mo ago
Created

Repo: secondsky/claude-skills