---
description: Reference for the Workflows Workers API, including WorkflowEntrypoint, step methods, and instance management.
title: Workers API
image: https://developers.cloudflare.com/workflows/build/workers-api/og.png?v=083f42c7b743cf63
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/workflows/llms.txt  
> Use this file to discover all available pages before exploring further.

# Workers API

Last updated Nov 11, 2026|Copy as Markdown| [View as Markdown](https://developers.cloudflare.com/workflows/build/workers-api/index.md)| [Agent setup](https://developers.cloudflare.com/agent-setup/)

This guide details the Workflows API within Cloudflare Workers, including methods, types, and usage examples.

## WorkflowEntrypoint

The `WorkflowEntrypoint` class is the core element of a Workflow definition. A Workflow must extend this class and define a `run` method with at least one `step` call to be considered a valid Workflow.

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

### run

- `run(event: WorkflowEvent<T>, step: WorkflowStep): Promise<T>`
  - `event` - the event passed to the Workflow, including an optional `payload` containing data (parameters)
  - `step` - the `WorkflowStep` type that provides the step methods for your Workflow

The `run` method can optionally return data, which is available when querying the instance status via the [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/#instancestatus), [REST API](https://developers.cloudflare.com/api/resources/workflows/subresources/instances/subresources/status/) and the Workflows dashboard. This can be useful if your Workflow is computing a result, returning the key to data stored in object storage, or generating some kind of identifier you need to act on.

```ts
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Steps here
		let someComputedState = await step.do("my step", async () => {});

		// Optional: return state from our run() method
		return someComputedState;
	}
}
```

The `WorkflowEvent` type accepts an optional [type parameter ↗︎](https://www.typescriptlang.org/docs/handbook/2/generics.html#working-with-generic-type-variables) that allows you to provide a type for the `payload` property within the `WorkflowEvent`.

Refer to the [events and parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/) documentation for how to handle events within your Workflow code.

Finally, any JS control-flow primitive (if conditions, loops, `try...catch` blocks, promises, and more) can be used to manage steps inside the `run` method.

## WorkflowEvent

```ts
export type WorkflowCronSchedule = {
	/** Cron expression that triggered this event. */
	cron: string;
	/** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */
	scheduledTime: number;
};

export type WorkflowEvent<T> = {
	payload: Readonly<T>;
	timestamp: Date;
	instanceId: string;
	workflowName: string;
	schedule?: WorkflowCronSchedule;
};
```

- The `WorkflowEvent` is the first argument to a Workflow's `run` method.
  - `payload` - a default type of `any` or type `T` if a type parameter is provided.
  - `timestamp` - a `Date` object set to the time the Workflow instance was created (triggered).
  - `instanceId` - the ID of the associated instance.
  - `workflowName` - the name of the associated Workflow.
  - `schedule` - metadata for Workflow instances created by a cron schedule, including the `cron` expression and `scheduledTime` in milliseconds since the Unix epoch.

Refer to the [events and parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/) documentation for how to handle events within your Workflow code.

## WorkflowStep

### step

- `step.do(name: string, callback: (ctx: WorkflowStepContext): RpcSerializable): Promise<T>`
- `step.do(name: string, callback: (ctx: WorkflowStepContext): RpcSerializable, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>`
- `step.do(name: string, config?: WorkflowStepConfig, callback: (ctx: WorkflowStepContext): RpcSerializable): Promise<T>`
  - `name` - the name of the step, up to 256 characters.
  - `config` (optional) - an optional `WorkflowStepConfig` for configuring [step specific retry behaviour](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/).
  - `callback` - an asynchronous function that receives a [`WorkflowStepContext`](https://developers.cloudflare.com/workflows/build/step-context/) and optionally returns serializable state for the Workflow to persist. In JavaScript Workflows, this includes a fresh, unlocked `ReadableStream<Uint8Array>` for large binary output.
- `step.do(name: string, config?: WorkflowStepConfig, callback: (ctx: WorkflowStepContext): RpcSerializable, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>`
  - `name` - the name of the step, up to 256 characters.
  - `config` (optional) - an optional `WorkflowStepConfig` for configuring [step specific retry behaviour](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/).
  - `callback` - an asynchronous function that receives a [`WorkflowStepContext`](https://developers.cloudflare.com/workflows/build/step-context/) and optionally returns serializable state for the Workflow to persist. In JavaScript Workflows, this includes a fresh, unlocked `ReadableStream<Uint8Array>` for large binary output.
  - `rollbackOptions` (optional) - register rollback logic for the step. If the Workflow later fails, registered rollbacks run in reverse step-start order.

Returning state

When returning state from a `step`, ensure that the object you return is *serializable*.

Primitive types like `string`, `number`, and `boolean`, along with composite structures such as `Array` and `Object` (provided they only contain serializable values), can be serialized. Any [structured-cloneable ↗︎](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone) type can be serialized, as long it is no longer than 1 MB.

On the other hand, objects that include `Function` or `Symbol` types, and objects with circular references, cannot be serialized. The Workflow instance will throw an error if objects with those types is returned.

In JavaScript Workflows, `ReadableStream<Uint8Array>` is a supported serializable return type when a step needs to persist larger binary output than the normal 1 MiB non-stream step-result limit.

Return a new stream from the callback.

Caution

Do not return a locked stream or a stream that has already been read. BYOB streams and BYOB readers are not supported.

After a `ReadableStream<Uint8Array>` object has been persisted within a step, it should not be reused - rely on the new fresh stream that gets returned from step. The bytes are preserved from the original stream, but the implementation might differ.

:::

```js
export class MyWorkflow extends WorkflowEntrypoint {
	async run(_event, step) {
		const reportStream = await step.do("read report from R2", async () => {
			const object = await this.env.MY_BUCKET.get("reports/latest.csv");

			if (!object?.body) {
				throw new Error("Could not read reports/latest.csv from R2.");
			}

			return object.body;
		});

		const preview = await new Response(reportStream).text();
		return { preview };
	}
}
```

```ts
type Env = {
	MY_BUCKET: R2Bucket;
};

export class MyWorkflow extends WorkflowEntrypoint<Env> {
	async run(_event: WorkflowEvent<unknown>, step: WorkflowStep) {
		const reportStream = await step.do("read report from R2", async () => {
			const object = await this.env.MY_BUCKET.get("reports/latest.csv");

			if (!object?.body) {
				throw new Error("Could not read reports/latest.csv from R2.");
			}

			return object.body;
		});

		const preview = await new Response(reportStream).text();
		return { preview };
	}
}
```

- `step.sleep(name: string, duration: WorkflowDuration): Promise<void>`
  - `name` - the name of the step.
  - `duration` - the duration to sleep for, as a `number` in milliseconds or as a `WorkflowDuration`-compatible string.
  - Refer to the [documentation on sleeping and retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/) to learn more about how Workflows are retried.
- `step.sleepUntil(name: string, timestamp: Date | number): Promise<void>`
  - `name` - the name of the step.
  - `timestamp` - a JavaScript `Date` object or milliseconds from the Unix epoch to sleep the Workflow instance until.

Note

`step.sleep` and `step.sleepUntil` methods do not count towards the maximum Workflow steps limit.

More information about the limits imposed on Workflow can be found in the [Workflows limits documentation](https://developers.cloudflare.com/workflows/reference/limits/).

- `step.waitForEvent(name: string, options: ): Promise<void>`- `name` - the name of the step. - `options` - an object with properties for `type` (up to 100 characters <sup>[1](#user-content-fn-1)</sup>), which determines which event type this `waitForEvent` call will match on when calling `instance.sendEvent`, and an optional `timeout` property, which defines how long the `waitForEvent` call will block for before throwing a timeout exception. The default timeout is 24 hours.

```js
export class MyWorkflow extends WorkflowEntrypoint {
	async run(event, step) {
		// Other steps in your Workflow
		let stripeEvent = await step.waitForEvent(
			"receive invoice paid webhook from Stripe",
			{ type: "stripe-webhook", timeout: "1 hour" },
		);
		// Rest of your Workflow
	}
}
```

```ts
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		// Other steps in your Workflow
		let stripeEvent = await step.waitForEvent<IncomingStripeWebhook>(
			"receive invoice paid webhook from Stripe",
			{ type: "stripe-webhook", timeout: "1 hour" },
		);
		// Rest of your Workflow
	}
}
```

Review the documentation on [events and parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/) to learn how to send events to a running Workflow instance.

## WorkflowStepConfig

```ts
export type WorkflowDynamicDelayContext = {
	ctx: WorkflowStepContext;
	error: Error;
};

export type WorkflowDelayFunction = (
	input: WorkflowDynamicDelayContext,
) => string | number | Promise<string | number>;

export type WorkflowStepConfig = {
	retries?: {
		limit: number;
		delay: string | number | WorkflowDelayFunction;
		backoff?: WorkflowBackoff;
	};
	timeout?: string | number;
};
```

- A `WorkflowStepConfig` is an optional argument to the `do` method of a `WorkflowStep` and defines properties that allow you to configure the retry behaviour of that step.
- Set `retries.delay` to a fixed duration, or pass a `WorkflowDelayFunction` to calculate the next retry delay from the current step context and thrown error.

Refer to the [documentation on sleeping and retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/) to learn more about how Workflows are retried.

## Rollback options

```ts
type WorkflowRollbackContext<T = unknown> = {
	ctx: WorkflowStepContext;
	error: Error;
	output: T | undefined;
};

type WorkflowRollbackHandler<T = unknown> = (
	ctx: WorkflowRollbackContext<T>,
) => Promise<void>;

type WorkflowStepRollbackConfig = Pick<
	WorkflowStepConfig,
	"retries" | "timeout"
>;

type WorkflowStepRollbackOptions<T = unknown> = {
	rollback: WorkflowRollbackHandler<T>;
	rollbackConfig?: WorkflowStepRollbackConfig;
};
```

- Pass this `WorkflowStepRollbackOptions` object as the final argument to `step.do()` to register a compensating action for a successful step.
- `rollback` receives the original step context, the error that caused the Workflow to fail, and the step output returned by the forward step.
- `rollbackConfig` applies retry and timeout settings to the rollback handler itself.

```js
export class BillingWorkflow extends WorkflowEntrypoint {
	async run(_event, step) {
		await step.do(
			"create charge",
			async () => {
				const charge = await createCharge();
				return { chargeId: charge.id };
			},
			{
				rollback: async ({ ctx, output, error }) => {
					const { chargeId } = output;
					await refundCharge(chargeId, {
						reason: `${ctx.step.name}: ${error.message}`,
					});
				},
				rollbackConfig: {
					retries: {
						limit: 3,
						delay: "30 seconds",
						backoff: "linear",
					},
					timeout: "5 minutes",
				},
			},
		);
	}
}
```

```ts
export class BillingWorkflow extends WorkflowEntrypoint<Env> {
	async run(_event: WorkflowEvent<unknown>, step: WorkflowStep) {
		await step.do(
			"create charge",
			async () => {
				const charge = await createCharge();
				return { chargeId: charge.id };
			},
			{
				rollback: async ({ ctx, output, error }) => {
					const { chargeId } = output as { chargeId: string };
					await refundCharge(chargeId, {
						reason: `${ctx.step.name}: ${error.message}`,
					});
				},
				rollbackConfig: {
					retries: {
						limit: 3,
						delay: "30 seconds",
						backoff: "linear",
					},
					timeout: "5 minutes",
				},
			},
		);
	}
}
```

## WorkflowStepContext

```ts
export type WorkflowStepContext = {
	step: {
		name: string;
		count: number;
	};
	attempt: number;
	config: WorkflowStepConfig;
};
```

- The `WorkflowStepContext` is passed as the first argument to the `step.do` callback function. It provides runtime information about the current step.
  - `step.name` - the name of the step as passed to `step.do`.
  - `step.count` - how many times `step.do` has been called with this name in the current Workflow run (1-indexed).
  - `attempt` - the current attempt number (1-indexed). `1` on the first try, `2` on the first retry, and so on.
  - `config` - the resolved `WorkflowStepConfig` for this step, including any defaults applied by the runtime.

Refer to the [step context documentation](https://developers.cloudflare.com/workflows/build/step-context/) for usage examples.

## Workflow step limits

Each workflow on Workers Paid supports 10,000 steps by default. You can increase this up to 25,000 steps by configuring `steps` within the `limits` property of your Workflow definition in your Wrangler configuration:

```jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "workflows": [
    {
      "name": "my-workflow",
      "binding": "MY_WORKFLOW",
      "class_name": "MyWorkflow",
      "limits": {
        "steps": 25000
      }
    }
  ]
}
```

```toml
[[workflows]]
name = "my-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

[workflows.limits]
steps = 25_000
```

`step.sleep` does not count towards the maximum steps limit.

Note that Workflows on Workers Free have a limit of 1,024 steps. Refer to [Workflow limits](https://developers.cloudflare.com/workflows/reference/limits/) for more information.

## Workflow concurrency limits

To cap how many instances of a single Workflow run at the same time, configure `limit` within the `concurrency` property of your Workflow definition in your Wrangler configuration:

```jsonc
{
	"workflows": [
		{
			"name": "my-workflow",
			"binding": "MY_WORKFLOW",
			"class_name": "MyWorkflow",
			"concurrency": {
				"limit": 10,
			},
		},
	],
}
```

```toml
[[workflows]]
name = "my-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

  [workflows.concurrency]
  limit = 10
```

Instances above the limit are queued and start automatically as running instances finish. The limit cannot be higher than your account's [concurrency limit](https://developers.cloudflare.com/workflows/reference/limits/). Refer to [Concurrency limits](https://developers.cloudflare.com/workflows/build/concurrency-limits/#per-workflow-concurrency-limits) for how limits are applied, and how to change or remove them.

## Default instance retention

By default, the state of a finished Workflow instance is retained for 3 days on the Workers Free plan. On the Workers Paid plan, instance state is retained for 7 days by default. Workflows created before the [Workers Paid default changed](https://developers.cloudflare.com/changelog/post/2026-09-10-paid-retention-default/) keep their existing 30-day default. To retain instances for a different period, up to your account's [retention limit](https://developers.cloudflare.com/workflows/reference/limits/), configure `default_retention` on the Workflow binding in your Wrangler configuration:

```jsonc
{
	"workflows": [
		{
			"name": "my-workflow",
			"binding": "MY_WORKFLOW",
			"class_name": "MyWorkflow",
			"default_retention": {
				"success_retention": "3 days",
				"error_retention": "7 days",
			},
		},
	],
}
```

```toml
[[workflows]]
name = "my-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"

  [workflows.default_retention]
  success_retention = "3 days"
  error_retention = "7 days"
```

- `success_retention` applies to instances that complete successfully and to instances that are terminated, and `error_retention` applies to instances that end in an errored state.
- Both fields are optional and accept either a duration string, such as `"3 days"`, or a whole number of milliseconds.

Instance-level retention settings take precedence over Workflow binding settings, which take precedence over the account default. The retention period cannot exceed your account's [retention limit](https://developers.cloudflare.com/workflows/reference/limits/).

Note

`default_retention` cannot be combined with `script_name`. If you bind to a Workflow defined in another Worker, set `default_retention` on the Worker that defines the Workflow.

## Workflow jurisdiction

To run the instances of a Workflow and store their data only within a region, set `jurisdiction` on the Workflow binding in your Wrangler configuration. Refer to [Data location](https://developers.cloudflare.com/workflows/reference/data-location/).

## Declare Workflows in `exports`

Note

Requires Wrangler 4.139.0 or above.

You can declare the Workflows a Worker defines in the `exports` field of your Wrangler configuration, instead of in a `workflows` binding:

- The Worker that declares the Workflow calls it through [`ctx.exports`](#call-a-workflow-through-ctxexports).
- Other Workers call the Workflow through a [cross-script binding](#cross-script-calls). Set `script_name` to the Worker that declares the export, and `class_name` to the key of the export.

Key each entry by the name of the class that extends `WorkflowEntrypoint`. Set `type` to `"workflow"` and `name` to the name of the Workflow:

```jsonc
{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "billing-worker",
	"main": "src/index.ts",
	"upload_source_maps": true,
	// Set this to today's date
	"compatibility_date": "2026-11-17",
	"exports": {
		"MyWorkflow": {
			"type": "workflow",
			"name": "billing-workflow",
			"schedules": ["0 * * * *"],
		},
	},
}
```

```toml
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "billing-worker"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-17"

[exports.MyWorkflow]
type = "workflow"
name = "billing-workflow"
schedules = [ "0 * * * *" ]
```

A `workflow` export accepts the same settings as a `workflows` binding: `limits`, `concurrency`, `schedules`, `default_retention`, and `jurisdiction`. When you run `wrangler deploy`, Wrangler creates or updates the Workflow with these settings. Refer to [Workflow exports](https://developers.cloudflare.com/workers/wrangler/configuration/#workflow-exports) for the full list of fields.

You can declare the same Workflow as both a binding and an export. Both declarations must use the same class. They cannot set the same setting to different values.

A `workflows` binding to a Workflow in another Worker cannot use the same `name` as a Workflow export in this Worker. Workflow names are unique per account.

### Call a Workflow through `ctx.exports`

Note

Local development requires one of the following, depending on your tooling:

- Wrangler 4.142.0 or above
- `@cloudflare/vite-plugin` 1.61.0 or above
- `@cloudflare/vitest-plugin` 1.3.0 or above

Each Workflow declared in `exports` is available on [`ctx.exports`](https://developers.cloudflare.com/workers/runtime-apis/context/#exports), keyed by class name. It has the same API as a [Workflow binding](#workflow), so the Worker does not need a `workflows` binding to call it.

The following Worker creates an instance of `MyWorkflow` through `ctx.exports`, and gets the status of an existing instance:

*src/index.jsjs*

```js
import {
	WorkflowEntrypoint,
	WorkflowEvent,
	WorkflowStep,
} from "cloudflare:workers";

export class MyWorkflow extends WorkflowEntrypoint {
	async run(event, step) {
		return await step.do("greet", async () => `Hello, ${event.payload.name}!`);
	}
}

export default {
	async fetch(request, env, ctx) {
		const id = new URL(request.url).searchParams.get("id");

		// Get the status of an existing instance
		if (id !== null) {
			const instance = await ctx.exports.MyWorkflow.get(id);
			return Response.json(await instance.status());
		}

		// Create a new instance
		const instance = await ctx.exports.MyWorkflow.create({
			params: { name: "World" },
		});
		return Response.json({ id: instance.id });
	},
};
```

*src/index.tsts*

```ts
import {
	WorkflowEntrypoint,
	WorkflowEvent,
	WorkflowStep,
} from "cloudflare:workers";

type Params = { name: string };

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
	async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
		return await step.do("greet", async () => `Hello, ${event.payload.name}!`);
	}
}

export default {
	async fetch(request, env, ctx): Promise<Response> {
		const id = new URL(request.url).searchParams.get("id");

		// Get the status of an existing instance
		if (id !== null) {
			const instance = await ctx.exports.MyWorkflow.get(id);
			return Response.json(await instance.status());
		}

		// Create a new instance
		const instance = await ctx.exports.MyWorkflow.create({
			params: { name: "World" },
		});
		return Response.json({ id: instance.id });
	},
} satisfies ExportedHandler<Env>;
```

If you use TypeScript, run [`wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/workers/#types) to type `ctx.exports.MyWorkflow` as `Workflow<Params>`. This requires Wrangler 4.142.0 or above.

A `workflows` binding and a `workflow` export with the same `name` share their instances. This includes instances created before you declared the Workflow in `exports`, so you can move a Workflow from a binding to an export without losing its instances.

To test a Workflow declared in `exports` with the Vitest integration, refer to [Introspect Workflows declared in `exports`](https://developers.cloudflare.com/workers/testing/vitest-integration/test-apis/#introspect-workflows-declared-in-exports).

## NonRetryableError

- `throw new NonRetryableError(message: string, name string optional)`: `NonRetryableError`
  - When thrown inside [`step.do()`](https://developers.cloudflare.com/workflows/build/workers-api/#step), this error stops step retries, propagating the error to the top level (the [run](https://developers.cloudflare.com/workflows/build/workers-api/#run) function). Any error not handled at this top level will cause the Workflow instance to fail.
  - Refer to the [documentation on sleeping and retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/) to learn more about how Workflows steps are retried.

## Call Workflows from Workers

Workflows exposes an API directly to your Workers scripts via the [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/#what-is-a-binding) concept. Bindings allow you to securely call a Workflow without having to manage API keys or clients.

You can bind to a Workflow by defining a `[[workflows]]` binding within your Wrangler configuration.

For example, to bind to a Workflow called `workflows-starter` and to make it available on the `MY_WORKFLOW` variable to your Worker script, you would configure the following fields within the `[[workflows]]` binding definition:

```jsonc
{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "workflows-starter",
	"main": "src/index.ts",
	"upload_source_maps": true,
	// Set this to today's date
	"compatibility_date": "2026-11-17",
	"workflows": [
		{
			// name of your workflow
			"name": "workflows-starter",
			// binding name env.MY_WORKFLOW
			"binding": "MY_WORKFLOW",
			// this is class that extends the Workflow class in src/index.ts
			"class_name": "MyWorkflow",
		},
	],
}
```

```toml
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "workflows-starter"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-17"

[[workflows]]
name = "workflows-starter"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"
```

### Bind from Pages

You can bind and trigger Workflows from [Pages Functions](https://developers.cloudflare.com/pages/functions/) by deploying a Workers project with your Workflow definition and then invoking that Worker using [service bindings](https://developers.cloudflare.com/pages/functions/bindings/#service-bindings) or a standard `fetch()` call.

Visit the documentation on [calling Workflows from Pages](https://developers.cloudflare.com/workflows/build/call-workflows-from-pages/) for examples.

### Cross-script calls

You can also bind to a Workflow that is defined in a different Worker script from the script your Workflow definition is in. To do this, provide the `script_name` key with the name of the script to the `[[workflows]]` binding definition in your Wrangler configuration.

For example, if your Workflow is defined in a Worker script named `billing-worker`, but you are calling it from your `web-api-worker` script, your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/) would resemble the following:

```jsonc
{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "web-api-worker",
	"main": "src/index.ts",
	"upload_source_maps": true,
	// Set this to today's date
	"compatibility_date": "2026-11-17",
	"workflows": [
		{
			// name of your workflow
			"name": "billing-workflow",
			// binding name env.MY_WORKFLOW
			"binding": "MY_WORKFLOW",
			// this is class that extends the Workflow class in src/index.ts
			"class_name": "MyWorkflow",
			// the script name where the Workflow is defined.
			// required if the Workflow is defined in another script.
			"script_name": "billing-worker",
		},
	],
}
```

```toml
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "web-api-worker"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-17"

[[workflows]]
name = "billing-workflow"
binding = "MY_WORKFLOW"
class_name = "MyWorkflow"
script_name = "billing-worker"
```

If you're using TypeScript, run [`wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/general/#types) whenever you modify your Wrangler configuration file. This generates types for the `env` object based on your bindings, as well as [runtime types](https://developers.cloudflare.com/workers/languages/typescript/).

## Workflow

Note

Ensure you have a compatibility date `2024-10-22` or later installed when binding to Workflows from within a Workers project.

The `Workflow` type provides methods that allow you to create, inspect the status, and manage running Workflow instances from within a Worker script. It is part of the generated types produced by [`wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/general/#types).

*./worker-configuration.d.tsts*

```ts
interface Env {
	// The 'MY_WORKFLOW' variable should match the "binding" value set in the Wrangler config file
	MY_WORKFLOW: Workflow;
}
```

The `Workflow` type exports the following methods:

### create

Create (trigger) a new instance of the given Workflow.

- `create(options?: WorkflowInstanceCreateOptions): Promise<WorkflowInstance>`
  - `options` - optional properties to pass when creating an instance, including a user-provided ID and payload parameters.

An ID is automatically generated, but a user-provided ID can be specified (up to 100 characters <sup>[1](#user-content-fn-1)</sup>). This can be useful when mapping Workflows to users, merchants or other identifiers in your system. You can also provide a JSON object as the `params` property, allowing you to pass data for the Workflow instance to act on as its [`WorkflowEvent`](https://developers.cloudflare.com/workflows/build/events-and-parameters/).

```ts
// Create a new Workflow instance with your own ID and pass params to the Workflow instance
let instance = await env.MY_WORKFLOW.create({
	id: myIdDefinedFromOtherSystem,
	params: { hello: "world" },
});
return Response.json({
	id: instance.id,
	details: await instance.status(),
});
```

Returns a `WorkflowInstance`.

Throws an error if the provided ID is already used by an existing instance that has not yet passed its [retention limit](https://developers.cloudflare.com/workflows/reference/limits/). To re-run a workflow with the same ID, you can [`restart`](https://developers.cloudflare.com/workflows/build/trigger-workflows/#restart-a-workflow) the existing instance.

Caution

Providing a type parameter does *not* validate that the incoming event matches your type definition. In TypeScript, properties (fields) that do not exist or conform to the type you provided will be dropped. If you need to validate incoming events, we recommend a library such as [zod ↗︎](https://zod.dev/) or your own validator logic.

You can also provide a type parameter to the `Workflows` type when creating (triggering) a Workflow instance using the `create` method of the [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/#workflow). Note that this does *not* propagate type information into the Workflow itself, as TypeScript types are a build-time construct.

To provide an optional type parameter to the `Workflow`, pass a type argument with your type when defining your Workflow bindings:

```ts
interface User {
	email: string;
	createdTimestamp: number;
}

interface Env {
	// Pass our User type as the type parameter to the Workflow definition
  MY_WORKFLOW: Workflow<User>;
}

export default {
	async fetch(request, env, ctx) {
		// More likely to come from your database or via the request body!
		const user: User = {
			email: user@example.com,
			createdTimestamp: Date.now()
		}

		let instance = await env.MY_WORKFLOW.create({
			// params expects the type User
			params: user
		})

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

### createBatch

Create (trigger) a batch of new instances of the given Workflow, up to 100 instances at a time.

This is useful when you are scheduling multiple instances at once. A call to `createBatch` is treated the same as a call to `create` (for a single instance) and allows you to work within the [instance creation limit](https://developers.cloudflare.com/workflows/reference/limits/).

- `createBatch(options: WorkflowBatchCreateOptions): Promise<WorkflowBatchCreateResult>`
  - `options` - either a `count` of instances to create with shared options, or a list of `instances`, each with its own options.

Note

To use this form of `createBatch` in local development and get its types from `wrangler types`, use Wrangler 4.148.0 or later.

To create instances that share the same options, pass `count` with optional `params` and `retention`. Each instance receives a generated ID:

```js
// Create 3 Workflow instances with generated IDs and the same params
const result = await env.MY_WORKFLOW.createBatch({
	count: 3,
	params: { hello: "world" },
});
```

```ts
// Create 3 Workflow instances with generated IDs and the same params
const result = await env.MY_WORKFLOW.createBatch({
	count: 3,
	params: { hello: "world" },
});
```

To give each instance its own ID or options, pass `instances`. Each entry accepts the same [`WorkflowInstanceCreateOptions`](https://developers.cloudflare.com/workflows/build/workers-api/#workflowinstancecreateoptions) as `create`:

```js
// Create 3 Workflow instances, each with its own ID and params
const result = await env.MY_WORKFLOW.createBatch({
	instances: [
		{ id: "id-abc123", params: { hello: "world-0" } },
		{ id: "id-def456", params: { hello: "world-1" } },
		{ id: "id-ghi789", params: { hello: "world-2" } },
	],
});
```

```ts
// Create 3 Workflow instances, each with its own ID and params
const result = await env.MY_WORKFLOW.createBatch({
	instances: [
		{ id: "id-abc123", params: { hello: "world-0" } },
		{ id: "id-def456", params: { hello: "world-1" } },
		{ id: "id-ghi789", params: { hello: "world-2" } },
	],
});
```

`options` takes one of the following shapes:

```ts
type WorkflowBatchCreateOptions =
	| {
			count: number;
			params?: unknown;
			retention?: {
				successRetention?: WorkflowRetentionDuration;
				errorRetention?: WorkflowRetentionDuration;
			};
	  }
	| {
			instances: WorkflowInstanceCreateOptions[];
	  };
```

`count` must be an integer from 1 to 100. `instances` must contain from 1 to 100 entries. You cannot pass both `count` and `instances` in the same call.

The operation returns the created instances and per-instance errors:

```ts
type WorkflowBatchCreateResult = {
	created: WorkflowInstance[];
	errors: {
		index: number;
		id?: string;
		code: number;
		message: string;
	}[];
};
```

`created` contains a `WorkflowInstance` for each created instance, in input order. `errors` contains the entries that were not created. Each error includes the position of the entry in the input (`index`), its `id` if one was provided, and an error code and message.

Unlike [`create`](https://developers.cloudflare.com/workflows/build/workers-api/#create), `createBatch` does not throw when an ID is already in use. Instead, it reports the entry in `errors` with one of the following codes:

| Code | Description |
| --- | --- |
| `10405` | An instance with this ID already exists. |
| `10415` | An earlier entry in the same batch uses this ID. Only the first entry with the ID is created. |

If any entry has invalid options, such as an invalid ID or retention duration, the call throws an error before it creates any instances.

#### Migrate from the array form

Caution

Passing an array to `createBatch` is deprecated. Use the `instances` option instead.

- `createBatch(batch: WorkflowInstanceCreateOptions[]): Promise<WorkflowInstance[]>`

The array form returns an array of `WorkflowInstance`. It skips IDs that already exist or repeat within the batch, and excludes them from the returned array without reporting an error.

To migrate, pass the array as `instances` and read the instances from `created`:

```js
// Deprecated: array form
const instances = await env.MY_WORKFLOW.createBatch(listOfInstances);

// Object form
const { created, errors } = await env.MY_WORKFLOW.createBatch({
	instances: listOfInstances,
});
```

```ts
// Deprecated: array form
const instances = await env.MY_WORKFLOW.createBatch(listOfInstances);

// Object form
const { created, errors } = await env.MY_WORKFLOW.createBatch({
	instances: listOfInstances,
});
```

### deleteBatch

Delete up to 100 Workflow instances and their stored state.

`deleteBatch(instanceIds: string[])` returns a `Promise<WorkflowBatchDeleteResult>`. The `instanceIds` argument contains the IDs of the Workflow instances to delete.

```js
const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);
```

```ts
const result = await env.MY_WORKFLOW.deleteBatch([
	"instance-abc",
	"instance-def",
]);
```

The operation returns successes and per-instance failures:

```ts
type WorkflowBatchDeleteResult = {
	deleted: { id: string }[];
	errors: {
		id: string;
		code: number;
		message: string;
	}[];
};
```

`deleted` contains the IDs that were deleted successfully. `errors` contains failures identified by instance ID, with a stable error code and message.

`deleteBatch()` accepts between 1 and 100 IDs. Duplicate IDs count toward the limit and are deleted once, with the result repeated for each input position. An ID whose instance does not exist is included in `errors`. If any ID is invalid, the call fails before deleting any instances. Deleting a running instance removes its stored state and stops its current execution without running rollback handlers.

### get

Get a specific Workflow instance by ID.

- `get(id: string): Promise<WorkflowInstance>`- `id` - the ID of the Workflow instance.

Returns a `WorkflowInstance`. Throws an exception if the instance ID does not exist.

```ts
// Fetch an existing Workflow instance by ID:
try {
	let instance = await env.MY_WORKFLOW.get(id);
	return Response.json({
		id: instance.id,
		details: await instance.status(),
	});
} catch (e: any) {
	// Handle errors
	// .get will throw an exception if the ID doesn't exist or is invalid.
	const msg = `failed to get instance ${id}: ${e.message}`;
	console.error(msg);
	return Response.json({ error: msg }, { status: 400 });
}
```

## WorkflowInstanceCreateOptions

Optional properties to pass when creating an instance.

```ts
interface WorkflowInstanceCreateOptions {
	/**
	 * An id for your Workflow instance. Must be unique within the Workflow.
	 */
	id?: string;
	/**
	 * The event payload the Workflow instance is triggered with
	 */
	params?: unknown;
	/**
	 * The retention policy for the Workflow instance.
	 * Defaults to the Workflow's `default_retention`, then the account default, then the plan default (3 days on Workers Free, 7 days on Workers Paid).
	 */
	retention?: {
		/**
		 * How long to retain instance state after the Workflow completes successfully
		 * or is terminated.
		 */
		successRetention?: WorkflowRetentionDuration;
		/**
		 * How long to retain instance state after the Workflow ends in an errored state.
		 */
		errorRetention?: WorkflowRetentionDuration;
	};
}

type WorkflowRetentionDuration = WorkflowSleepDuration;
```

If `retention` is not set, instance state is retained for the [`default_retention`](https://developers.cloudflare.com/workflows/build/workers-api/#default-instance-retention) configured on the Workflow binding. If the binding does not set a default either, the account-level default applies, if one is set. Otherwise, instance state is retained for 3 days on the Workers Free plan, or 7 days on the Workers Paid plan (30 days for Workflows created before the [Workers Paid default changed](https://developers.cloudflare.com/changelog/post/2026-09-10-paid-retention-default/)). Refer to the [retention limit](https://developers.cloudflare.com/workflows/reference/limits/) for more information.

The following example creates an instance that retains state for 1 day after success and 7 days after an error:

```ts
let instance = await env.MY_WORKFLOW.create({
	id: myIdDefinedFromOtherSystem,
	params: { hello: "world" },
	retention: {
		successRetention: "1 day",
		errorRetention: "7 days",
	},
});
```

## WorkflowInstance

Represents a specific instance of a Workflow, and provides methods to manage the instance.

```ts
declare abstract class WorkflowInstance {
	public id: string;
	/**
	 * Pause the instance.
	 */
	public pause(): Promise<void>;
	/**
	 * Resume the instance. If it is already running, an error will be thrown.
	 */
	public resume(): Promise<void>;
	/**
	 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.
	 */
	public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;
	/**
	 * Restart the instance from the beginning, or from a specific step.
	 */
	public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
	/**
	 * Delete the instance and its stored state.
	 */
	public delete(): Promise<void>;
	/**
	 * Returns the current status of the instance.
	 */
	public status(): Promise<InstanceStatus>;
	/**
	 * Subscribe to events from this Workflow instance.
	 */
	public subscribe(
		options?: WorkflowInstanceSubscribeOptions,
	): Promise<WorkflowInstanceSubscription>;
}
```

### id

Return the id of a Workflow.

- `id: string`

### status

Return the status of a running Workflow instance.

- `status(): Promise<InstanceStatus>`

### pause

Pause a running Workflow instance.

- `pause(): Promise<void>`

### resume

Resume a paused Workflow instance.

- `resume(): Promise<void>`

### restart

Restart a Workflow instance from the beginning, or from a specific step.

- `restart(options?: WorkflowInstanceRestartOptions): Promise<void>`
  - `options` - optional properties that control from where the instance restarts.

```ts
let instance = await env.MY_WORKFLOW.get("abc-123");

// Restart the instance from the beginning.
await instance.restart();

// Restart the instance from the step named "aggregate".
await instance.restart({ from: { name: "aggregate" } });

// Restart the instance from the third call to a step named "process".
await instance.restart({ from: { name: "process", count: 3 } });
```

When restarting from a specific step, the cached results of every earlier step are reused, while the target step and any steps that follow it run again. The call throws an error if no step matching `from` is found in the instance's execution history.

#### WorkflowInstanceRestartOptions

```ts
interface WorkflowInstanceRestartOptions {
	/**
	 * The step to restart the instance from.
	 * If omitted, the instance restarts from the beginning.
	 */
	from?: {
		/**
		 * The name of the step.
		 */
		name: string;
		/**
		 * The 1-based index of the step, used when multiple steps share the same name and type. Defaults to 1 (the first occurrence).
		 */
		count?: number;
		/**
		 * The step type. Use this to disambiguate when the same name is shared across step types. Defaults to "do".
		 */
		type?: "do" | "sleep" | "waitForEvent";
	};
}
```

The `from` object identifies the step to restart from. Only `name` is required; `count` and `type` are only needed when the same step name appears more than once in the run.

- `name` - the name of the step.
- `count` - the 1-based index of the step, used when multiple steps share the same name and type (for example, inside a loop). Defaults to `1` (the first occurrence). Corresponds to `step.count` in the [step context](https://developers.cloudflare.com/workflows/build/step-context/).
- `type` - the step type ( `"do"`, `"sleep"`, or `"waitForEvent"`). Defaults to `"do"`. Use this when the same name is shared across different step types.

### terminate

Terminate a Workflow instance.

- `terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>`
  - `options` - optional properties that control how the instance is terminated.

```ts
let instance = await env.MY_WORKFLOW.get("abc-123");

// Terminate without running rollback handlers.
await instance.terminate();

// Run registered rollback handlers before terminating.
await instance.terminate({ rollback: true });
```

If `rollback` is `true`, Workflows runs the rollback handlers registered by completed or eligible steps before the instance reaches the `terminated` state. Steps without rollback handlers are skipped.

#### WorkflowInstanceTerminateOptions

```ts
interface WorkflowInstanceTerminateOptions {
	/**
	 * If true, run registered rollback handlers before terminating the instance.
	 */
	rollback?: boolean;
}
```

### delete

Delete a Workflow instance and its stored state with `delete(): Promise<void>`.

```js
const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();
```

```ts
const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();
```

Deleting a running instance stops its current execution without running rollback handlers. If a Workflow deletes its own instance, execution stops during `await instance.delete()`, and code after the call does not run.

### sendEvent

[Send an event](https://developers.cloudflare.com/workflows/build/events-and-parameters/) to a running Workflow instance.

- `sendEvent(): Promise<void>`- `options` - the event `type` (up to 100 characters <sup>[1](#user-content-fn-1)</sup>) and `payload` to send to the Workflow instance. The `type` must match the `type` in the corresponding `waitForEvent` call in your Workflow.

Return `void` on success; throws an exception if the Workflow is not running or is an errored state.

```js
export default {
	async fetch(req, env) {
		const instanceId = new URL(req.url).searchParams.get("instanceId");
		const webhookPayload = await req.json();

		let instance = await env.MY_WORKFLOW.get(instanceId);
		// Send our event, with `type` matching the event type defined in
		// our step.waitForEvent call
		await instance.sendEvent({
			type: "stripe-webhook",
			payload: webhookPayload,
		});

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

```ts
export default {
	async fetch(req: Request, env: Env) {
		const instanceId = new URL(req.url).searchParams.get("instanceId");
		const webhookPayload = await req.json<Payload>();

		let instance = await env.MY_WORKFLOW.get(instanceId);
		// Send our event, with `type` matching the event type defined in
		// our step.waitForEvent call
		await instance.sendEvent({
			type: "stripe-webhook",
			payload: webhookPayload,
		});

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

You can call `sendEvent` multiple times, setting the value of the `type` property to match the specific `waitForEvent` calls in your Workflow.

This allows you to wait for multiple events at once, or use `Promise.race` to wait for multiple events and allow the first event to progress the Workflow.

### subscribe

Subscribe to historical and live execution events from a Workflow instance.

- `subscribe(options?: WorkflowInstanceSubscribeOptions): Promise<WorkflowInstanceSubscription>`
  - `options` - optional properties that set the starting cursor and filter event types.

The returned subscription provides a `next()` method. Each call returns the next matching `WorkflowInstanceEvent` or waits for one. The subscription ends when the instance completes, errors, or terminates.

#### WorkflowInstanceSubscribeOptions

```ts
interface WorkflowInstanceSubscribeOptions {
	/**
	 * The event ID after which to start.
	 */
	cursor?: number;
	/**
	 * Emit only events with one of these types.
	 */
	filter?: WorkflowInstanceEventType[];
}

type WorkflowInstanceEventType = WorkflowInstanceEvent["type"];
```

Call `subscribe()` without options to receive all events. Use `cursor` and `filter` to control which events the subscription returns:

```js
const instance = await env.MY_WORKFLOW.get("abc-123");

// Subscribe to all events.
using allEvents = await instance.subscribe();

// Subscribe to events after event ID 100.
using eventsAfterCursor = await instance.subscribe({ cursor: 100 });

// Subscribe to selected event types.
using filteredEvents = await instance.subscribe({
	filter: ["workflow_completed", "workflow_errored"],
});
```

```ts
const instance = await env.MY_WORKFLOW.get("abc-123");

// Subscribe to all events.
using allEvents = await instance.subscribe();

// Subscribe to events after event ID 100.
using eventsAfterCursor = await instance.subscribe({ cursor: 100 });

// Subscribe to selected event types.
using filteredEvents = await instance.subscribe({
	filter: ["workflow_completed", "workflow_errored"],
});
```

For event types, filtering behavior, and cursor usage, refer to [Subscribe to events](https://developers.cloudflare.com/workflows/build/subscribe-to-instance-events/).

### InstanceStatus

Details the status of a Workflow instance.

```ts
type InstanceStatus = {
	status:
		| "queued" // means that instance is waiting to be started (see concurrency limits)
		| "running"
		| "paused"
		| "errored"
		| "terminated" // user terminated the instance while it was running
		| "complete"
		| "waiting" // instance is hibernating and waiting for sleep or event to finish
		| "waitingForPause" // instance is finishing the current work to pause
		| "unknown";
	error?: {
		name: string;
		message: string;
	};
	output?: unknown;
	rollback: {
		outcome: "complete" | "failed";
		error: {
			name: string;
			message: string;
		} | null;
	} | null;
};
```

If a Workflow enters rollback, the Workers API continues to report `status: "running"` for compatibility while the rollback is executing. After the instance reaches a terminal state, inspect `rollback` to determine whether compensating steps completed successfully or failed.

## Footnotes

1. Match pattern: `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$` [↩](#user-content-fnref-1) [↩<sup>2</sup>](#user-content-fnref-1-2) [↩<sup>3</sup>](#user-content-fnref-1-3)

Was this helpful?

YesNo

## On this page

[![](https://developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/workflows/build/workers-api/#page","headline":"Workers API","description":"Reference for the Workflows Workers API, including WorkflowEntrypoint, step methods, and instance management.","url":"https://developers.cloudflare.com/workflows/build/workers-api/","inLanguage":"en","image":"https://developers.cloudflare.com/workflows/build/workers-api/og.png?v=083f42c7b743cf63","dateModified":"2026-11-11","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```
