Workers API
This guide details the Workflows API within Cloudflare Workers, including methods, types, and usage examples.
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 optionalpayload
containing data (parameters)step
- theWorkflowStep
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.
export type WorkflowEvent<T> = { payload: Readonly<T>; timestamp: Date;};
-
The
WorkflowEvent
is the first argument to a Workflow’srun
method, and includes an optionalpayload
parameter and atimestamp
property.payload
- a default type ofany
or typeT
if a type parameter is provided.timestamp
- aDate
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.
-
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 optionalWorkflowStepConfig
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 aWorkflowDuration
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 JavaScriptDate
object or seconds from the Unix epoch to sleep the Workflow instance until.
export type WorkflowStepConfig = { retries?: { limit: number; delay: string | number; backoff?: WorkflowBackoff; }; timeout?: string | number;};
- A
WorkflowStepConfig
is an optional argument to thedo
method of aWorkflowStep
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.
-
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.
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:
#:schema node_modules/wrangler/config-schema.jsonname = "workflows-starter"main = "src/index.ts"compatibility_date = "2024-10-22"
[[workflows]]# name of your workflowname = "workflows-starter"# binding name env.MYWORKFLOWbinding = "MY_WORKFLOW"# this is class that extends the Workflow class in src/index.tsclass_name = "MyWorkflow"
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 (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 a specific Workflow instance by ID.
-
get(id: string): Promise<WorkflowInstance>
id
- the ID of the Workflow instance.
Returns a WorkflowInstance
.
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;}
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>;}
Return the id of a Workflow.
-
id: string
Return the status of a running Workflow instance.
-
status(): Promise<void>
Pause a running Workflow instance.
-
pause(): Promise<void>
Restart a Workflow instance.
-
restart(): Promise<void>
Terminate a Workflow instance.
-
terminate(): Promise<void>
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;};