Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
refactor(cloudflare-workflows): Knowledge-gap audit - Add 14 major 2025 updates, trim to 589 lines
Jez91f1065170bb
diff --git a/skills/cloudflare-workflows/SKILL.md b/skills/cloudflare-workflows/SKILL.mdindex 466945a1..a76219af 100644--- a/skills/cloudflare-workflows/SKILL.md+++ b/skills/cloudflare-workflows/SKILL.md@@ -1,266 +1,102 @@---name: cloudflare-workflowsdescription: |- Build durable, long-running workflows on Cloudflare Workers with automatic retries, state persistence, and- multi-step orchestration. Supports step.do, step.sleep, step.waitForEvent, and runs for hours to days.+ Build durable workflows with Cloudflare Workflows (GA April 2025). Features step.do, step.sleep, waitForEvent,+ Vitest testing, and runs for hours to days with automatic retries and state persistence.Use when: creating long-running workflows, implementing retry logic, building event-driven processes,- coordinating API calls, scheduling multi-step tasks, or troubleshooting NonRetryableError, I/O context,- serialization errors, or workflow execution failures.+ testing workflows with cloudflare:test, coordinating API calls, or troubleshooting NonRetryableError,+ I/O context errors, serialization failures.Keywords: cloudflare workflows, workflows workers, durable execution, workflow step,WorkflowEntrypoint, step.do, step.sleep, workflow retries, NonRetryableError,workflow state, wrangler workflows, workflow events, long-running tasks, step.sleepUntil,- step.waitForEvent, workflow bindings+ step.waitForEvent, workflow bindings, vitest testing, cloudflare:test, introspectWorkflowInstancelicense: MIT---# Cloudflare Workflows-**Status**: Production Ready ✅-**Last Updated**: 2025-10-22+**Status**: Production Ready ✅ (GA since April 2025)+**Last Updated**: 2025-11-25**Dependencies**: cloudflare-worker-base (for Worker setup)-**Latest Versions**: [email protected], @cloudflare/[email protected]+**Latest Versions**: [email protected], @cloudflare/[email protected]------## Quick Start (10 Minutes)+**Recent Updates (2025)**:+- **April 2025**: Workflows GA release - waitForEvent API, Vitest testing, CPU time metrics, 4,500 concurrent instances+- **October 2025**: Instance creation rate 10x faster (100/sec), concurrency increased to 10,000+- **2025 Limits**: Max steps 1,024, state persistence 1MB/step (100MB-1GB per instance), event payloads 1MB, CPU time 5 min max+- **Testing**: cloudflare:test module with introspectWorkflowInstance, disableSleeps, mockStepResult, mockEvent modifiers+- **Platform**: Waiting instances don't count toward concurrency, retention 3-30 days, subrequests 50-1,000-### 1. Create a Workflow+----Use the Cloudflare Workflows starter template:+## Quick Start (5 Minutes)```bash+# 1. Scaffold projectnpm create cloudflare@latest my-workflow -- --template cloudflare/workflows-starter --git --deploy falsecd my-workflow-```--**What you get:**-- WorkflowEntrypoint class template-- Worker to trigger workflows-- Complete wrangler.jsonc configuration--### 2. Understand the Basic 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) {- // Access params from event.payload- const { userId, email } = event.payload;-- // Step 1: Do some work- const result = await step.do('process user', async () => {- return { processed: true, userId };- });-- // Step 2: Wait before next action- await step.sleep('wait 1 hour', '1 hour');-- // Step 3: Continue workflow- await step.do('send email', async () => {- // Send email logic- return { sent: true, email };- });-- // Optional: return final state- return { completed: true, userId };- }-}--// Worker to trigger workflow-export default {- async fetch(req: Request, env: Env): Promise<Response> {- // Create new workflow instance- const instance = await env.MY_WORKFLOW.create({- params: { userId: '123', email: '[email protected]' }- });-- return Response.json({- id: instance.id,- status: await instance.status()- });- }-};-```--### 3. Configure Wrangler--**wrangler.jsonc:**--```jsonc+# 2. Configure wrangler.jsonc{"name": "my-workflow","main": "src/index.ts",- "compatibility_date": "2025-10-22",- "workflows": [- {- "name": "my-workflow",- "binding": "MY_WORKFLOW",- "class_name": "MyWorkflow"- }- ]+ "compatibility_date": "2025-11-25",+ "workflows": [{+ "name": "my-workflow",+ "binding": "MY_WORKFLOW",+ "class_name": "MyWorkflow"+ }]}-```-### 4. Deploy and Test--```bash-# Deploy workflow-npm run deploy--# Trigger workflow (visit in browser or curl)-curl https://my-workflow.<subdomain>.workers.dev/--# View workflow instances-npx wrangler workflows instances list my-workflow--# Check instance status-npx wrangler workflows instances describe my-workflow <instance-id>-```-------## WorkflowEntrypoint Class--### Extend WorkflowEntrypoint--Every Workflow must extend `WorkflowEntrypoint` and implement a `run()` method:+# 3. Create workflow (src/index.ts)+import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';-```typescriptexport class MyWorkflow extends WorkflowEntrypoint<Env, Params> {async run(event: WorkflowEvent<Params>, step: WorkflowStep) {- // Workflow steps here+ const result = await step.do('process', async () => { /* work */ });+ await step.sleep('wait', '1 hour');+ await step.do('continue', async () => { /* more work */ });}}-```--**Type Parameters:**-- `Env` - Environment bindings (KV, D1, R2, etc.)-- `Params` - Type of workflow parameters passed via `event.payload`-### run() Method--```typescript-async run(- event: WorkflowEvent<Params>,- step: WorkflowStep-): Promise<T | void>+# 4. Deploy and test+npm run deploy+npx wrangler workflows instances list my-workflow```-**Parameters:**-- `event` - Contains workflow metadata and payload-- `step` - Provides step methods (do, sleep, sleepUntil, waitForEvent)--**Returns:**-- Optional return value (must be serializable)-- Return value available via instance.status()--**Example:**--```typescript-export class OrderWorkflow extends WorkflowEntrypoint<Env, OrderParams> {- async run(event: WorkflowEvent<OrderParams>, step: WorkflowStep) {- const { orderId, customerId } = event.payload;-- // Access bindings via this.env- const order = await this.env.DB.prepare(- 'SELECT * FROM orders WHERE id = ?'- ).bind(orderId).first();-- const result = await step.do('process payment', async () => {- // Payment processing- return { paid: true, amount: order.total };- });-- // Return final state- return {- orderId,- status: 'completed',- paidAmount: result.amount- };- }-}-```+**CRITICAL**: Extends `WorkflowEntrypoint`, implements `run()` with `step` methods, bindings in wrangler.jsonc---+## Step Methods### step.do() - Execute Work```typescript-step.do<T>(- name: string,- config?: WorkflowStepConfig,- callback: () => Promise<T>-): Promise<T>-```--**OR** (config is optional):--```typescript-step.do<T>(- name: string,- callback: () => Promise<T>-): Promise<T>+step.do<T>(name: string, config?: WorkflowStepConfig, callback: () => Promise<T>): Promise<T>```**Parameters:**- `name` - Step name (for observability)-- `config` (optional) - Retry configuration+- `config` (optional) - Retry configuration (retries, timeout, backoff)- `callback` - Async function that does the work-**Returns:**-- The value returned from callback (must be serializable)+**Returns:** Value from callback (must be serializable)**Example:**-```typescript-// Simple step-const files = await step.do('fetch files', async () => {- const response = await fetch('https://api.example.com/files');- return await response.json();+const result = await step.do('call API', { retries: { limit: 10, delay: '10s', backoff: 'exponential' }, timeout: '5 min' }, async () => {+ return await fetch('https://api.example.com/data').then(r => r.json());});--// Step with retry config-const result = await step.do(- 'call payment API',- {- retries: {- limit: 10,- delay: '10 seconds',- backoff: 'exponential'- },- timeout: '5 minutes'- },- async () => {- const response = await fetch('https://payment-api.example.com/charge', {- method: 'POST',- body: JSON.stringify({ amount: 100 })- });- return await response.json();- }-);```**CRITICAL - Serialization:**-- Return value must be JSON serializable- ✅ Allowed: string, number, boolean, Array, Object, null- ❌ Forbidden: Function, Symbol, circular references, undefined-- Step will throw error if return value isn't serializable+- Throws error if return value isn't JSON serializable---@@ -272,53 +108,24 @@ step.sleep(name: string, duration: WorkflowDuration): Promise<void>**Parameters:**- `name` - Step name-- `duration` - Number (milliseconds) or human-readable string--**Accepted units:**-- `"second"` / `"seconds"`-- `"minute"` / `"minutes"`-- `"hour"` / `"hours"`-- `"day"` / `"days"`-- `"week"` / `"weeks"`-- `"month"` / `"months"`-- `"year"` / `"years"`+- `duration` - Number (ms) or string: `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"year"` (plural forms accepted)**Examples:**-```typescript-// Sleep for 5 minutesawait step.sleep('wait 5 minutes', '5 minutes');--// Sleep for 1 hour-await step.sleep('hourly delay', '1 hour');--// Sleep for 2 days+await step.sleep('wait 1 hour', '1 hour');await step.sleep('wait 2 days', '2 days');--// Sleep using milliseconds-await step.sleep('wait 30 seconds', 30000);--// Common pattern: schedule daily task-await step.do('send daily report', async () => {- // Send report-});-await step.sleep('wait until tomorrow', '1 day');-// Workflow continues next day+await step.sleep('wait 30 seconds', 30000); // milliseconds```-**Priority:**-- Workflows resuming from sleep take priority over new instances-- Ensures older workflows complete before new ones start+**Note:** Resuming workflows take priority over new instances. Sleeps don't count toward step limits.---### step.sleepUntil() - Sleep to Specific Date```typescript-step.sleepUntil(- name: string,- timestamp: Date | number-): Promise<void>+step.sleepUntil(name: string, timestamp: Date | number): Promise<void>```**Parameters:**@@ -326,119 +133,61 @@ step.sleepUntil(- `timestamp` - Date object or UNIX timestamp (milliseconds)**Examples:**-```typescript-// Sleep until specific date-const launchDate = new Date('2025-12-25T00:00:00Z');-await step.sleepUntil('wait for launch', launchDate);--// Sleep until UNIX timestamp-const timestamp = Date.parse('24 Oct 2024 13:00:00 UTC');-await step.sleepUntil('wait until time', timestamp);--// Sleep until next Monday 9am UTC-const nextMonday = new Date();-nextMonday.setDate(nextMonday.getDate() + ((1 + 7 - nextMonday.getDay()) % 7 || 7));-nextMonday.setUTCHours(9, 0, 0, 0);-await step.sleepUntil('wait until Monday 9am', nextMonday);--// Schedule work at specific time-await step.do('prepare campaign', async () => {- // Prepare marketing campaign-});--const campaignLaunch = new Date('2025-11-01T12:00:00Z');-await step.sleepUntil('wait for campaign launch', campaignLaunch);--await step.do('launch campaign', async () => {- // Launch campaign-});+await step.sleepUntil('wait for launch', new Date('2025-12-25T00:00:00Z'));+await step.sleepUntil('wait until time', Date.parse('24 Oct 2024 13:00:00 UTC'));```----### step.waitForEvent() - Wait for External Event+### step.waitForEvent() - Wait for External Event (GA April 2025)```typescript-step.waitForEvent<T>(- name: string,- options: { type: string; timeout?: string | number }-): Promise<T>+step.waitForEvent<T>(name: string, options: { type: string; timeout?: string | number }): Promise<T>```**Parameters:**- `name` - Step name- `options.type` - Event type to match-- `options.timeout` (optional) - Max wait time (default: 24 hours)+- `options.timeout` (optional) - Max wait time (default: 24 hours, max: 30 days)-**Returns:**-- The event payload sent via `instance.sendEvent()`+**Returns:** Event payload sent via `instance.sendEvent()`**Example:**-```typescriptexport class PaymentWorkflow extends WorkflowEntrypoint<Env, Params> {async run(event: WorkflowEvent<Params>, step: WorkflowStep) {- // Create payment intent- await step.do('create payment intent', async () => {- // Call Stripe API- });+ await step.do('create payment', async () => { /* Stripe API */ });- // Wait for webhook from Stripe (max 1 hour)const webhookData = await step.waitForEvent<StripeWebhook>('wait for payment confirmation',{ type: 'stripe-webhook', timeout: '1 hour' });- // Continue based on webhookif (webhookData.status === 'succeeded') {- await step.do('fulfill order', async () => {- // Fulfill order- });- } else {- await step.do('handle failed payment', async () => {- // Handle failure- });+ await step.do('fulfill order', async () => { /* fulfill */ });}}}-// Worker receives webhook and sends event to workflow+// Worker sends event to workflowexport default {async fetch(req: Request, env: Env): Promise<Response> {if (req.url.includes('/webhook/stripe')) {- const webhookData = await req.json();-- // Get workflow instance by ID (stored when created)const instance = await env.PAYMENT_WORKFLOW.get(instanceId);-- // Send event to waiting workflow- await instance.sendEvent({- type: 'stripe-webhook',- payload: webhookData- });-+ await instance.sendEvent({ type: 'stripe-webhook', payload: await req.json() });return new Response('OK');}}};```-**Timeout behavior:**-- If timeout expires, throws error and workflow can retry or fail-- Wrap in try-catch if timeout should not fail workflow-+**Timeout handling:**```typescripttry {- const event = await step.waitForEvent('wait for user input', {- type: 'user-submitted',- timeout: '10 minutes'- });+ const event = await step.waitForEvent('wait for user', { type: 'user-submitted', timeout: '10 minutes' });} catch (error) {- // Timeout occurred - handle gracefully- await step.do('send reminder', async () => {- // Send reminder to user- });+ await step.do('send reminder', async () => { /* reminder */ });}```@@ -446,12 +195,10 @@ try {## WorkflowStepConfig-Configure retry behavior for individual steps:-```typescriptinterface WorkflowStepConfig {retries?: {- limit: number; // Max retry attempts (Infinity allowed)+ limit: number; // Max attempts (Infinity allowed)delay: string | number; // Delay between retriesbackoff?: 'constant' | 'linear' | 'exponential';};@@ -459,110 +206,24 @@ interface WorkflowStepConfig {}```-### Default Configuration--If no config provided, Workflows uses:--```typescript-{- retries: {- limit: 5,- delay: 10000, // 10 seconds- backoff: 'exponential'- },- timeout: '10 minutes'-}-```--### Retry Examples--**Constant Backoff (same delay each time):**--```typescript-await step.do(- 'send email',- {- retries: {- limit: 3,- delay: '30 seconds',- backoff: 'constant' // Always wait 30 seconds- }- },- async () => {- // Send email- }-);-```--**Linear Backoff (increasing delay):**--```typescript-await step.do(- 'poll API',- {- retries: {- limit: 5,- delay: '1 minute',- backoff: 'linear' // 1m, 2m, 3m, 4m, 5m- }- },- async () => {- // Poll API- }-);-```--**Exponential Backoff (recommended for most cases):**+**Default:** `{ retries: { limit: 5, delay: 10000, backoff: 'exponential' }, timeout: '10 minutes' }`+**Backoff Examples:**```typescript-await step.do(- 'call rate-limited API',- {- retries: {- limit: 10,- delay: '10 seconds',- backoff: 'exponential' // 10s, 20s, 40s, 80s, 160s, ...- },- timeout: '5 minutes'- },- async () => {- // API call- }-);-```+// Constant: 30s, 30s, 30s+{ retries: { limit: 3, delay: '30 seconds', backoff: 'constant' } }-**Unlimited Retries:**+// Linear: 1m, 2m, 3m, 4m, 5m+{ retries: { limit: 5, delay: '1 minute', backoff: 'linear' } }-```typescript-await step.do(- 'critical operation',- {- retries: {- limit: Infinity, // Retry forever- delay: '1 minute',- backoff: 'exponential'- }- },- async () => {- // Operation that must succeed eventually- }-);-```+// Exponential (recommended): 10s, 20s, 40s, 80s, 160s+{ retries: { limit: 10, delay: '10 seconds', backoff: 'exponential' }, timeout: '5 minutes' }-**No Retries:**+// Unlimited retries+{ retries: { limit: Infinity, delay: '1 minute', backoff: 'exponential' } }-```typescript-await step.do(- 'non-idempotent operation',- {- retries: {- limit: 0 // Fail immediately on error- }- },- async () => {- // One-time operation- }-);+// No retries+{ retries: { limit: 0 } }```---@@ -613,56 +274,33 @@ export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {### Catch Errors to Continue Workflow-Prevent entire workflow from failing by catching step errors:+Prevent workflow failure by catching optional step errors:```typescriptexport class MyWorkflow extends WorkflowEntrypoint<Env, Params> {async run(event: WorkflowEvent<Params>, step: WorkflowStep) {- // Critical step - workflow fails if this fails- await step.do('process payment', async () => {- // Payment processing- });+ await step.do('process payment', async () => { /* critical */ });- // Optional step - workflow continues even if it failstry {- await step.do('send confirmation email', async () => {- // Email sending- });+ await step.do('send email', async () => { /* optional */ });} catch (error) {- console.log(`Email failed: ${error.message}`);-- // Do cleanup or alternative action- await step.do('log email failure', async () => {- await this.env.DB.prepare(- 'INSERT INTO failed_emails (user_id, error) VALUES (?, ?)'- ).bind(event.payload.userId, error.message).run();+ await step.do('log failure', async () => {+ await this.env.DB.prepare('INSERT INTO failed_emails VALUES (?, ?)').bind(event.payload.userId, error.message).run();});}- // Workflow continues- await step.do('update order status', async () => {- // Update status- });+ await step.do('update status', async () => { /* continues */ });}}```-**Pattern: Graceful degradation:**-+**Graceful Degradation:**```typescript-// Try primary service, fall back to secondarylet result;-try {- result = await step.do('call primary API', async () => {- return await callPrimaryAPI();- });-} catch (error) {- console.log('Primary API failed, trying backup');-- result = await step.do('call backup API', async () => {- return await callBackupAPI();- });+ result = await step.do('call primary API', async () => await callPrimaryAPI());+} catch {+ result = await step.do('call backup API', async () => await callBackupAPI());}```@@ -670,426 +308,81 @@ try {## Triggering Workflows-### From Workers--**Configure binding in wrangler.jsonc:**-+**Configure binding (wrangler.jsonc):**```jsonc{- "name": "trigger-worker",- "main": "src/index.ts",- "compatibility_date": "2025-10-22",- "workflows": [- {- "name": "my-workflow",- "binding": "MY_WORKFLOW",- "class_name": "MyWorkflow",- "script_name": "workflow-worker" // If workflow is in different Worker- }- ]+ "workflows": [{+ "name": "my-workflow",+ "binding": "MY_WORKFLOW",+ "class_name": "MyWorkflow",+ "script_name": "workflow-worker" // If workflow in different Worker+ }]}```**Trigger from Worker:**-```typescript-type Env = {- MY_WORKFLOW: Workflow;-};--export default {- async fetch(req: Request, env: Env): Promise<Response> {- // Create new workflow instance- const instance = await env.MY_WORKFLOW.create({- params: {- userId: '123',- email: '[email protected]'- }- });-- // Return instance ID- return Response.json({- id: instance.id,- status: await instance.status()- });- }-};+const instance = await env.MY_WORKFLOW.create({ params: { userId: '123' } });+return Response.json({ id: instance.id, status: await instance.status() });```-### Get Instance Status-+**Instance Management:**```typescript-// Get instance by IDconst instance = await env.MY_WORKFLOW.get(instanceId);--// Get status-const status = await instance.status();--console.log(status);-// {-// status: 'running' | 'complete' | 'errored' | 'queued' | 'unknown',-// error: string | null,-// output: any // Return value from run() if complete-// }-```--### Send Events to Running Instance--```typescript-// Get instance-const instance = await env.MY_WORKFLOW.get(instanceId);--// Send event (will be received by step.waitForEvent)-await instance.sendEvent({- type: 'user-action',- payload: { action: 'approved' }-});-```--### Pause and Resume--```typescript-// Pause instance+const status = await instance.status(); // { status: 'running'|'complete'|'errored'|'queued', error, output }+await instance.sendEvent({ type: 'user-action', payload: { action: 'approved' } });await instance.pause();--// Resume instanceawait instance.resume();--// Terminate instanceawait instance.terminate();```----## Workflow Patterns--### Pattern 1: Long-Running Process--```typescript-export class VideoProcessingWorkflow extends WorkflowEntrypoint<Env, VideoParams> {- async run(event: WorkflowEvent<VideoParams>, step: WorkflowStep) {- const { videoId } = event.payload;-- // Step 1: Upload to processing service- const uploadResult = await step.do('upload video', async () => {- const video = await this.env.MY_BUCKET.get(`videos/${videoId}`);- const response = await fetch('https://processor.example.com/upload', {- method: 'POST',- body: video?.body- });- return await response.json();- });-- // Step 2: Wait for processing (could take hours)- await step.sleep('wait for initial processing', '10 minutes');-- // Step 3: Poll for completion- let processed = false;- let attempts = 0;-- while (!processed && attempts < 20) {- const status = await step.do(`check status attempt ${attempts}`, async () => {- const response = await fetch(- `https://processor.example.com/status/${uploadResult.jobId}`- );- return await response.json();- });-- if (status.complete) {- processed = true;- } else {- attempts++;- await step.sleep(`wait before retry ${attempts}`, '5 minutes');- }- }-- // Step 4: Download processed video- await step.do('download processed video', async () => {- const response = await fetch(uploadResult.downloadUrl);- const processed = await response.blob();- await this.env.MY_BUCKET.put(`processed/${videoId}`, processed);- });-- return { videoId, status: 'complete' };- }-}-```-------### Pattern 2: Event-Driven Approval Flow--```typescript-export class ApprovalWorkflow extends WorkflowEntrypoint<Env, ApprovalParams> {- async run(event: WorkflowEvent<ApprovalParams>, step: WorkflowStep) {- const { requestId, requesterId } = event.payload;-- // Step 1: Create approval request- await step.do('create approval request', async () => {- await this.env.DB.prepare(- 'INSERT INTO approvals (id, requester_id, status) VALUES (?, ?, ?)'- ).bind(requestId, requesterId, 'pending').run();- });-- // Step 2: Send notification to approvers- await step.do('notify approvers', async () => {- await sendNotification(requestId);- });-- // Step 3: Wait for approval (max 7 days)- let approvalEvent;-- try {- approvalEvent = await step.waitForEvent<ApprovalEvent>(- 'wait for approval decision',- { type: 'approval-decision', timeout: '7 days' }- );- } catch (error) {- // Timeout - auto-reject- await step.do('auto-reject due to timeout', async () => {- await this.env.DB.prepare(- 'UPDATE approvals SET status = ? WHERE id = ?'- ).bind('rejected', requestId).run();- });-- return { requestId, status: 'rejected', reason: 'timeout' };- }-- // Step 4: Process decision- await step.do('process approval decision', async () => {- await this.env.DB.prepare(- 'UPDATE approvals SET status = ?, approver_id = ? WHERE id = ?'- ).bind(approvalEvent.approved ? 'approved' : 'rejected', approvalEvent.approverId, requestId).run();- });-- // Step 5: Execute approved action (if approved)- if (approvalEvent.approved) {- await step.do('execute approved action', async () => {- // Execute the action- });- }-- return { requestId, status: approvalEvent.approved ? 'approved' : 'rejected' };- }-}-```-------### Pattern 3: Scheduled Workflow--```typescript-export class DailyReportWorkflow extends WorkflowEntrypoint<Env, ReportParams> {- async run(event: WorkflowEvent<ReportParams>, step: WorkflowStep) {- // Calculate next 9am UTC- const now = new Date();- const tomorrow9am = new Date();- tomorrow9am.setUTCDate(tomorrow9am.getUTCDate() + 1);- tomorrow9am.setUTCHours(9, 0, 0, 0);-- // Sleep until tomorrow 9am- await step.sleepUntil('wait until 9am tomorrow', tomorrow9am);-- // Generate report- const report = await step.do('generate daily report', async () => {- const results = await this.env.DB.prepare(- 'SELECT * FROM metrics WHERE date = ?'- ).bind(now.toISOString().split('T')[0]).all();-- return {- date: now.toISOString().split('T')[0],- metrics: results.results- };- });-- // Send report- await step.do('send report', async () => {- await sendEmail({- to: event.payload.recipients,- subject: `Daily Report - ${report.date}`,- body: formatReport(report.metrics)- });- });-- return { sent: true, date: report.date };- }-}-```-------### Pattern 4: Workflow Chaining--```typescript-export class OrderWorkflow extends WorkflowEntrypoint<Env, OrderParams> {- async run(event: WorkflowEvent<OrderParams>, step: WorkflowStep) {- const { orderId } = event.payload;-- // Step 1: Process payment- const paymentResult = await step.do('process payment', async () => {- return await processPayment(orderId);- });-- // Step 2: Trigger fulfillment workflow- const fulfillmentInstance = await step.do('start fulfillment', async () => {- return await this.env.FULFILLMENT_WORKFLOW.create({- params: {- orderId,- paymentId: paymentResult.id- }- });- });-- // Step 3: Wait for fulfillment to complete- await step.sleep('wait for fulfillment', '5 minutes');-- // Step 4: Check fulfillment status- const fulfillmentStatus = await step.do('check fulfillment', async () => {- const instance = await this.env.FULFILLMENT_WORKFLOW.get(fulfillmentInstance.id);- return await instance.status();- });-- if (fulfillmentStatus.status === 'complete') {- // Step 5: Send confirmation- await step.do('send order confirmation', async () => {- await sendConfirmation(orderId);- });- }-- return { orderId, status: 'complete' };- }-}-```-------## Wrangler Commands--### List Workflow Instances--```bash-# List all instances of a workflow-npx wrangler workflows instances list my-workflow--# Filter by status-npx wrangler workflows instances list my-workflow --status running-npx wrangler workflows instances list my-workflow --status complete-npx wrangler workflows instances list my-workflow --status errored-```--### Describe Instance--```bash-# Get detailed info about specific instance-npx wrangler workflows instances describe my-workflow <instance-id>--# Output shows:-# - Current status (running/complete/errored)-# - Each step with start/end times-# - Step outputs-# - Retry history-# - Any errors-# - Sleep state (if sleeping)-```--### Trigger Workflow (Development)--```bash-# Deploy workflow-npx wrangler deploy--# Trigger via HTTP (if Worker is set up to trigger)-curl https://my-workflow.<subdomain>.workers.dev/-```-----## State Persistence-### What Can Be Persisted-Workflows automatically persist state returned from `step.do()`:-**✅ Serializable Types:**+**✅ Serializable:**- Primitives: `string`, `number`, `boolean`, `null`-- Arrays: `[1, 2, 3]`, `['a', 'b', 'c']`-- Objects: `{ key: 'value' }`, `{ nested: { data: true } }`-- Nested structures: `{ users: [{ id: 1, name: 'Alice' }] }`+- Arrays, Objects, Nested structures-**❌ Non-Serializable Types:**-- Functions: `() => {}`-- Symbols: `Symbol('key')`-- Circular references: `const obj = {}; obj.self = obj;`-- undefined (use null instead)-- Class instances (serialize to plain objects)--**Example - Correct Serialization:**+**❌ Non-Serializable:**+- Functions, Symbols, circular references, undefined, class instances+**Example:**```typescript-// ✅ Good - all values serializable-const result = await step.do('fetch data', async () => {- return {- users: [- { id: 1, name: 'Alice', active: true },- { id: 2, name: 'Bob', active: false }- ],- timestamp: Date.now(),- metadata: null- };-});+// ✅ Good+const result = await step.do('fetch data', async () => ({+ users: [{ id: 1, name: 'Alice' }],+ timestamp: Date.now(),+ metadata: null+}));-// ❌ Bad - contains function-const bad = await step.do('bad example', async () => {- return {- data: [1, 2, 3],- transform: (x) => x * 2 // ❌ Function not serializable- };-});-// This will throw an error!+// ❌ Bad - function not serializable+const bad = await step.do('bad', async () => ({ data: [1, 2, 3], transform: (x) => x * 2 })); // Throws error!```-### Access State Across Steps-+**Access State Across Steps:**```typescript-export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {- async run(event: WorkflowEvent<Params>, step: WorkflowStep) {- // Step 1: Get data- const userData = await step.do('fetch user', async () => {- return { id: 123, email: '[email protected]' };- });-- // Step 2: Use data from step 1- const orderData = await step.do('create order', async () => {- return {- userId: userData.id, // ✅ Access previous step's data- userEmail: userData.email,- orderId: 'ORD-456'- };- });-- // Step 3: Use data from step 1 and 2- await step.do('send confirmation', async () => {- await sendEmail({- to: userData.email, // ✅ Still accessible- subject: `Order ${orderData.orderId} confirmed`- });- });- }-}+const userData = await step.do('fetch user', async () => ({ id: 123, email: '[email protected]' }));+const orderData = await step.do('create order', async () => ({ userId: userData.id, orderId: 'ORD-456' }));+await step.do('send email', async () => sendEmail({ to: userData.email, subject: `Order ${orderData.orderId}` }));```---## Observability-### Built-in Metrics+### Built-in Metrics (Enhanced in 2025)Workflows automatically track:-- **Instance status**: queued, running, complete, errored, paused+- **Instance status**: queued, running, complete, errored, paused, waiting- **Step execution**: start/end times, duration, success/failure- **Retry history**: attempts, errors, delays- **Sleep state**: when workflow will wake up- **Output**: return values from steps and run()+- **CPU time** (GA April 2025): Active processing time per instance for billing insights### View Metrics in Dashboard@@ -1103,43 +396,59 @@ Access via Cloudflare dashboard:- Success/error rates- Average execution time- Step-level performance+- **CPU time consumption** (2025 feature)### Programmatic Access```typescript-// Get instance statusconst instance = await env.MY_WORKFLOW.get(instanceId);const status = await instance.status();console.log(status);// {-// status: 'complete',-// error: null,+// status: 'complete' | 'running' | 'errored' | 'queued' | 'waiting' | 'unknown',+// error: string | null,// output: { userId: '123', status: 'processed' }// }```+**CPU Time Configuration (2025):**+```jsonc+// wrangler.jsonc+{ "limits": { "cpu_ms": 300000 } } // 5 minutes max (default: 30 seconds)+```+----## Limits--| Feature | Limit |-|---------|-------|-| **Max workflow duration** | 30 days |-| **Max steps per workflow** | 10,000 |-| **Max sleep/sleepUntil duration** | 30 days |-| **Max step timeout** | 15 minutes |-| **Max concurrent instances** | Unlimited (autoscales) |-| **Max payload size** | 128 KB |-| **Max step output size** | 128 KB |-| **Max waitForEvent timeout** | 30 days |-| **Max retry limit** | Infinity (configurable) |--**Notes:**-- `step.sleep()` and `step.sleepUntil()` do NOT count toward 10,000 step limit-- Workflows can run for up to 30 days total-- Each step execution limited to 15 minutes max-- Retries count as separate attempts, not separate steps+## Limits (Updated 2025)++| Feature | Workers Free | Workers Paid |+|---------|--------------|--------------|+| **Max steps per workflow** | 1,024 | 1,024 |+| **Max state per step** | 1 MiB | 1 MiB |+| **Max state per instance** | 100 MB | 1 GB |+| **Max event payload size** | 1 MiB | 1 MiB |+| **Max sleep/sleepUntil duration** | 365 days | 365 days |+| **Max waitForEvent timeout** | 365 days | 365 days |+| **CPU time per step** | 10 ms | 30 sec (default), 5 min (max) |+| **Duration (wall clock) per step** | Unlimited | Unlimited |+| **Max workflow executions** | 100,000/day | Unlimited |+| **Concurrent instances** | 25 | 10,000 (Oct 2025, up from 4,500) |+| **Instance creation rate** | 100/second | 100/second (Oct 2025, 10x faster) |+| **Max queued instances** | 100,000 | 1,000,000 |+| **Max subrequests per instance** | 50/request | 1,000/request |+| **Retention (completed state)** | 3 days | 30 days |+| **Max Workflow name length** | 64 chars | 64 chars |+| **Max instance ID length** | 100 chars | 100 chars |++**CRITICAL Notes:**+- `step.sleep()` and `step.sleepUntil()` do NOT count toward 1,024 step limit+- **Waiting instances** (sleeping, retrying, or waiting for events) do NOT count toward concurrency limits+- Instance creation rate increased 10x (October 2025): 100 per 10 seconds → 100 per second+- Max concurrency increased (October 2025): 4,500 → 10,000 concurrent instances+- State persistence limits increased (2025): 128 KB → 1 MiB per step, 100 MB - 1 GB per instance+- Event payload size increased (2025): 128 KB → 1 MiB+- CPU time configurable via `wrangler.jsonc`: `{ "limits": { "cpu_ms": 300000 } }` (5 min max)---@@ -1161,37 +470,6 @@ console.log(status);- Workflow with 3 steps, 1 step retries 2 times: **5 step executions** (3 + 2)- 10M simple workflows/month (5 steps each): ((50M - 10M) / 1M) × $0.30 = **$12/month**------## Always Do ✅--1. **Use descriptive step names** - "fetch user data", not "step 1"-2. **Return serializable values only** - primitives, arrays, plain objects-3. **Use NonRetryableError for terminal errors** - auth failures, invalid input-4. **Configure retry limits** - avoid infinite retries unless necessary-5. **Catch errors for optional steps** - use try-catch if step can fail gracefully-6. **Use exponential backoff for retries** - default backoff for most cases-7. **Validate inputs early** - fail fast with NonRetryableError if invalid-8. **Store workflow instance IDs** - save to DB/KV to query status later-9. **Use waitForEvent for human-in-loop** - approvals, external confirmations-10. **Monitor workflow metrics** - track success rates and errors-------## Never Do ❌--1. **Never return functions from steps** - will throw serialization error-2. **Never create circular references** - will fail to serialize-3. **Never assume steps execute immediately** - they may retry or sleep-4. **Never use blocking operations** - use step.do() for async work-5. **Never exceed 128 KB payload/output** - will fail-6. **Never retry non-idempotent operations infinitely** - use retry limits-7. **Never ignore serialization errors** - fix the data structure-8. **Never use workflows for real-time operations** - use Durable Objects instead-9. **Never skip error handling for critical steps** - wrap in try-catch or use NonRetryableError-10. **Never assume step order is guaranteed across retries** - each step is independent-----## Troubleshooting@@ -1238,101 +516,74 @@ throw new NonRetryableError('User not found');----### Issue: "The requested module 'cloudflare:workers' does not provide an export named 'WorkflowEvent'"+## Vitest Testing (GA April 2025)-**Cause:** Incorrect import or outdated @cloudflare/workers-types+Workflows support full testing integration via `cloudflare:test` module.-**Solution:**+### Setup```bash-# Update types-npm install -D @cloudflare/workers-types@latest--# Ensure correct import-import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';-import { NonRetryableError } from 'cloudflare:workflows';+npm install -D vitest@latest @cloudflare/vitest-pool-workers@latest```------### Issue: Step returns undefined instead of expected value--**Cause:** Step callback doesn't return a value--**Solution:** Always return from step callbacks-+**vitest.config.ts:**```typescript-// ❌ Bad - no return-const result = await step.do('get data', async () => {- const data = await fetchData();- // Missing return!-});-console.log(result); // undefined--// ✅ Good - explicit return-const result = await step.do('get data', async () => {- const data = await fetchData();- return data; // ✅-});+import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';+export default defineWorkersConfig({ test: { poolOptions: { workers: { miniflare: { bindings: { MY_WORKFLOW: { scriptName: 'workflow' } } } } } } });```------### Issue: Workflow instance stuck in "running" state+### Introspection API-**Possible causes:**-1. Step is sleeping for long duration-2. Step is waiting for event that never arrives-3. Step is retrying with long backoff+```typescript+import { env, introspectWorkflowInstance } from 'cloudflare:test';-**Solution:**+it('should complete workflow', async () => {+ const instance = await introspectWorkflowInstance(env.MY_WORKFLOW, 'test-123');-```bash-# Check instance details-npx wrangler workflows instances describe my-workflow <instance-id>+ try {+ await instance.modify(async (m) => {+ await m.disableSleeps(); // Skip all sleeps+ await m.mockStepResult({ name: 'fetch data' }, { users: [{ id: 1 }] }); // Mock step result+ await m.mockEvent({ type: 'approval', payload: { approved: true } }); // Send mock event+ await m.mockStepError({ name: 'call API' }, new Error('Network timeout'), 1); // Force error once+ });-# Look for:-# - Sleep state (will show wake time)-# - Waiting for event (will show event type and timeout)-# - Retry history (will show attempts and delays)+ await env.MY_WORKFLOW.create({ id: 'test-123' });+ await expect(instance.waitForStatus('complete')).resolves.not.toThrow();+ } finally {+ await instance.dispose(); // Cleanup+ }+});```----+### Test Modifiers++- `disableSleeps(steps?)` - Skip sleeps instantly+- `mockStepResult(step, result)` - Mock step.do() result+- `mockStepError(step, error, times?)` - Force step.do() to throw+- `mockEvent(event)` - Send mock event to step.waitForEvent()+- `forceStepTimeout(step, times?)` - Force step.do() timeout+- `forceEventTimeout(step)` - Force step.waitForEvent() timeout-## Production Checklist--Before deploying workflows to production:--- [ ] All steps have descriptive names-- [ ] Retry limits configured for all steps-- [ ] NonRetryableError used for terminal errors-- [ ] Critical steps have error handling-- [ ] Optional steps wrapped in try-catch-- [ ] No non-serializable values returned-- [ ] Payload sizes under 128 KB-- [ ] Workflow duration under 30 days-- [ ] Instance IDs stored for status queries-- [ ] Monitoring and alerting configured-- [ ] waitForEvent timeouts configured-- [ ] Tested in development environment-- [ ] Tested retry behavior-- [ ] Tested error scenarios+**Official Docs**: https://developers.cloudflare.com/workers/testing/vitest-integration/---## Related Documentation-- [Cloudflare Workflows Docs](https://developers.cloudflare.com/workflows/)-- [Get Started Guide](https://developers.cloudflare.com/workflows/get-started/guide/)-- [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/)-- [Sleeping and Retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/)-- [Events and Parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/)-- [Limits](https://developers.cloudflare.com/workflows/reference/limits/)-- [Pricing](https://developers.cloudflare.com/workflows/platform/pricing/)-- [Changelog](https://developers.cloudflare.com/workflows/reference/changelog/)+- **Cloudflare Workflows Docs**: https://developers.cloudflare.com/workflows/+- **Get Started Guide**: https://developers.cloudflare.com/workflows/get-started/guide/+- **Workers API**: https://developers.cloudflare.com/workflows/build/workers-api/+- **Vitest Testing**: https://developers.cloudflare.com/workers/testing/vitest-integration/+- **Sleeping and Retrying**: https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/+- **Events and Parameters**: https://developers.cloudflare.com/workflows/build/events-and-parameters/+- **Limits**: https://developers.cloudflare.com/workflows/reference/limits/+- **Pricing**: https://developers.cloudflare.com/workflows/platform/pricing/+- **Changelog**: https://developers.cloudflare.com/workflows/reference/changelog/+- **MCP Tool**: Use `mcp__cloudflare-docs__search_cloudflare_documentation` for latest docs----**Last Updated**: 2025-10-22+**Last Updated**: 2025-11-25**Version**: 1.0.0**Maintainer**: Jeremy Dawes | [email protected]