Skip to content

Workers API

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.

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
// Steps here
}
};
  • 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 WorkflowEvent type accepts an optional type parameter ↗ that allows you to provide a type for the payload property within the WorkflowEvent.

Refer to the events and parameters documentation for how to handle events within yur Workflow code.

WorkflowEvent

export type WorkflowEvent<T> = {
payload: Readonly<T>;
timestamp: Date;
};
  • The WorkflowEvent is the first argument to a Workflow's run method, and includes an optional payload parameter and a timestamp property.

    • 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).

Refer to the events and parameters documentation for how to handle events within yur Workflow code.

WorkflowStep

step

  • step.do(name: string, callback: (): RpcSerializable): Promise<T>
  • step.do(name: string, config?: WorkflowStepConfig, callback: (): RpcSerializable): Promise<T>
    • name - the name of the step.
    • config (optional) - an optional WorkflowStepConfig for configuring step specific retry behaviour.
    • callback - an asynchronous function that optionally returns serializable state for the Workflow to persist.
  • step.sleep(name: string, duration: WorkflowDuration): Promise<void>
    • name - the name of the step.
    • duration - the duration to sleep until, in either seconds or as a WorkflowDuration compatible string.
    • Refer to the documentation on sleeping and retrying to learn more about how 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 seconds from the Unix epoch to sleep the Workflow instance until.

WorkflowStepConfig

export type WorkflowStepConfig = {
retries?: {
limit: number;
delay: string | number;
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.

Refer to the documentation on sleeping and retrying to learn more about how how Workflows are retried.

NonRetryableError

  • throw new NonRetryableError(message: string , name string optional): NonRetryableError

    • Throws an error that forces the current Workflow instance to fail and not be retried.
    • Refer to the documentation on sleeping and retrying to learn more about how how Workflows are retried.

Call Workflows from Workers

Workflows exposes an API directly to your Workers scripts via the bindings 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.toml 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:

wrangler.toml
#:schema node_modules/wrangler/config-schema.json
name = "workflows-starter"
main = "src/index.ts"
compatibility_date = "2024-10-22"
[[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"

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.toml 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.toml would resemble the following:

wrangler.toml
#:schema node_modules/wrangler/config-schema.json
name = "web-api-worker"
main = "src/index.ts"
compatibility_date = "2024-10-22"
[[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"

Workflow

The Workflow type provides methods that allow you to create, inspect the status, and manage running Workflow instances from within a Worker script.

interface Env {
// The 'MY_WORKFLOW' variable should match the "binding" value set in wrangler.toml
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.

An ID is automatically generated, but a user-provided ID can be specified. This can be useful when mapping Workflows to users, merchants or other identifiers in your system.

// Create a new Workflow instance with your own ID:
let instance = await env.MY_WORKFLOW.create({ id: myIdDefinedFromOtherSystem })
return Response.json({
id: instance.id,
details: await instance.status(),
});

Returns a WorkflowInstance.

get

Get a specific Workflow instance by ID.

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

Returns a WorkflowInstance.

WorkflowInstanceCreateOptions

Optional properties to pass when creating an instance.

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;
}

WorkflowInstance

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

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(): Promise<void>;
/**
* Restart the instance.
*/
public restart(): Promise<void>;
/**
* Returns the current status of the instance.
*/
public status(): Promise<InstanceStatus>;
}

id

Return the id of a Workflow.

  • id: string

status

Return the status of a running Workflow instance.

  • status(): Promise<void>

pause

Pause a running Workflow instance.

  • pause(): Promise<void>

restart

Restart a Workflow instance.

  • restart(): Promise<void>

terminate

Terminate a Workflow instance.

  • terminate(): Promise<void>

InstanceStatus

Details the status of a Workflow instance.

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?: string;
output?: object;
};