Back to Skills

Cloudflare Workflows

Cloudflare Workflows for durable long-running execution. Use for multi-step workflows, retries, state persistence, or encountering NonRetryableError, execution failed errors.

cloudflareai
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# Cloudflare Workflows

**Status**: Production Ready ✅ | **Last Verified**: 2025-12-27 | **Version**: 3.0.0

**Dependencies**: cloudflare-worker-base (for Worker setup)

**Contents**: [Quick Start](#quick-start-10-minutes) • [Commands](#commands) • [Agents](#agents) • [Core Concepts](#core-concepts) • [Critical Rules](#critical-rules) • [Top Errors](#top-5-errors-critical) • [Common Patterns](#common-patterns) • [When to Load References](#when-to-load-references) • [Limits](#limits--pricing)

---

## Quick Start (10 Minutes)

### 1. Create a Workflow

Use the Cloudflare Workflows starter template:

```bash
npm create cloudflare@latest my-workflow -- --template cloudflare/workflows-starter --git --deploy false
cd my-workflow
```

**What you get:**
- WorkflowEntrypoint class template
- Worker to trigger workflows
- Complete wrangler.jsonc configuration

### 2. Basic Workflow Structure

**src/index.ts:**

```typescript
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';

type Env = {
  MY_WORKFLOW: Workflow;
};

type Params = {
  userId: string;
  email: string;
};

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
  async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
    const { userId, email } = event.payload;

    // Step 1: Do work with automatic retries
    const result = await step.do('process user', async () => {
      return { processed: true, userId };
    });

    // Step 2: Wait before next step
    await step.sleep('wait 1 hour', '1 hour');

    // Step 3: Continue workflow
    await step.do('send email', async () => {
      return { sent: true, email };
    });

    return { completed: true, userId };
  }
}

// Worker to trigger workflow
export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const instance = await env.MY_WORKFLOW.create({
      params: { userId: '123', email: 'user@example.com' }
    });

    return Response.json({
      id: instance.id,
      status: await instance.status()
    });
  }
};
```

**Template**: See `templates/basic-workflow.ts` for complete example

### 3. Configure wrangler.jsonc

```jsonc
{
  "name": "my-workflow",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-22",
  "workflows": [
    {
      "binding": "MY_WORKFLOW",
      "name": "my-workflow",
      "class_name": "MyWorkflow"
    }
  ]
}
```

**Template**: See `templates/wrangler-workflows-config.jsonc`

### 4. Deploy

```bash
npm run deploy
```

---

## Commands

Interactive slash commands for workflow development:

| Command | Description | Use When |
|---------|-------------|----------|
| `/workflow-setup` | Complete wizard for new workflow projects | Starting new project, need full setup |
| `/workflow-create` | Quick scaffolding for workflow classes | Adding workflow to existing project |
| `/workflow-debug` | Interactive debugging with error patterns | Troubleshooting workflow issues |
| `/workflow-test` | Test workflows locally and remotely | Validating workflow behavior |

**Example Usage**:
```
/workflow-setup   # Full guided setup wizard
/workflow-create  # Quick workflow scaffolding
/workflow-debug   # Debug workflow issues
/workflow-test    # Test workflow execution
```

---

## Agents

Autonomous agents for complex workflow tasks:

| Agent | Description | Triggers |
|-------|-------------|----------|
| `workflow-debugger` | Auto-detects and fixes configuration/runtime errors | "debug workflow", "fix workflow errors" |
| `workflow-optimizer` | Analyzes performance, cost, and reliability | "optimize workflow", "improve performance" |
| `workflow-setup-assistant` | Autonomous project scaffolding | "setup workflow", "create first workflow" |

**Key Capabilities**:
- **Debugger**: 6-phase analysis, auto-fix for I/O context, serialization, export issues
- **Optimizer**: Cost analysis, reliability scoring, actionable recommendations
- **Setup Assistant**: Project detection, automatic scaffolding, validation

---

## Scripts

Automation scripts in `scripts/` directory:

| Script | Purpose |
|--------|---------|
| `validate-workflow-config.sh` | Validate wrangler.jsonc configuration |
| `test-workflow.sh` | Create and test workflow instances |
| `benchmark-workflow.sh` | Measure performance and cost |
| `generate-workflow.sh` | Scaffold new workflows from templates |
| `check-workflow-limits.sh` | Validate against Cloudflare limits |

**Usage**:
```bash
./scripts/validate-workflow-config.sh           # Check config
./scripts/test-workflow.sh my-workflow          # Test workflow
./scripts/benchmark-workflow.sh my-workflow 10  # Benchmark 10 runs
./scripts/generate-workflow.sh MyWorkflow       # Generate scaffold
./scripts/check-workflow-limits.sh src/workflows/my-workflow.ts
```

---

## Core Concepts

### WorkflowEntrypoint

Every workflow must extend `WorkflowEntrypoint`:

```typescript
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
  async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
    // Workflow logic here
  }
}
```

**Key Points**:
- `Env`: Environment bindings (KV, D1, etc.)
- `Params`: Typed payload passed when creating workflow instance
- `event`: Contains `id`, `payload`, `timestamp`
- `step`: Methods for durable execution

### Step Methods

All workflow work MUST be done in steps for durability:

```typescript
// step.do - Execute work with automatic retries
await step.do('step name', async () => {
  return { result: 'data' };
});

// step.sleep - Wait for duration
await step.sleep('wait', '1 hour');

// step.sleepUntil - Wait until timestamp
await step.sleepUntil('wait until', Date.now() + 3600000);

// step.waitForEvent - Wait for external event
const event = await step.waitForEvent('payment received', 'payment.completed', {
  timeout: '30 minutes'
});
```

**CRITICAL**: All I/O (fetch, KV, D1, R2) must happen **inside** `step.do()` callbacks!

**Reference**: See `references/workflow-patterns.md` for all patterns

---

## Critical Rules

### Always Do ✅

✅ **Perform all I/O inside step.do()** - Required for durability
✅ **Use named steps** - Makes debugging easier
✅ **Return JSON-serializable data from steps** - Required for state persistence
✅ **Use step.sleep() for delays** - Don't use setTimeout()
✅ **Handle errors explicitly** - Use try/catch in step callbacks
✅ **Use NonRetryableError for permanent failures** - Stops retries

**Workflow Patterns**: See `references/workflow-patterns.md` for:
- Sequential workflows
- Parallel execution
- Event-driven workflows
- Scheduled workflows
- Human-in-the-loop workflows

### Never Do ❌

❌ **Never do I/O outside step.do()** - Will fail with "I/O context" error
❌ **Never use setTimeout() or setInterval()** - Use step.sleep() instead
❌ **Never return non-serializable data** - Functions, Promises, etc. will fail
❌ **Never hardcode timeouts** - Use workflow config
❌ **Never ignore NonRetryableError** - Indicates permanent failure

---

## Top 5 Critical Errors

### Error #1: I/O Context Error ⚠️

**Error:**
```
Cannot perform I/O on behalf of a different request
```

**Cause:** Performing I/O outside `step.do()` callback

**Solution:**
```typescript
// ❌ WRONG
const data = await fetch('https://api.example.com');
await step.do('use data', async () => {
  return data; // Error!
});

// ✅ CORRECT
const data = await step.do('fetch data', async () => {
  const response = await fetch('https://api.example.com');
  return await response.json();
});
```

### Error #2: Serialization Error

**Error:**
```
Cannot serialize workflow state
```

**Cause:** Returning non-JSON-serializable data from step

**Solution:**
```typescript
// ❌ WRONG
await step.do('process', async () => {
  return { fn: () => {} }; // Functions not serializable
});

// ✅ CORRECT
await step.do('process', async () => {
  return { result: 'data' }; // JSON-serializable
});
```

### Error #3: NonRetryableError Not Thrown

**Error:** Workflow retries forever on permanent failures

**Solution:**
```typescript
import { NonRetryableError } from 'cloudflare:workers';

await step.do('validate', async () => {
  if (!isValid) {
    throw new NonRetryableError('Invalid input'); // Stop retries
  }
  return { valid: true };
});
```

### Error #4: WorkflowEvent Not Found

**Error:**
```
WorkflowEvent 'payment.completed' not found
```

**Cause:** Event name mismatch between `waitForEvent` and trigger

**Solution:**
```typescript
// Workflow waits for event
const event = await step.waitForEvent('wait payment', 'payment.completed', {
  timeout: '30 minutes'
});

// Trigger event with EXACT same name
await instance.trigger('payment.completed', { amount: 100 });
```

### Error #5: Workflow Execution Failed

**Error:**
```
Workflow execution failed: Step timeout exceeded
```

**Cause:** Step exceeds maximum CPU time (30 seconds)

**Solution:**
```typescript
// ❌ WRONG
await step.do('long task', async () => {
  for (let i = 0; i < 1000000; i++) {
    // Long computation
  }
});

// ✅ CORRECT - Break into smaller steps
for (let i = 0; i < 100; i++) {
  await step.do(`batch ${i}`, async () => {
    // Process batch
  });
}
```

---

**All Issues**: See `references/common-issues.md` for complete documentation

---

## Common Patterns

### Sequential Workflow

Basic workflow with steps executing in order. Each step completes before the next begins.

**Use cases**: Order processing, user onboarding, data pipelines

**Load `templates/basic-workflow.ts` for complete example**

### Scheduled Workflow

Workflow with time delays between steps using `step.sleep()` or `step.sleepUntil()`.

**Use cases**: Reminder sequences, scheduled tasks, delayed notifications

**Load `templates/scheduled-workflow.ts` for complete example**

### Event-Driven Workflow

Wait for external events with `step.waitForEvent()`. Always set timeout and handle with `NonRetryableError`:

```typescript
const payment = await step.waitForEvent('wait payment', 'payment.completed', {
  timeout: '30 minutes'
});
if (!payment) throw new NonRetryableError('Payment timeout');
```

**Load `templates/workflow-with-events.ts` for complete example**

### Workflow with Retries

Use `NonRetryableError` for permanent failures (404), regular `Error` for transient failures (5xx):

```typescript
const data = await step.do('fetch', async () => {
  const response = await fetch(url);
  if (!response.ok) {
    if (response.status === 404) throw new NonRetryableError('Not found');
    throw new Error('Temporary failure'); // Will retry
  }
  return await response.json();
});
```

**Load `templates/workflow-with-retries.ts` for complete example with retry configuration**

---

## Triggering Workflows

**From Worker**: Create instances via `env.MY_WORKFLOW.create()`, get status with `instance.status()`, trigger events with `instance.trigger()`.

**From Cron**: Use `scheduled()` handler to create workflow instances on schedule.

**Load `templates/worker-trigger.ts` for complete Worker trigger example**
**Load `templates/scheduled-workflow.ts` for complete Cron trigger example**

---

## When to Load References

**`references/common-issues.md`**: Encountering I/O context, serialization, NonRetryableError, event naming, or timeout errors; troubleshooting workflow failures.

**`references/workflow-patterns.md`**: Building complex orchestration, approval workflows, idempotency patterns, or circuit breaker patterns.

**`references/wrangler-commands.md`**: Need CLI commands for managing workflow instances, debugging stuck workflows, or monitoring production.

**`references/production-checklist.md`**: Preparing for deployment, need pre-deployment verification, setting up monitoring/error handling.

**`references/limits-quotas.md`**: Hitting instance/step/payload limits, optimizing for cost, designing high-volume workflows.

**`references/2025-features.md`**: Using events system, enhanced retries, instance lifecycle control, or latest Workflows features.

**`references/metrics-analytics.md`**: Setting up monitoring, custom metrics, external logging integration, or workflow dashboards.

**`references/troubleshooting.md`**: Complex debugging scenarios, stuck instances, systematic diagnosis, performance issues.

**`templates/`**: **basic-workflow.ts** (sequential), **scheduled-workflow.ts** (delays/sleep), **workflow-with-events.ts** (waitForEvent), **workflow-with-retries.ts** (custom retry), **worker-trigger.ts** (Worker triggers), **wrangler-workflows-config.jsonc** (Wrangler config), **parallel-execution-workflow.ts** (batched parallel processing), **circuit-breaker-workflow.ts** (resilient external calls)

---

## Wrangler Commands

**Key Commands**: `wrangler workflows create`, `wrangler workflows instances list/describe/terminate`, `wrangler deploy`

**Load `references/wrangler-commands.md` for complete CLI reference with all workflow management commands, monitoring workflows, and debugging stuck instances.**

---

## State Persistence

Workflows automatically persist state between steps. No manual state management needed:

```typescript
export class StatefulWorkflow extends WorkflowEntrypoint {
  async run(event, step) {
    // Step 1 result is automatically persisted
    const result1 = await step.do('step 1', async () => {
      return { data: 'value' };
    });

    // Even if workflow crashes here, step 1 won't re-run
    await step.sleep('wait', '1 hour');

    // Step 2 can use step 1's result (still available after sleep)
    await step.do('step 2', async () => {
      console.log(result1.data); // 'value' - persisted!
    });
  }
}
```

**Key Points**:
- Step results automatically persisted
- Completed steps never re-run (even after crash/restart)
- State available throughout workflow lifetime

---

## Limits

| Resource | Limit |
|----------|-------|
| **Step CPU Time** | 30 seconds |
| **Workflow Duration** | 30 days |
| **Step Payload Size** | 128 KB |
| **Workflow Payload Size** | 128 KB |
| **Steps per Workflow** | 1,000 |
| **Concurrent Instances** | 1,000 per workflow |
| **Event Payload Size** | 128 KB |

**Workarounds**:
- Large data: Store in KV/R2, pass key in step
- Long CPU: Break into smaller steps
- Many steps: Consider sub-workflows

## Pricing

- **Duration**: $0.02 per million GB-s (same as Workers)
- **Requests**: $0.15 per million (workflow creation + step execution)
- **State Storage**: Included (no additional cost)
- **Sleep**: Free (no CPU usage during sleep)

**Example Cost** (1M workflow runs):
- 5 steps each = 5M requests = $0.75
- 10ms per step = 50GB-s = $0.001
- **Total**: ~$0.75 per million workflows

---

## Troubleshooting

### "I/O context" error
**Solution**: Move all I/O into `step.do()` callbacks → See `references/common-issues.md` #1

### "Serialization error"
**Solution**: Return only JSON-serializable data from steps → See `references/common-issues.md` #2

### Workflow retries forever
**Solution**: Throw `NonRetryableError` for permanent failures → See `references/common-issues.md` #3

### "WorkflowEvent not found"
**Solution**: Ensure event names match exactly → See `references/common-issues.md` #4

### "Step timeout exceeded"
**Solution**: Break long computations into smaller steps → See `references/common-issues.md` #5

---

## Production Checklist

**10-Point Pre-Deployment Checklist**: I/O context isolation, JSON serialization, NonRetryableError usage, event name consistency, step duration limits, error handling, retry configuration, timeouts, workflow naming, and monitoring.

**Load `references/production-checklist.md` for complete checklist with detailed explanations, code examples, verification steps, and deployment workflow.**

---

## Official Documentation

**Workflows**: https://developers.cloudflare.com/workflows/ • **API Reference**: https://developers.cloudflare.com/workflows/reference/ • **Examples**: https://developers.cloudflare.com/workflows/examples/ • **Blog**: https://blog.cloudflare.com/cloudflare-workflows/

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-cloudflare-workflows.md
  4. Use /claude-skills-cloudflare-workflows in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub