skip to content

Durable Workflows

Workflows persist each step.do result, so after a crash run() replays and skips the finished steps. Interviewers ask why step bodies must be idempotent and how waitForEvent works.

on this pageshow

explore

questions

5

In a Cloudflare Workflow, how do step.do() retries and timeouts behave by default, and when do you throw NonRetryableError?

level: middleimportance: must knowfreq 45%

answer

  1. a config object before the callback
  2. five retries, exponential
  3. the timeout is per attempt
  4. permanent failure, stop retrying

basics

~20 s

By default each step.do() retries a thrown error 5 times with a 10-second exponential backoff and a 10-minute timeout per attempt; a per-step config overrides it. Throwing NonRetryableError stops the retries at once for a permanent failure.

solid answer

~40 s

`step.do(name, config, callback)` takes an optional `WorkflowStepConfig`. Without one, Workflows applies `retries: { limit: 5, delay: 10000, backoff: "exponential" }` and `timeout: "10 minutes"`. `limit` counts retries, so 5 means up to six attempts; `delay` is milliseconds or a string such as `"30 seconds"`; `backoff` is `constant`, `linear` or `exponential`; and as of 2026 `delay` may also be a function of the attempt and the error. `timeout` applies to each attempt, and the docs advise 30 minutes or less, with `step.waitForEvent()` for longer waits. For a permanent error such as a missing payment method, throw `NonRetryableError` from `cloudflare:workflows`: the step stops retrying and the error reaches `run()`, where, uncaught, it ends the instance as `errored`. A `try...catch` around the step lets the run continue with a fallback step.

code

javascript · 38 lines
javascript
import { WorkflowEntrypoint } from "cloudflare:workers";
import { NonRetryableError } from "cloudflare:workflows";

export class BillingWorkflow extends WorkflowEntrypoint {
  async run(event, step) {
    return await step.do(
      "charge first invoice",
      {
        retries: { limit: 3, delay: "30 seconds", backoff: "exponential" },
        timeout: "2 minutes",
      },
      async (ctx) => {
        if (!event.payload.paymentMethodId) {
          throw new NonRetryableError("no payment method on file");
        }
        console.log(`charge attempt ${ctx.attempt}`);
        return { charged: event.payload.userId };
      },
    );
  }
}

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const id = url.searchParams.get("id");
    if (id) {
      return Response.json(await (await env.BILLING.get(id)).status());
    }
    const instance = await env.BILLING.create({
      params: {
        userId: "user-42",
        paymentMethodId: url.searchParams.get("pm"),
      },
    });
    return Response.json({ id: instance.id });
  },
};

go deeper

for a junior

Know that each step.do() retries a thrown error on its own and that a config object between the name and the callback changes how.

for a middle

Recite the defaults (limit 5, 10-second delay, exponential backoff, 10-minute timeout), explain that limit counts retries and timeout is per attempt, and say when NonRetryableError is the right throw.

for a senior

Tune each step to its dependency: short timeouts and idempotent bodies for payments, delay functions for rate limits, waitForEvent instead of hour-long timeouts, and try/catch or rollback handlers for compensation.

for a principal

Treat retry policy as part of each integration's contract: agree with each downstream owner on which errors are permanent, how much retry load they accept, and how compensation is audited.

## What a step retry is In **Cloudflare Workflows**, every `step.do()` call is a unit of work that the engine runs, persists and, if its callback throws, **retries** on its own. Only the failing step runs again; earlier steps keep their saved results. This is what lets an onboarding run survive a flaky email or payment API without repeating the account creation. Each step's behaviour is set by an optional `WorkflowStepConfig` passed between the name and the callback: `step.do(name, config, callback)`. ## The default configuration When no config is passed, Workflows applies these values: | Field | Default | Meaning | |---|---|---| | `retries.limit` | `5` | Retries after the first attempt, so up to six attempts | | `retries.delay` | `10000` (ms) | Base wait before a retry | | `retries.backoff` | `"exponential"` | How the wait grows: `constant`, `linear` or `exponential` | | `timeout` | `"10 minutes"` | Limit for **each attempt**, not for all attempts together | `delay` and `timeout` accept milliseconds or duration strings such as `"30 seconds"`. With `constant` the wait stays at the base delay, with `linear` it grows by the base delay each time, and with `exponential` it doubles after each failed attempt. A step may retry at most 10,000 times. Inside the callback, `ctx.attempt` is `1` on the first try and `2` on the first retry, and `ctx.config` shows the resolved config with defaults filled in. The local simulator in `wrangler dev` resolves a shorter 1-second default delay, so retry timing seen locally is not production timing. ## Configuring a step Tune each step to the system it calls: - A **payment call**: few retries, a short timeout, and an idempotent body, since an attempt can commit at the provider and still fail locally. - A **rate-limited provider**: pass a function as `retries.delay`. It receives `{ ctx, error }` and returns the next delay, so a rate-limit error can wait longer than a network blip. - A **slow job**: raise `timeout`, but keep it at 30 minutes or less as the docs advise; waiting on a person or webhook belongs in `step.waitForEvent()`. - **CPU** is a separate budget: a Workflow shares the Workers CPU limit, 30 seconds per invocation by default on Workers Paid, raisable with `limits.cpu_ms`. ## Stopping retries with NonRetryableError Some failures will never succeed on retry: a missing payment method, an authentication failure, a malformed payload. Retrying them only delays the inevitable and burns attempts. For these, throw `NonRetryableError`, imported from `cloudflare:workflows`: 1. The current step stops retrying immediately; no further attempts are scheduled. 2. The error propagates out of `step.do()` into `run()`. 3. If `run()` does not catch it, the instance ends in the `errored` state and no later steps run. An ordinary thrown `Error`, by contrast, is retried until `limit` is used up, and then the last attempt's error propagates the same way. ## What a retry leaves alone A retry is scoped to the one failing step, which shapes how you read a failing run: - Steps that already completed are **not** run again; their stored results stay in place. - While a step waits for its next attempt, the instance is in the `waiting` state, which does not count toward the account's concurrency limit, so a long backoff costs no running slot. - Each attempt is recorded. `wrangler workflows instances describe` lists a step's attempts with their start, end and state, which is how you tell a flaky dependency (one failure, then success) from a broken one (every attempt failing the same way). - A retry re-runs the **whole callback**. Anything the callback did before it threw, such as a request the provider accepted, happens again, which is why step bodies are written to be idempotent. ## Catching a failed step Any step failure, retried-out or non-retryable, surfaces as an exception at the `await`. Wrap the step in `try...catch` when the Workflow should continue: record the failure in a cleanup step, mark the account as unbilled, or notify someone. Since June 2026, `step.do()` also accepts rollback options as its last argument: a `rollback` handler and `rollbackConfig` that run in reverse step order when the instance later fails, for saga-style compensation such as refunding a charge. ## Common mistakes - Assuming a failed step retries forever: it stops after `limit` retries. - Reading `limit` as total attempts: `limit: 3` allows four attempts. - Expecting `timeout` to cap the whole retry sequence: it caps each attempt. - Swallowing a permanent error inside the callback and returning normally, which records a false success that the engine will never retry.

  • How many times can the callback run with retries: { limit: 2 }?
    Up to three times: the first attempt plus two retries, because `limit` counts retries rather than attempts. `ctx.attempt` reads 1, 2 and 3 across them. If the third attempt also throws, the step fails with that attempt's error, which propagates to `run()` and ends the instance as `errored` unless the code catches it.
  • How should a step handle a provider that answers with rate-limit errors?
    Pass a function as `retries.delay`. It receives `{ ctx, error }` and returns a duration string or milliseconds, so the step can wait, say, `${ctx.attempt * 30} seconds` after a rate-limit error and 10 seconds after anything else. Keep `limit` high enough to outlast the provider's window, and keep the body idempotent.

  • A failed step.do() keeps retrying until it eventually succeeds.
  • retries.limit counts total attempts, so limit: 5 means five calls.
  • The step timeout caps all retry attempts of that step together.
  • Throwing NonRetryableError just skips the current attempt; the step retries later.
  • A step timeout of several hours is the right way to wait for a person.

Assumes Workflows as of 2026-10-10; the defaults have not changed, but delay functions for retries.delay arrived in July 2026 and rollback options on step.do() in June 2026.

open as a page

After a long step.sleep(), a Cloudflare onboarding Workflow sent a second welcome email and a later step read an empty array; why, and how do you fix it?

level: seniorimportance: must knowfreq 42%

basics

~20 s

When an instance wakes or the engine restarts, Workflows replays run() from the top: finished step.do() calls return their saved results, but code between steps runs again and in-memory variables start empty. Put side effects inside steps and build state from step returns.

open as a page

In Cloudflare Workflows, how do you define a workflow and start an instance of it from a Worker?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Export a class that extends WorkflowEntrypoint and implements run(event, step), declare it under workflows in the Wrangler file, then call env.BINDING.create({ id, params }) from a Worker; the instance runs its steps durably in the background.

open as a page

In Cloudflare Workflows, how do step.sleep(), step.sleepUntil() and step.waitForEvent() pause an instance, and what happens when a wait times out?

level: middleimportance: should knowfreq 38%

basics

~10 s

step.sleep() waits a duration and step.sleepUntil() until a Date or timestamp; step.waitForEvent() waits for instance.sendEvent() with a matching type, 24 hours by default. A timed-out waitForEvent() throws and fails the instance unless caught.

open as a page

A Cloudflare onboarding Workflow instance ended errored at its charge step; how do you inspect it and get that user's run going again?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Read instance.status() or wrangler workflows instances describe to see the error and each step's attempts, fix the cause, then call restart() on that instance, optionally from the failed step; create() with the same ID throws while the instance is retained.

open as a page