okayus/okayus-skills/cloudflare-workflows-for-long-tasks
Claude Code and agent skill by okayus/okayus-skills
- community
Checking that the SKILL.md file is still in the repository.
Migrate a Cloudflare Worker post-response task off `ctx.waitUntil()` onto a `WorkflowEntrypoint` when the task can exceed the 30-second `waitUntil` wall-clock cap (Vision LLM inference, third-party API with slow tails, multi-step orchestration). Use when you see "waitUntil() tasks did not complete within the allowed time after invocation end and have been cancelled" in `wrangler tail`, or when DB rows get stuck in an in-progress state because the runtime killed the task before the catch block ran. Covers the exact `wrangler.jsonc` workflows binding, the `WorkflowEntrypoint` class export pattern alongside the default `fetch` handler, the `step.do()` retry / persist / serializable-output rules, the production cleanup runbook for rows orphaned in `running`/`pending` status, and the gotchas (the `Workflow<Params>` type is a global — via `wrangler types` or workers-types — not a `cloudflare:workers` import; bytes can't ride the wire between steps).
Install
npx vskill@latest install okayus/okayus-skills/cloudflare-workflows-for-long-tasksSKILL.md
The same SKILL.md was published earlier as okayus/okayus-skills/cloudflare-workflows-for-long-tasks.
Cloudflare Workflows for Long Tasks
Replace a ctx.waitUntil(longJob()) call with a Cloudflare Workflow when the job can exceed 30 seconds. Workflows give durable execution (minutes / hours / weeks), per-step retry, and persistent state — so a half-completed job never silently disappears.
Prerequisite: a working Worker that already does ctx.waitUntil(...) for some post-response work, and you've either hit the 30s cap in production or are designing a job that obviously will (Vision LLM, large file processing, external API with slow tails).
When to use
- A
ctx.waitUntil()task is being killed mid-run withwaitUntil() tasks did not complete within the allowed time after invocation end and have been cancelled - DB rows get stuck in
running/pendingbecause the kill is abrupt — yourtry/catchfor marking themfailednever runs - A long task needs automatic retry (e.g., flaky third-party API), and you don't want to hand-roll exponential backoff inside a 30s budget
- A job has natural steps that you want to checkpoint individually (download → transform → upload → notify), so a partial failure doesn't redo finished steps
- You want a UI to inspect the in-flight job (Cloudflare Dashboard shows each step's status;
step.do()outputs are durably persisted by the Workflows runtime)
Do not use for:
- Tasks that genuinely fit in 30 seconds —
ctx.waitUntil()is simpler, no extra binding, no class export - Fan-out / queue-style work — use Cloudflare Queues (a consumer invocation gets up to 15 min wall clock, 30s CPU by default / 5 min max — see Queues limits). Pick Queues for many small independent jobs, Workflows for one durable multi-step job with checkpoints
- Real-time streaming responses to a client — Workflows run after the response is sent; for streaming use SSE / WebSockets directly in the fetch handler
The 30s ceiling — and why it's worse than you'd expect
ctx.waitUntil() extends the Worker lifetime up to 30 seconds total (docs). Paid plan does not change this. When the budget runs out:
- The runtime cancels any in-flight Promise. Your code does not get a
try/catch-able rejection — it just stops mid-await. - Any DB row you flipped to
runningto record "I started" staysrunningforever, because the catch branch that would flip it tofailednever runs. wrangler tailshows a single warning line:(warn) waitUntil() tasks did not complete within the allowed time.... No stack, no step-level breakdown, no clue about whether the task was 1 second from finishing or hung from byte one.
This silently turns operational bugs into data corruption — every retry attempt creates another orphan, and you can't tell from the data whether the task is in flight or dead.
This is the migration trigger. If you're hitting it: fix forward to Workflows, don't just add a longer timeout (there is no longer timeout).
The migration: waitUntil → Workflow
Three artefacts change. The domain logic does not.
The "before" file gets deleted; its body becomes the body of three step.do() calls. The fetch-handler call site changes from ctx.waitUntil(runJob(...)) to env.MY_WORKFLOW.create({ params: ... }).
Full step-by-step migration guide in references/migration-pattern.md, including the production cleanup SQL for rows you orphaned before the migration.
Core deliverables
worker/lib/<job>-workflow.ts— theWorkflowEntrypointclass withrun(event, step). Steps split as:mark-running→ real work (with retries config) →persist-result, plusmark-failedin the catchwrangler.jsonc—workflows[]array entry mapping a binding name to aclass_nameworker/index.ts—export { JobWorkflow }alongsideexport default app(Hono / fetch handler)worker/types.ts— Bindings getsMY_WORKFLOW: Workflow<JobParams>(Workflowis a global, no import)- Fetch handler call site — replace
ctx.waitUntil(runJob(env, ...))withawait env.MY_WORKFLOW.create({ params: ... }) - Old
runJobfile deleted - Cleanup SQL run against production:
UPDATE <table> SET status='failed', error_message='waitUntil timeout (30s); migrating to Workflows', finished_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE status IN ('running', 'pending')
Full source for each file in references/implementation.md.
The step.do() rules you must internalise
A step.do(name, [config], async () => ...) block is not a normal await. The runtime treats it as a checkpoint:
- Idempotency. A step may be re-executed on retry or replay. Don't write code that double-counts (e.g.,
INSERTwithout anON CONFLICTclause, increment counters, send emails). Use upserts and idempotency keys. - Serializable outputs only. The return value of the callback is persisted as JSON.
ArrayBuffer,Uint8Array,Date,Map, class instances → all fail or get mangled. If you fetch bytes (R2 object, image), process them in the same step that fetched them — don't pass bytes between steps. Pass the small structured result instead. - Throwing triggers retry. If the callback throws, the step is retried up to
config.retries.limitwithconfig.retries.backoff. Past the limit, the throw propagates out of the workflow'srun()method. So your error path needs a top-leveltry/catchto mark the rowfailed, then re-throw so the Workflow run itself is also recorded as failed. - `config.timeout` is per attempt. A
timeout: "5 minutes"withretries.limit: 2means up to 15 minutes total wall-clock. Set both deliberately.
The third pitfall — bytes between steps — has tripped projects that intuit "split fetch and analyse into separate steps". Don't. Combine I/O + analysis in one step, return only the small JSON result.
More worked examples in references/pitfalls.md.
The Workflow<Params> type is a global, not an import
WorkflowEntrypoint / WorkflowEvent / WorkflowStep do come from cloudflare:workers (those are runtime values), but the binding type does not. This bites once per project; expect it.
Diagnosing the production scenario you're probably in
If you're reading this because rows are stuck and you don't know why, the symptom matrix:
status column | error_message | What happened | |
|---|---|---|---|
running, finished_at = NULL, hours old | NULL | ctx.waitUntil() cancellation. The catch branch never ran. Fix forward to Workflows. | |
running, finished_at = NULL, < 5 min old | NULL | Either still in flight (wait) or just got killed (will stay forever). Check wrangler tail for a "did not complete within the allowed time" warning | |
failed, error_message: "..." | populated | Caught error path ran. Read the message, fix the underlying error | |
succeeded, no values | populated or NULL | Job ran but produced no output — check the analyzer / builder logic, not the runtime |
Once on Workflows, the equivalent stuck case becomes a row with status='running' whose Workflow has been visibly retrying or marked failed in the Cloudflare Dashboard — much easier to diagnose.
Production cleanup runbook (one-time, before deploying the migration)
Keep the export file in backups/ (gitignored) for at least one release cycle. Full runbook in references/migration-pattern.md.
Scope boundary
This skill does NOT cover:
- Workers AI input shapes / model selection — Workflows give you durable execution and visibility into errors, but the analyzer logic itself is orthogonal. If you migrate to Workflows and the inner work still fails, fix it in the analyzer, not in the workflow plumbing
- Cloudflare Queues — different abstraction (batch consumer; 15 min wall clock per invocation, CPU 30s default / 5 min max). Use Queues when you have many small jobs that fan out, Workflows when you have one durable job per request
- Workflow signal events / external triggers —
step.waitForEventexists, but skeleton migration doesn't need it; cover it when you actually need approval / webhook gates - Local Workflow emulation —
wrangler devemulates Workflows locally (v3.89+); what is not supported is--remote/ remote bindings. This skill still assumes final verification against a deployed Worker — local dev can triggerenv.MY_WORKFLOW.create()and run steps in the emulator, but production observability (Dashboard instances) only exists deployed - Hono `c.executionCtx` vs Workers raw `ctx` — the migration replaces
c.executionCtx.waitUntil(...)(orctx.waitUntil(...)) withc.env.MY_WORKFLOW.create(...)either way; whichever framework you use, the call site change is the same
References
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/cloudflare-workflows-for-long-tasks/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-workflows-for-long-tasks)