A Scheduled Trigger Starts Work but Does Not Model Every Step
Every Monday at 09:00 UTC, a small documentation team publishes a weekly digest. The first implementation is the obvious one: a Cron Trigger, a scheduled() handler, and four things done in sequence — collect the week's posts, render the email, hand it to a delivery provider, purge the CDN cache for the archive page.
It works for six weeks. On the seventh Monday the delivery provider returns a 503 three seconds into the send. The handler throws, the invocation ends, and nothing records that the posts were collected, the email was rendered, or that part of the recipient list had already accepted a message. The next Monday the same code runs from the top and sends a second copy to those recipients.
Cron answers when, not what finished
The bug is not in the code. It is in the choice of primitive. A Cron Trigger answers when. It does not answer what has already succeeded.
Define the terms before going further. A scheduled trigger maps a cron expression to a scheduled() handler. Cloudflare evaluates cron expressions in UTC and invokes the Worker; the trigger itself holds no per-run state. Durable execution means the platform records the completion and return value of each named unit of work, so a later attempt continues from the last recorded point instead of restarting the job. A step is that named unit — step.do("render email", ...). An instance is one run of a Workflow, with an ID you can query, pause, restart, or terminate.
The analogy is a short-order kitchen. The Cron Trigger is the alarm clock that tells the cook to start at 09:00. Durable execution is the ticket rail: each dish is crossed off as it leaves the pass, and the ticket survives a shift change. If the fire alarm interrupts service, the next cook reads the rail, not the clock. An alarm clock is still useful — it just cannot tell you what is already plated.
Figure 1 draws the two paths side by side. The cron path is one invocation with several unrecorded sub-tasks, so a failure at the send stage forces every earlier sub-task to be repeated. The Workflow path records each step result and retries only the step that failed.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
C[Cron fires at 09:00 UTC] --> H[scheduled handler runs]
H --> W[Fetch posts, render email, send, purge cache]
W -->|provider 503 during send| F[Handler throws]
F --> N[Next Monday repeats every sub-task]
H -.->|or create one instance| I[Workflow instance]
I --> S1[Step 1 result persisted]
S1 --> S2[Step 2 runs]
S2 -->|fails| R[Retry step 2 only]
R --> S2
S2 -->|succeeds| S3[Step 3 result persisted]
S3 --> D[Instance complete]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class C,H,F,N,I,S1,S2,R,S3 secondary;
class W,D ok;
Figure 2 makes the boundary explicit as layers. A cron trigger reaches the clock and the invocation, then stops. A Workflow also owns the layer where step outputs and instance status live; external effects sit outside both, which is why neither primitive can make an email "unsend".
Cron remains the correct tool for a single action that is safe to repeat: deleting expired sessions, warming a cache, emitting a heartbeat. The decision rule is not "is it periodic?" but "does partial completion matter?" If the answer is yes, the schedule should create an instance of something durable rather than do the work inline.
A cron invocation is capped at 15 minutes
Scheduled Workers have a 15-minute wall-clock limit per invocation, and Cron Trigger changes can take up to 15 minutes to propagate. A job that needs 40 minutes, or must survive a deploy mid-run, is already outside what a bare cron handler models.
Workflow Steps, Retries, and Durable Progress
Put the digest behind a Workflow and compare two Mondays. On the first, the first send step succeeds and returns a provider message ID, while step.do("send batch 2") throws a 503. Workflows persists the successful output, waits, and retries only the failed send. On the second Monday, the render step produces an empty document; NonRetryableError ends the instance instead of burning the retry budget on a permanent fault.
A step is a checkpoint, not a transaction
Each step.do callback runs in its own invocation, its return value is persisted, and the next step receives that value. Return values must be serializable and no larger than 1 MiB for non-stream results; store large artifacts in R2 and return a key. Step names are the identity used by operator restarts, so renaming one changes the replay boundary.
The default retry policy is easy to forget. With no configuration, Workflows allows 5 retries (6 attempts) with a 10-second base delay, exponential backoff, and a 10-minute timeout per attempt. The retry limit can be set as high as 10,000 per step, and the timeout applies to each attempt, not to the step as a whole. Retries re-run the callback from its first line — the detail that makes the next section necessary.
Workflows also removes time from the concurrency equation. step.sleep accepts a duration up to 365 days, and step.waitForEvent can pause until an external system or a human sends an event, with a 24-hour default timeout. Waiting instances do not count against concurrent-instance limits, so a million approvals can be pending without a million slots. A sleeping instance still needs a slot when it wakes, and at the ceiling it is queued rather than resumed instantly.
The table compares the four primitives that most often compete for the same job. The values are the documented behaviour as of the verification date in the final section; the limits are plan-specific and should be re-checked before designing around them.
| Criterion | Cron Trigger | Workflow | Durable Object alarm | Queue consumer |
|---|---|---|---|---|
| Unit of invocation | One scheduled() handler call | One instance with many steps | One object's alarm() handler | One batch of messages |
| Remembers completed sub-work | No; handler state dies with the invocation | Yes; each step output is persisted | Yes, in object storage, but you design the ledger | No; the message is retried as a whole |
| Retry granularity | Invocation level only; no per-step policy | Per step, with configurable limit, delay, backoff, timeout | Handler retried up to 6 times, exponential from 2 seconds | Per message or batch, with max_retries and optional dead-letter queue |
| Hard wall-clock ceiling | 15 minutes per invocation | Unlimited per step; CPU limit governs compute | 15 minutes per alarm invocation | 15 minutes per consumer invocation |
| Scheduling model | UTC cron expressions; 5 per account Free, 250 Paid | schedules on the binding, up to 100 expressions per account | setAlarm() per object, one alarm at a time | No schedule; delaySeconds up to 86400 |
| Best fit | Periodic single action that is safe to repeat | Multi-step work, long waits, human approval, compensation | Per-entity recurring work and coordination | Decoupling, buffering, fan-out, single-step jobs |
Figure 3 shows the retry path and the terminal path in sequence, including the point where a completed step's persisted output is reused rather than recomputed.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
autonumber
participant W as run(event, step)
participant E as Workflow engine
participant A as Provider API
W->>E: step.do("reserve slot")
E->>A: POST /reserve with Idempotency-Key
A-->>E: 201 reservationId
E-->>W: persist step output
W->>E: step.do("send batch 1")
E->>A: POST /send with Idempotency-Key
A-->>E: 503 upstream unavailable
E-->>W: step throws
Note over E: wait 10 seconds, exponential backoff
W->>E: retry "send batch 1" only
E->>A: POST /send with the same key
A-->>E: 200 deduplicated
E-->>W: persist step output
W->>E: step.do("purge cache")
E-->>W: 403 permanent failure
Note over W,E: rollbacks run in reverse order
The product boundary deserves a precise sentence. Workflows is included in both Workers Free and Workers Paid, but the plans are not equivalent: the Free plan allows 1,024 steps per instance, 100 concurrent instances, and 3 days of retention, while the Paid plan defaults to 10,000 steps (configurable to 25,000), 50,000 concurrent instances, and 7 days of retention (configurable up to 30). Read the current limits page for the plan you will deploy on rather than assuming parity.
The code below is a minimal publication workflow that exercises all three ideas: an idempotent reservation keyed to the business identity, a render step whose output is small enough to persist, and a publish step with its own compensating action. It uses D1 as the idempotency ledger, R2 for the artifact, and a deterministic instance ID so a repeated HTTP request cannot create a second run.
Three details carry the reliability
- Stable idempotency key. The key comes from the slug and revision, not from the attempt number or a timestamp, so every retry and restart presents the same key to the database.
- Content-addressed output. The published object key is derived from the revision, so a repeated write replaces identical bytes instead of creating a second artifact.
- Permanent faults stop. A missing source object throws
NonRetryableError, which stops the retry loop and lets the registered rollbacks run.
External Side Effects Need Idempotency
The misconception worth naming is that durable execution implies exactly-once effects. It does not. Durability is a statement about the platform's record of progress; the email provider, the payment processor, and the search index are outside that record.
Consider the failure window. A step sends POST /send, the provider commits, and the response is lost to a timeout. The step throws, so Workflows retries. Platform bookkeeping cannot distinguish "never received" from "received, acknowledgement lost", so the retry sends a second request unless the request carries a key the provider recognises.
Never mint the key inside the retry
The key must be stable across retries and restarts. Generating crypto.randomUUID() inside the step is the classic mistake: each attempt gets a fresh key, and the provider treats each attempt as new work. Derive the key from business identity — order-1042/charge, digest-2026-11-02/recipient-8812 — and store it next to the effect so an operator can reconcile after an incident.
Three patterns help, in order of preference. Use a provider that accepts an idempotency key and returns the original result on replay. Otherwise make the operation naturally idempotent: a deterministic object key, or INSERT ... ON CONFLICT DO NOTHING against a unique constraint. If neither is possible, record an intent row before the call and reconcile by querying the provider for the business key afterwards.
Compensation is not a substitute for idempotency. Rollback handlers undo reversible effects, but they run after the failure and can fail themselves. If a reader already fetched the published object, deleting it is a second visible change, not an undo. A compensating action should restore an invariant an observer can check — a redirect to the previous revision, a refund paired with a reversal record — rather than pretend the first effect never happened.
Design every effect to run twice
A Workflow does not re-run a completed step, but it does re-run a failed step from its first line — including any side effect that succeeded before the failure. Design every side-effecting step as if it will execute twice, because during an incident it will.
The verifiable consequence is simple to state: after a forced retry, a correctly keyed ledger contains exactly one row per business identity, and a correctly keyed provider shows one accepted message. Two rows, or two messages, mean the boundary was placed in the wrong layer.
Pausing, Resuming, and Operator Intervention
Operators need handles that match the state machine, not a generic "retry" button. Workflows exposes nine statuses, including unknown; each maps to a different intervention.
| State or call | Effect | Caveat |
|---|---|---|
queued, running, waiting | Scheduled, executing, or waiting on a sleep or event | Waiting instances do not hold a concurrency slot; waking ones queue at the ceiling |
waitingForPause | Pause requested; the in-flight step finishes first | Can last as long as the step's timeout |
paused | No step runs; resume, restart, or terminate remain available | Not terminal |
errored | Retries exhausted or a non-retryable error | Registered rollbacks run |
complete, terminated | Terminal states | A terminated instance cannot resume |
pause() | Moves to waitingForPause, then paused | Does not kill the current step |
resume() | Returns a paused instance to running | Queued first when the concurrency ceiling is reached |
restart() | Erases intermediate state and starts over | Side effects repeat |
restart({ from: ... }) | Reuses earlier outputs and re-runs the named step and everything after it | Later side effects repeat; their keys must still hold |
terminate(), delete() | terminate is final; delete removes state | terminate({ rollback: true }) runs rollback handlers; delete() skips them |
Figure 4 shows the transitions an operator can cause and the two terminal paths that do not involve an operator at all: a last step returning successfully, and a step exhausting its retry budget.
Three failure modes dominate operator experience. A run that looks stuck is usually a blocked network call or a long retry wait; pause it, read the step history, then restart from the failed step rather than the whole instance. Unbounded retries keep an instance alive while it repeats a permanent 404, so use NonRetryableError for 4xx and validation failures. Lost evidence is the quiet one: completed state is retained 3 days on Free and 7 days by default on Paid, so export the outputs you need — an audit table, an R2 object, a log line.
While a rollback executes, the status endpoint still reports running; inspect rollback.outcome after the instance settles. And a restart erases intermediate state, so state that must survive belongs outside the instance.
Model a Multi-Step Publication or Order Workflow
The exercise models the publication pipeline locally. It is design-only: nothing was executed for this article, no hosted deployment was performed, and no timings or costs were measured.
Setup uses two tabs: the Worker bindings and the local commands. The card then records what each action should prove.
Model a Multi-Step Publication or Order Workflow
Mode: design-only (not executed). No measured results are reported.
Prerequisites. Node.js 20 or later, npm, and a current Wrangler release: local Workflow methods and wrangler workflows --local are recent, so check npx wrangler --version. A Cloudflare account is only needed if you deploy; the exercise runs offline.
Setup. Create the project with the Hello World TypeScript template, add the three bindings from the JSON tab, run the table creation and object upload from the Bash tab, paste the workflow from the previous section into src/index.ts, then start the local server.
| Step | Action | Expected |
|---|---|---|
| 1 · Trigger | Send POST /?slug=hello&revision=1&sourceKey=drafts/hello.md and record the returned instance ID | One instance created |
| 2 · Repeat | Send the identical request again | Response is marked deduplicated; instance ID unchanged; the ledger still has one row |
| 3 · Inspect | Run npx wrangler workflows instances list publish-workflow --local (add --help if the subcommand differs) | One instance, status complete once the steps finish |
| 4 · Pause | Call pause() from an admin route or the CLI equivalent while the instance runs | Status moves through waitingForPause to paused; the in-flight step finishes rather than being killed |
| 5 · Resume | Call resume() and watch the instance | Returns to running and reaches complete |
| 6 · Force a retry | Make the render step throw once, for example by adding a flags row that the step reads and clears | The step context reports attempt: 2; the ledger and object count do not change |
Expected observations. One ledger row for hello@1, one object at the published revision key, and one instance that ends complete. A second HTTP request must not produce a second instance or a second row.
Failure checks.
- Drop the
UNIQUEconstraint and repeat action 2: two ledger rows appear, the duplicate-effect failure the constraint prevents. - Set the render step's retry limit to zero and feed it a missing
sourceKey: the instance endserroredinstead of retrying. - Make a rollback handler throw and check
rollback.outcome: it should reportfailed.
Cost dimensions. Local development incurs no Cloudflare charges. A hosted equivalent bills requests, CPU milliseconds, steps, and storage. Published Workflows pricing at the verification date lists 3,000 steps per day on Free, and 500,000 steps per month included on Paid with $0.80 per additional 100,000; storage is $0.20 per GB-month beyond the included 1 GB-month. Compute totals from your own step counts.
Cleanup. Stop the dev server and remove .wrangler/state to clear local R2 and D1 data. If you deployed, run npx wrangler delete, then remove the R2 bucket, D1 database, and Workflow from the dashboard.
If you prefer an order workflow, substitute reserve inventory, authorize payment, create shipment, and send confirmation for the four publication steps. The shape is identical: each external effect gets its own step, idempotency key, and compensating action. The publication version is easier to run locally because R2 and D1 replace a payment sandbox.
Retry a Failed Step Without Duplicating Its Side Effect
The test is narrow: after a controlled failure and retry, the ledger holds one row per business identity and the published object exists once. What follows is the evidence to collect, not a report of a run.
Pass criteria.
PASS— the ledger has exactly one row forhello@1after at least two attempts at the reservation step.PASS— the published object key is identical across attempts, and its bytes match the rendered revision.PASS— the instance reachescomplete, and each step's output is visible in the instance history.PASS— a permanent fault produceserroredwith aNonRetryableError, not an exhausted retry loop.FAIL— two ledger rows, two objects, or two provider messages for one business identity.FAIL— status remainsrunningwith no step transition beyond the configured timeout, orrollback.outcomeisfailedand nobody is alerted.
A duplicate row is an idempotency bug at the effect boundary. A stuck run is an observability or retry-policy bug; it may have produced no duplicate effect, but it has stopped making progress.
Self-check. Answer before reading the explanations.
- Does a Workflow guarantee that each step executes exactly once? No. A completed step is not re-executed during normal progress, but a failed step is retried from its first line, and a restart re-runs the target step and everything after it. The guarantee is durable progress, not exactly-once effects.
- Where should the idempotency key be generated? At the boundary of the external effect, from stable business identity, before the call. Generating it inside the retried callback produces a new key per attempt and defeats the provider's deduplication.
- When is a Cron Trigger still the right choice? When the job is a single action that is safe to repeat and partial completion has no meaning — a cache warm, a cleanup sweep, a heartbeat. If a failure halfway through would force you to reconstruct what finished, use a Workflow.
- What does
restart({ from: { name: "render artifact" } })do to earlier steps? It reuses their cached outputs and re-runs the named step and every step after it. Side effects in those later steps happen again, so their idempotency keys must still hold.
Unresolved limitations. Nothing was executed, so there are no measured latencies, costs, or provider behaviours. Local emulation does not reproduce production concurrency queuing, network partitions, or provider-side idempotency windows. D1's ON CONFLICT is the ledger primitive here; a system already built on Durable Objects would keep the same ledger in object storage, with the same uniqueness requirement. Workflows limits, retention defaults, and pricing change; the figures above are a snapshot, not a contract.
Verification. Documentation checked on 2026-11-05 against the pages listed below. No runtime version was tested because no deployment or local run was performed; the code is written against the documented Workers API but is unexecuted.
References.
- Cloudflare Workflows overview: https://developers.cloudflare.com/workflows/
- Sleeping and retrying: https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/
- Workflows Workers API: https://developers.cloudflare.com/workflows/build/workers-api/
- Triggering Workflows, including pause, resume, restart, and terminate: https://developers.cloudflare.com/workflows/build/trigger-workflows/
- Workflows limits: https://developers.cloudflare.com/workflows/reference/limits/
- Workflows pricing: https://developers.cloudflare.com/workflows/reference/pricing/
- Cron Triggers: https://developers.cloudflare.com/workers/configuration/cron-triggers/
- Workers limits, including Cron Trigger counts and wall time: https://developers.cloudflare.com/workers/platform/limits/
- Queues JavaScript APIs, including retries and acknowledgement: https://developers.cloudflare.com/queues/configuration/javascript-apis/
- Durable Objects alarms: https://developers.cloudflare.com/durable-objects/api/alarms/
- Workers best practices on choosing Queues or Workflows: https://developers.cloudflare.com/workers/best-practices/workers-best-practices/
Next in the Series
In Choose Containers, Sandboxes, or Browser Run, we'll explore Match Linux processes and browser sessions to the right execution model.