In Cloudflare Workflows, how do step.sleep(), step.sleepUntil() and step.waitForEvent() pause an instance, and what happens when a wait times out?
answer
- waiting is a step too
- a duration, a date, an event
- matching type, one instance
- default 24 hours, then it throws
basics
~10 sstep.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.
solid answer
~50 sAll three are steps, so the wait is persisted and the instance can hibernate in the `waiting` state, which does not count toward the concurrency limit. `step.sleep(name, duration)` takes milliseconds or a string such as `"14 days"`, up to 365 days; `step.sleepUntil(name, timestamp)` takes a `Date` or epoch milliseconds. `step.waitForEvent(name, { type, timeout })` blocks until code calls `instance.sendEvent({ type, payload })` on that instance, or the REST API's events endpoint is called, and returns an object with `payload`, `type` and `timestamp`. The `timeout` defaults to 24 hours and can be set from 1 second to 365 days. When it expires, `waitForEvent()` throws, and if nothing catches it the instance errors. A 'verify within three days' flow therefore wraps it in `try...catch` and takes the unverified branch. An event sent before the instance reaches the wait is buffered and delivered when it gets there.
code
javascript · 49 linesimport { WorkflowEntrypoint } from "cloudflare:workers";
export class OnboardingWorkflow extends WorkflowEntrypoint {
async run(event, step) {
const account = await step.do("create account", async () => {
return { userId: event.payload.userId };
});
let verified;
try {
verified = await step.waitForEvent("await email verification", {
type: "email-verified",
timeout: "3 days",
});
} catch {
return await step.do("mark unverified", async () => {
return { userId: account.userId, trial: false };
});
}
await step.do("start trial", async () => {
return { userId: account.userId, verifiedAt: verified.payload.at };
});
await step.sleep("trial period", "14 days");
return await step.do("charge first invoice", async () => {
return { charged: account.userId };
});
}
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
const instanceId = url.searchParams.get("instance");
if (url.pathname === "/verify") {
const instance = await env.ONBOARDING.get(instanceId);
await instance.sendEvent({
type: "email-verified",
payload: { at: new Date().toISOString() },
});
return Response.json(await instance.status());
}
const instance = await env.ONBOARDING.create({
id: `signup-${url.searchParams.get("user")}`,
params: { userId: url.searchParams.get("user") },
});
return Response.json({ id: instance.id });
},
};go deeper
Know the three waits: step.sleep() for a duration, step.sleepUntil() for a moment, and step.waitForEvent() for an event that sendEvent() delivers.
Explain matching by type on one instance, the 24-hour default timeout, the throw on timeout and the try/catch fallback, and that early events are buffered.
Design waits for production: instance IDs the webhook can derive, type names in the allowed character set, fallbacks for silence, and state rebuilt from step results after a long hibernation.
Decide which business deadlines live inside a Workflow as waits and timeouts and which stay in the product's own data, and who owns sending each external event.
## Three ways to wait A **Cloudflare Workflows** instance can stop for seconds or months without a Worker staying alive, because waiting is itself a step that the engine records. The onboarding flow uses two of them: it waits up to three days for the user to verify their email, then sleeps through a 14-day trial before charging. | Method | Argument | Ends when | Limits | |---|---|---|---| | `step.sleep(name, duration)` | ms or a string such as `"14 days"` | The duration passes | Up to 365 days | | `step.sleepUntil(name, timestamp)` | A `Date` or epoch milliseconds | That moment arrives | Behaves as a sleep until that moment | | `step.waitForEvent(name, { type, timeout })` | An event type and optional timeout | A matching event arrives, or it times out | Timeout 1 second to 365 days, default 24 hours | While an instance waits, its status is `waiting`, and **waiting instances do not count toward the concurrency limit**: millions can sleep at once, and only `running` instances use a slot. `step.sleep()` and `step.sleepUntil()` do not count toward the per-instance step limit either. When a sleeping instance wakes, it takes priority over newly queued instances. ## Sleeping - Duration strings use the units `second`, `minute`, `hour`, `day`, `week`, `month` and `year`, so `"3 hours"` and `"26 hours"` both work. - `step.sleepUntil()` suits a time that comes from elsewhere: a trial end date stored on the account, or "Monday 09:00 UTC". - A long sleep will probably hibernate the instance, so every value needed afterwards must come from a step's return value, not from a variable filled before the sleep. ## Waiting for an event The usual flow for an external signal such as a clicked verification link: 1. The Workflow calls `step.waitForEvent("await email verification", { type: "email-verified", timeout: "3 days" })`. 2. A separate Worker route receives the click, looks up the instance with `env.ONBOARDING.get(instanceId)`, and calls `instance.sendEvent({ type: "email-verified", payload })`. 3. The Workflow resumes, and `waitForEvent()` returns `{ payload, type, timestamp }`. Points that matter in practice: - `sendEvent()` targets **one instance**. The calling code must know the instance ID, which is why onboarding instances often get an ID derived from the sign-up, such as `signup-<userId>`. - The `type` must match exactly, is up to 100 characters, and allows only letters, digits, `-` and `_`. A dot, as in `email.verified`, is rejected with a `workflow.invalid_event_type` error. - An event sent **before** the instance reaches the matching `waitForEvent()` is buffered and delivered when execution gets there, so a fast click is not lost. - External systems can deliver the same event through the REST API's events endpoint, and `wrangler workflows instances send-event` sends one by hand with `--type` and `--payload`. ## What the event gives back `waitForEvent()` resolves to a `WorkflowStepEvent` with three fields: - `payload`: whatever the sender passed, which must be serializable, like any step result. - `type`: the matched event type. - `timestamp`: a `Date` for when the event was received. In TypeScript, a type parameter such as `step.waitForEvent<Verification>(...)` types `payload`. Because the wait is a step, its result is persisted like a `step.do()` result: on a later replay of `run()`, the same call returns the same event without waiting again. That is also why each wait needs a stable, deterministic name, and why one Workflow can wait several times, each wait with its own name and, where the signals differ, its own type. ## Timeouts When the timeout expires, `waitForEvent()` **throws**. The Workflow does not continue on its own, and an uncaught timeout leaves the instance `errored`. For a flow where silence is a normal outcome, catch it: - In `try`, wait for the event and continue to the trial. - In `catch`, run a step that marks the account unverified, or sends a reminder and waits again. Do not stretch a `step.do()` timeout to cover a human delay. The docs advise step timeouts of 30 minutes or less and point longer waits at `waitForEvent()`. ## Combining waits Because these are ordinary awaited calls, normal control flow works around them. A Workflow can wait for several event types, loop "remind, then wait again" a fixed number of times, or race an event against a deadline. As with any concurrency between steps, wrap a `Promise.race()` in its own `step.do()` so the outcome is recorded once.
- What happens if the user clicks the verification link before the Workflow reaches waitForEvent()?Nothing is lost. Once the instance exists, `instance.sendEvent()` with a matching `type` is buffered, and the `waitForEvent()` call returns it as soon as execution arrives there. The welcome-email step can still be running when the click lands. What fails is sending to an instance ID that was never created.
- Why use waitForEvent() instead of a long step timeout or a polling loop?A waiting instance hibernates: it spends no CPU and holds no concurrency slot. A step stretched over days goes against the advice to keep step timeouts at 30 minutes or less. A polling loop spends a step and a subrequest on every check, counting toward the step limit. `waitForEvent()` resumes the moment the event arrives, and its timeout gives a clean fallback branch.
- A sleeping Workflow instance keeps a Worker running and holds a concurrency slot.
- When waitForEvent() times out it returns undefined and the run carries on.
- sendEvent() reaches every instance of the Workflow that waits on that type.
- An event sent before the instance reaches waitForEvent() is dropped.
- step.sleep() calls count toward the per-instance step limit.
- Dotted event types such as email.verified are fine for waitForEvent().