The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 492 lines 15.4 KB
Raw
1 ---
2 title: Add a Workflow
3 description: Orchestrate durable, multi-step work with Cloudflare Workflows — automatic retries, replayable steps, and at-least-once delivery.
4 sidebar:
5 order: 10
6 ---
7
8 This guide builds a Workflow end to end: a durable multi-step job
9 that writes to KV and broadcasts each task's progress back to a chat
10 `Room` Durable Object. For the concept, start at
11 [Workflows](/cloudflare/compute/workflows).
12
13 ## How a Workflow looks
14
15 The two-phase shape — a constructor `Effect.gen` that returns an
16 `Effect.fn` body — plus `task`, `sleep`, and the replay caution are
17 covered on [Workflows](/cloudflare/compute/workflows).
18
19 ## Create the workflow file
20
21 Create `src/NotifyWorkflow.ts` with a typed workflow body. The
22 `Effect.fn` takes the `input` payload directly, so `notifier.create({
23 params: { roomId, message } })` is type-checked end to end — and the
24 workflow's return value flows through to `instance.status().output`:
25
26 ```typescript
27 // src/NotifyWorkflow.ts
28 import * as Cloudflare from "@alchemy.run/cloudflare";
29 import * as Effect from "effect/Effect";
30 import Room from "./room.ts";
31
32 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
33 "Notifier",
34 Effect.gen(function* () {
35 const rooms = yield* Room;
36
37 return Effect.fn(function* (input: { roomId: string; message: string }) {
38 const { roomId, message } = input;
39 return { roomId, message };
40 });
41 }),
42 ) {}
43 ```
44
45 The constructor resolves shared dependencies — here, the `Room` DO
46 namespace from the previous tutorial so we can broadcast back to
47 it. The inner `Effect.fn` is the workflow body that the Cloudflare
48 runtime executes task by task.
49
50 ## Declare a KV namespace
51
52 Tasks need somewhere durable to read and write. Give the workflow
53 a KV namespace by declaring it in its own file:
54
55 ```typescript
56 // src/KV.ts
57 import * as Cloudflare from "@alchemy.run/cloudflare";
58
59 export const KV = Cloudflare.KV.Namespace("KV");
60 ```
61
62 `Cloudflare.KV.Namespace("KV")` is just a description — Alchemy
63 provisions the real namespace on the next deploy as soon as
64 something binds to it.
65
66 ## Bind KV to the workflow
67
68 `Cloudflare.KV.ReadWriteNamespace(KV)` belongs in the workflow's outer
69 Construction phase. It registers the binding on the workflow's worker and
70 returns a typed Effect-native client whose methods (`get`, `put`,
71 `list`, `delete`) are Effects you can `yield*` directly:
72
73 ```diff lang="typescript"
74 // src/NotifyWorkflow.ts
75 import * as Cloudflare from "@alchemy.run/cloudflare";
76 import * as Effect from "effect/Effect";
77 +import { KV } from "./KV.ts";
78 import Room from "./room.ts";
79
80 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
81 "Notifier",
82 Effect.gen(function* () {
83 const rooms = yield* Room;
84 + const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
85
86 return Effect.fn(function* (input: { roomId: string; message: string }) {
87 const { roomId, message } = input;
88 return { roomId, message };
89 });
90 }),
91 ) {}
92 ```
93
94 Yielding the binding in the constructor is a one-time setup — the
95 inner workflow body closes over `kv` and uses it on every run.
96
97 ## Add a task
98
99 `Cloudflare.Workflows.task("name", effect)` runs the inner Effect inside a
100 Cloudflare workflow step — the result is checkpointed so a crash +
101 replay returns the persisted value instead of re-running the side
102 effect. Wrap **anything** that touches the outside world — HTTP
103 calls, binding I/O, file writes — in a task:
104
105 ```diff lang="typescript"
106 // src/NotifyWorkflow.ts
107 import * as Cloudflare from "@alchemy.run/cloudflare";
108 import * as Effect from "effect/Effect";
109 import { KV } from "./KV.ts";
110 import Room from "./room.ts";
111
112 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
113 "Notifier",
114 Effect.gen(function* () {
115 const rooms = yield* Room;
116 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
117
118 return Effect.fn(function* (input: { roomId: string; message: string }) {
119 const { roomId, message } = input;
120
121 + const stored = yield* Cloudflare.Workflows.task(
122 + "kv-roundtrip",
123 + Effect.gen(function* () {
124 + const key = `workflow:${roomId}`;
125 + yield* kv.put(key, message);
126 + return yield* kv.get(key);
127 + }).pipe(Effect.orDie),
128 + );
129
130 - return { roomId, message };
131 + return { roomId, message: stored };
132 });
133 }),
134 ) {}
135 ```
136
137 `task` automatically threads the binding's service requirement
138 through, so `kv.put` / `kv.get` work directly inside the inner
139 Effect with no extra plumbing.
140
141 :::caution[Always wrap I/O in `task`]
142 The body Effect can re-execute many times during a replay. Anything
143 you do outside a `task` (like a raw `kv.put`) runs on every replay.
144 Wrapping the I/O in `task` makes the result persisted and the side
145 effect run exactly once.
146 :::
147
148 ## Broadcast to the chat room
149
150 Add another task that fans the stored value out to the matching
151 `Room` instance:
152
153 ```diff lang="typescript"
154 // src/NotifyWorkflow.ts
155 import * as Cloudflare from "@alchemy.run/cloudflare";
156 import * as Effect from "effect/Effect";
157 import { KV } from "./KV.ts";
158 import Room from "./room.ts";
159
160 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
161 "Notifier",
162 Effect.gen(function* () {
163 const rooms = yield* Room;
164 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
165
166 return Effect.fn(function* (input: { roomId: string; message: string }) {
167 const { roomId, message } = input;
168
169 const stored = yield* Cloudflare.Workflows.task(
170 "kv-roundtrip",
171 Effect.gen(function* () {
172 const key = `workflow:${roomId}`;
173 yield* kv.put(key, message);
174 return yield* kv.get(key);
175 }).pipe(Effect.orDie),
176 );
177
178 + const room = rooms.getByName(roomId);
179 + yield* Cloudflare.Workflows.task(
180 + "broadcast",
181 + room.broadcast(`[workflow] ${stored}`),
182 + );
183
184 return { roomId, message: stored };
185 });
186 }),
187 ) {}
188 ```
189
190 Calling the DO's `broadcast` RPC method from inside a `task` makes
191 the message-send durable too — replays don't double-broadcast.
192
193 ## Sleep between tasks
194
195 `Cloudflare.Workflows.sleep("name", "2 seconds")` parks the workflow without
196 billing for compute, then resumes at the requested time. Names are
197 required because Cloudflare uses them as replay keys:
198
199 ```diff lang="typescript"
200 // src/NotifyWorkflow.ts
201 import * as Cloudflare from "@alchemy.run/cloudflare";
202 import * as Effect from "effect/Effect";
203 import { KV } from "./KV.ts";
204 import Room from "./room.ts";
205
206 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
207 "Notifier",
208 Effect.gen(function* () {
209 const rooms = yield* Room;
210 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
211
212 return Effect.fn(function* (input: { roomId: string; message: string }) {
213 const { roomId, message } = input;
214
215 const stored = yield* Cloudflare.Workflows.task(
216 "kv-roundtrip",
217 Effect.gen(function* () {
218 const key = `workflow:${roomId}`;
219 yield* kv.put(key, message);
220 return yield* kv.get(key);
221 }).pipe(Effect.orDie),
222 );
223
224 const room = rooms.getByName(roomId);
225 yield* Cloudflare.Workflows.task(
226 "broadcast",
227 room.broadcast(`[workflow] ${stored}`),
228 );
229
230 + yield* Cloudflare.Workflows.sleep("cooldown", "2 seconds");
231 +
232 + yield* Cloudflare.Workflows.task(
233 + "finalize",
234 + room.broadcast(`[workflow] complete for ${roomId}`),
235 + );
236
237 return { roomId, message: stored };
238 });
239 }),
240 ) {}
241 ```
242
243 After the cool-down the workflow broadcasts a "complete" message
244 and finishes. The whole sequence — KV roundtrip → broadcast →
245 sleep → broadcast → return — is durable end to end.
246
247 ## Bind a secret
248
249 Most real workflows need credentials — an upstream API key, a
250 signing token, etc. `Config.Redacted` registers a `secret_text`
251 binding on the workflow at plantime and hands back a
252 `Redacted<string>` for use inside steps:
253
254 ```diff lang="typescript"
255 import * as Cloudflare from "@alchemy.run/cloudflare";
256 +import * as Config from "effect/Config";
257 import * as Effect from "effect/Effect";
258 import { KV } from "./KV.ts";
259 import Room from "./room.ts";
260
261 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
262 "Notifier",
263 Effect.gen(function* () {
264 const rooms = yield* Room;
265 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
266 + const apiKey = yield* Config.Redacted("API_KEY");
267 ```
268
269 `Config.Redacted("API_KEY")` reads `API_KEY` from the active
270 `Config` provider (env vars, `.env`, …) at plantime and binds it
271 into the workflow as `secret_text`. Set it in your local `.env`:
272
273 ```sh
274 # .env
275 API_KEY=sk-test-123
276 ```
277
278 See [Concepts › Secrets](/environments/secrets) for the full set of
279 input shapes (literals, `Effect`, `Config`, …).
280
281 ## Use the secret in a task
282
283 The `Redacted<string>` resolved in the constructor is captured by the Runtime
284 body. Unwrap with `Redacted.value` only at the call
285 site that needs it (here, an `Authorization` header):
286
287 ```diff lang="typescript"
288 // src/NotifyWorkflow.ts
289 import * as Cloudflare from "@alchemy.run/cloudflare";
290 import * as Config from "effect/Config";
291 import * as Effect from "effect/Effect";
292 +import * as Redacted from "effect/Redacted";
293 +import * as HttpClient from "effect/http/HttpClient";
294 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
295 import { KV } from "./KV.ts";
296 import Room from "./room.ts";
297
298 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
299 "Notifier",
300 Effect.gen(function* () {
301 const rooms = yield* Room;
302 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
303 const apiKey = yield* Config.Redacted("API_KEY");
304
305 return Effect.fn(function* (input: { roomId: string; message: string }) {
306 const { roomId, message } = input;
307
308 const stored = yield* Cloudflare.Workflows.task("kv-roundtrip", /* ... */);
309
310 const room = rooms.getByName(roomId);
311 yield* Cloudflare.Workflows.task(
312 "broadcast",
313 room.broadcast(`[workflow] ${stored}`),
314 );
315
316 + yield* Cloudflare.Workflows.task(
317 + "fetch-with-auth",
318 + HttpClientRequest.get("https://example.com/data").pipe(
319 + HttpClientRequest.bearerToken(Redacted.value(apiKey)),
320 + HttpClient.execute,
321 + Effect.flatMap((r) => r.text),
322 + ),
323 + );
324
325 yield* Cloudflare.Workflows.sleep("cooldown", "2 seconds");
326
327 yield* Cloudflare.Workflows.task(
328 "finalize",
329 room.broadcast(`[workflow] complete for ${roomId}`),
330 );
331
332 return { roomId, message: stored };
333 });
334 }),
335 ) {}
336 ```
337
338 `HttpClient.execute` runs inside
339 `Cloudflare.Workflows.task`, so the response is checkpointed and the
340 request only fires once across replays. `Redacted.value` is
341 called at the single header site that needs the cleartext;
342 elsewhere the value stays redacted.
343
344 ## Trigger from the Worker
345
346 A Workflow becomes a typed handle when you `yield*` it in the
347 Worker's Construction phase. Use `create()` to start an instance and
348 `get(id).status()` to poll it:
349
350 ```diff lang="typescript"
351 // src/worker.ts
352 import * as Cloudflare from "@alchemy.run/cloudflare";
353 import * as Effect from "effect/Effect";
354 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
355 import * as HttpServerResponse from "effect/http/HttpServerResponse";
356 +import NotifyWorkflow from "./NotifyWorkflow.ts";
357
358 export default Cloudflare.Worker(
359 "Worker",
360 { main: import.meta.url },
361 Effect.gen(function* () {
362 + const notifier = yield* NotifyWorkflow;
363
364 return {
365 fetch: Effect.gen(function* () {
366 + const request = yield* HttpServerRequest;
367 +
368 + if (
369 + request.url.startsWith("/workflow/start/") &&
370 + request.method === "POST"
371 + ) {
372 + const roomId = request.url.split("/").pop()!;
373 + const instance = yield* notifier.create({
374 + params: {
375 + roomId,
376 + message: "hello from workflow",
377 + },
378 + });
379 + return yield* HttpServerResponse.json({ instanceId: instance.id });
380 + }
381 +
382 + if (request.url.startsWith("/workflow/status/")) {
383 + const instanceId = request.url.split("/").pop()!;
384 + const instance = yield* notifier.get(instanceId);
385 + const status = yield* instance.status();
386 + return yield* HttpServerResponse.json(status);
387 + }
388 +
389 return HttpServerResponse.text("Hello from my Worker!");
390 }),
391 };
392 }),
393 );
394 ```
395
396 `notifier.create({ params })` immediately returns an instance id —
397 the workflow runs asynchronously on Cloudflare's side.
398 `instance.status()` returns one of `"queued"`, `"running"`,
399 `"paused"`, `"waiting"`, `"complete"`, `"errored"`, or
400 `"terminated"` along with the `output` (what the body Effect
401 returned) or `error`.
402
403 Deploy:
404
405 ```sh
406 bun alchemy deploy
407 ```
408
409 Add a test that POSTs to `/workflow/start/:roomId`, then polls
410 `/workflow/status/:instanceId` until the workflow reaches
411 `complete`:
412
413 ```diff lang="typescript"
414 // test/integ.test.ts
415 import * as Cloudflare from "@alchemy.run/cloudflare";
416 import * as Test from "@alchemy.run/test/Bun";
417 import { expect } from "bun:test";
418 import * as Effect from "effect/Effect";
419 import * as Schedule from "effect/Schedule";
420 import * as HttpClient from "effect/http/HttpClient";
421 import Stack from "../alchemy.run.ts";
422
423 const { test, beforeAll, deploy } = Test.make({
424 providers: Cloudflare.providers(),
425 state: Cloudflare.state(),
426 });
427
428 const stack = beforeAll(deploy(Stack));
429
430 +test(
431 + "Notifier workflow completes within 60s",
432 + Effect.gen(function* () {
433 + const { url } = yield* stack;
434 + const roomId = `room-${Date.now()}`;
435 +
436 + const start = yield* HttpClient.post(`${url}/workflow/start/${roomId}`);
437 + const { instanceId } = (yield* start.json) as { instanceId: string };
438 + expect(instanceId).toBeString();
439 +
440 + const status = yield* HttpClient.get(
441 + `${url}/workflow/status/${instanceId}`,
442 + ).pipe(
443 + Effect.flatMap((res) => res.json),
444 + Effect.map((s) => s as { status: string }),
445 + Effect.repeat({
446 + schedule: Schedule.spaced("2 seconds"),
447 + until: (s) => s.status === "complete" || s.status === "errored",
448 + }),
449 + Effect.timeout("60 seconds"),
450 + );
451 +
452 + expect(status.status).toBe("complete");
453 + }),
454 + { timeout: 120_000 },
455 +);
456 ```
457
458 ```sh
459 bun test test/integ.test.ts
460 ```
461
462 The polling loop should see the workflow transition through
463 `running` and finish in `complete` within ~5 seconds (most of which
464 is the `sleep("cooldown", "2 seconds")` cooldown).
465
466 ## Test it locally
467
468 The same test runs entirely on your machine — no separate
469 workerd/vitest setup needed. Add `dev: true` to `Test.make` and the
470 whole stack (Worker, Workflow, KV, Durable Objects) boots in a
471 local workerd with real step semantics — tasks checkpoint, sleeps
472 park, replays skip completed steps:
473
474 ```diff lang="typescript"
475 const { test, beforeAll, deploy } = Test.make({
476 providers: Cloudflare.providers(),
477 state: Cloudflare.state(),
478 + dev: true,
479 });
480 ```
481
482 `stack.url` now points at `http://localhost:<port>`, and the
483 start/poll assertions run unchanged against the local workflow. See
484 [Test harness → dev](/testing/test-harness#dev) for the option's
485 full semantics, and [Local development](/cloudflare/local-development)
486 for what else runs locally.
487
488 Your app now spans a Worker, a Vite frontend, Durable Objects,
489 hibernatable WebSockets, a Container, and a Workflow — all
490 deploying from CI thanks to [Part 5](/cloudflare/tutorial/part-5). From here,
491 browse the [Concepts](/infrastructure-as-code/stack), [Guides](/cli), and
492 [Providers](/providers) sections for whatever you need next.