In Cloudflare Workers, what does ctx.waitUntil() let a fetch handler do after returning its response, and what limits apply?
answer
- work the client need not wait for
- a floating promise can be cancelled
- thirty seconds after the response
- one budget shared by every call
basics
~20 sctx.waitUntil(promise) lets a fetch handler return its response while the runtime keeps running that promise, for up to 30 seconds after the response is sent or the client disconnects, shared across every waitUntil() call in the request.
solid answer
~40 s`ctx.waitUntil(promise)` hands a promise to the Workers runtime so the handler can return its `Response` immediately while the work, such as recording an analytics event, continues afterwards. For an HTTP-triggered Worker the extension lasts up to 30 seconds after the response is sent or the client disconnects, and that limit is shared by every `waitUntil()` call in the request; anything still pending is cancelled with a warning in Workers Logs. Promises from separate calls settle independently, like `Promise.allSettled`. Without `waitUntil()` or `await`, a promise can be cancelled when the invocation ends and its work silently lost. Work that might take longer, or must not be lost, belongs on a queue instead.
code
javascript · 17 linesexport default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const top = (await env.RANKINGS.get("top", "json")) ?? [];
// Runs after the response is sent; the response does not wait for it.
ctx.waitUntil(recordView(env, url.pathname));
return Response.json({ top });
},
};
async function recordView(env, path) {
const key = `views:${path}`;
const n = Number((await env.RANKINGS.get(key)) ?? "0");
await env.RANKINGS.put(key, String(n + 1));
}go deeper
Recall that ctx.waitUntil() lets the response go out while background work continues, and that the work gets up to 30 seconds after the response.
Explain the rules: the 30 seconds are shared across calls, floating promises may be cancelled, rejections settle independently, and streaming responses keep the invocation alive anyway.
Show production judgment: spot floating promises and destructured ctx in review, and move slow or must-not-lose work from waitUntil() to a queue consumer.
Frame it as a reliability boundary: waitUntil() is best effort for cheap side effects, so a team rule should say which work is allowed there and which needs durable delivery.
## Why post-response work needs a handle A Worker's `fetch` handler lives as long as its request does. Once the response has been fully sent, or the client has disconnected, the runtime may cancel whatever asynchronous work is still running for that request. A promise that is neither `await`ed, returned, nor passed to `ctx.waitUntil()` is a **floating promise**: it can be cancelled when the invocation ends, which drops logs, leaves writes half-done and swallows its errors without a trace. Take a leaderboard API Worker that, after answering `GET /top`, records an analytics event. The client does not need that event before it gets the rankings, so awaiting it would only add latency. Firing it and forgetting it would lose some events. `ctx.waitUntil()` is the middle path. ## What ctx.waitUntil() does `ctx.waitUntil(promise)` registers a promise with the runtime and returns immediately, so the handler can return its response at once. The runtime keeps the invocation alive while the promise settles, within these rules: - **30 seconds after the end.** For an HTTP-triggered Worker, `waitUntil()` extends execution for up to 30 seconds after the response is sent or the client disconnects. - **One shared budget.** That limit is shared across all `waitUntil()` calls in the same request; it is not 30 seconds per call. - **Cancellation is logged.** Promises still pending at the limit are cancelled, and Workers Logs and any attached Tail Workers receive the warning `waitUntil() tasks did not complete within the allowed time after invocation end and have been cancelled.` - **Independent settling.** Like `Promise.allSettled`, a rejected promise from one `waitUntil()` call does not stop the promises passed to other calls. - **Not a request timeout.** HTTP requests have no wall-time limit while the client stays connected, and a Worker still streaming a response body stays active without `waitUntil()`. ```javascript export default { async fetch(request, env, ctx) { const top = (await env.RANKINGS.get("top", "json")) ?? []; ctx.waitUntil(recordView(env, "/top")); return Response.json({ top }); }, }; ``` ## Choosing await, waitUntil or something else | The work | Use | |---|---| | The response depends on it, such as reading the rankings | `await` it before returning | | Small and after the fact, such as an analytics event or a cache write | `ctx.waitUntil()` | | May run past 30 seconds, or must never be lost | Send a message to a queue and let a consumer do it | | Logging exceptions, even when the handler throws | A Tail Worker attached to the Worker | `waitUntil()` is a best-effort extension, not a delivery guarantee: it does not retry a rejected promise, and work cut off at the limit is simply gone. Writes through Workers Analytics Engine do not need `waitUntil()` at all. ## Pitfalls to name in an interview 1. **Destructuring the context.** `const { waitUntil } = ctx; waitUntil(p)` detaches the method from `ctx`, and the call throws `TypeError: Illegal invocation`, complaining of an incorrect `this` reference. Call `ctx.waitUntil(p)` directly. 2. **Passing slow work.** A report that takes a minute to build will be cancelled after 30 seconds; move it to a queue consumer. 3. **Relying on it for correctness.** If the client must see the effect, such as a score that must be saved before the reply, `await` it. 4. **Using it to keep a Durable Object alive.** Durable Objects stay active while they handle requests or I/O; `waitUntil()` there exists only for API compatibility. In a scheduled handler the picture shifts slightly: the runtime already waits for the promise `scheduled()` returns, up to the 15-minute limit, so `await` is enough for one task, and `waitUntil()` matters for running several tasks at once and for recording the first failure as the run's status. ## How the legacy form compares In the deprecated Service Worker syntax the same method lived on the event, `event.waitUntil(promise)`. The module format moved it to `ctx`, the handler's third parameter, along with `passThroughOnException()`. The semantics, including the 30-second limit after the response, are the same; only the place you reach it changed. A strong middle-level answer names the 30-second shared limit, the cancellation of floating promises, and the rule for choosing between `await`, `waitUntil()` and a queue. A lint rule against floating promises, such as a no-floating-promises check in the team's linter, catches most of these bugs before review.
- Does a Cloudflare Worker's scheduled() handler need ctx.waitUntil() to finish its work?Not for a single task: the runtime waits for the promise `scheduled()` returns, up to the 15-minute limit of a Cron Trigger run, so `await` is enough. `ctx.waitUntil()` helps when several tasks run concurrently, and the first `waitUntil()` promise to fail is recorded as the run's status.
- Why does const { waitUntil } = ctx break in a Cloudflare Worker?Destructuring copies the method off `ctx`, so calling it loses its `this` binding and the runtime throws `TypeError: Illegal invocation`. Keep the call as `ctx.waitUntil(promise)`, or bind it explicitly if a helper needs it.
- When should a Cloudflare Worker send work to a queue instead of ctx.waitUntil()?When the work can run past the 30-second limit after the response, or when losing it is unacceptable. `waitUntil()` neither retries nor survives cancellation, while a queue delivers the message to a consumer Worker with retries.
- ctx.waitUntil() delays the response until the promise has settled.
- Each ctx.waitUntil() call gets its own separate 30-second allowance.
- A promise the handler never awaits still always finishes after the response.
- ctx.waitUntil() retries a rejected promise until it succeeds.
- Destructuring const { waitUntil } = ctx works the same as calling ctx.waitUntil().
- One rejected waitUntil() promise cancels the others registered for the request.