Workers API (5)·续2

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

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

// Object form
const { created, errors } = await env.MY_WORKFLOW.createBatch({
    instances: listOfInstances,
});
// 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.

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

The operation returns successes and per-instance failures:


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.

// 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.

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 maximum retention period available for the owner's account.
     */
    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 configured on the Workflow binding. If the binding does not set a default either, instance state is retained for the maximum retention period available on your account (3 days on the Workers Free plan, 30 days on the Workers Paid plan). Refer to the retention limit for more information.

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

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.

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

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

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

const instance = await env.MY_WORKFLOW.get("instance-abc");
await instance.delete();
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 to a running Workflow instance.

  • sendEvent(): Promise<void>- options - the event type (up to 100 characters <sup>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.

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(),
        });
    },
};
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

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:

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"],
});
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.

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?: {
        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-_]*$ ↩ ↩<sup>2</sup> ↩<sup>3</sup>

Was this helpful?

YesNo

On this page

Workers API (5)·续2 - 图1Docs

{"@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-10-12","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/"}}


description: Query Workflows execution metrics, error rates, and step durations via the dashboard or GraphQL Analytics API. title: Metrics and analytics image: https://developers.cloudflare.com/workflows/observability/metrics-analytics/og.png?v=c5981e7bd72ee59d


Skip to 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.