The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | --- |
| 2 | title: Durable Objects |
| 3 | description: Durable Objects are globally-unique stateful instances with transactional storage — define one as an Effect, persist state per key, expose typed RPC methods, and stream values back to the caller. |
| 4 | --- |
| 5 | |
| 6 | A Durable Object (DO) is a globally-unique stateful instance |
| 7 | addressed by name: every request for `"user-123"` — from any Worker, |
| 8 | anywhere in the world — lands on the *same* instance, with its own |
| 9 | transactional SQLite-backed storage. That combination of identity + |
| 10 | storage + single-threaded execution makes DOs the right tool for |
| 11 | per-entity state: counters, chat rooms, game sessions, WebSocket |
| 12 | hubs, rate limiters, collaborative documents. |
| 13 | |
| 14 | In alchemy a DO is a class with the same two-phase Effect pattern as |
| 15 | a [Worker](/cloudflare/compute/workers), and every method you return becomes |
| 16 | a typed RPC method — no schemas, no serialization boilerplate. This |
| 17 | page builds one from scratch: a `Counter` that keeps a per-key count |
| 18 | in transactional storage, exposes RPC methods, and streams a |
| 19 | sequence of numbers back to the caller. It also shows how to |
| 20 | [schedule durable callbacks](#create-an-object-for-scheduled-work) |
| 21 | atomically with application writes. |
| 22 | |
| 23 | ## Create the Counter file |
| 24 | |
| 25 | Like Workers, a DO has two `Effect.gen` blocks: the outer one |
| 26 | resolves the instance's `state` and any shared dependencies, and |
| 27 | the inner one returns the public API. |
| 28 | |
| 29 | Create `src/counter.ts` with the smallest possible DO — empty |
| 30 | public API, no state yet: |
| 31 | |
| 32 | ```typescript |
| 33 | // src/counter.ts |
| 34 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 35 | import * as Effect from "effect/Effect"; |
| 36 | |
| 37 | export default class Counter extends Cloudflare.DurableObject<Counter>()( |
| 38 | "Counter", |
| 39 | Effect.gen(function* () { |
| 40 | // Outer (Construction): resolve the instance state and shared |
| 41 | // dependencies here. |
| 42 | return Effect.gen(function* () { |
| 43 | // Inner: return the public API for this instance. |
| 44 | return {}; |
| 45 | }); |
| 46 | }), |
| 47 | ) {} |
| 48 | ``` |
| 49 | |
| 50 | :::tip[Why `Cloudflare.DurableObject<Counter>()(...)` ?] |
| 51 | The empty `()` after `Cloudflare.DurableObject<Counter>` lets |
| 52 | TypeScript capture the class identity for the typed RPC stub. It's a |
| 53 | one-time bit of ceremony — the rest of your DO code looks completely |
| 54 | normal. |
| 55 | ::: |
| 56 | |
| 57 | ## Persist the count |
| 58 | |
| 59 | Each DO instance has its own key/value storage, backed by SQLite. |
| 60 | Resolve `Cloudflare.DurableObjectState` in the **outer** Effect, |
| 61 | then pull the current count out of storage in the inner constructor so it |
| 62 | survives restarts and hibernation: |
| 63 | |
| 64 | ```diff lang="typescript" |
| 65 | Effect.gen(function* () { |
| 66 | + const state = yield* Cloudflare.DurableObjectState; |
| 67 | return Effect.gen(function* () { |
| 68 | + let count = (yield* state.storage.get<number>("count")) ?? 0; |
| 69 | return {}; |
| 70 | }); |
| 71 | }); |
| 72 | ``` |
| 73 | |
| 74 | `Cloudflare.DurableObjectState` is the same per-instance handle |
| 75 | Cloudflare exposes for `storage`, `setAlarm`, `acceptWebSocket`, |
| 76 | and friends. We'll use it more in the next part for WebSockets. |
| 77 | |
| 78 | :::note |
| 79 | You resolve the *reference* to `state` in the outer (Construction) Effect, |
| 80 | but its methods — like `storage.get` — are |
| 81 | [colored with `RuntimeContext`](/infrastructure-as-effects/layers#the-types-hold-the-boundary), |
| 82 | so you can only *use* them in the inner (runtime) Effect. That's why |
| 83 | `state` is yielded above but `state.storage.get(...)` lives below. |
| 84 | ::: |
| 85 | |
| 86 | ## SQL migrations |
| 87 | |
| 88 | For objects that use SQL tables, generate and commit migration files with your |
| 89 | schema changes before deploying. Load them in the outer Effect and apply them |
| 90 | in the inner Effect: |
| 91 | |
| 92 | ```typescript |
| 93 | Effect.gen(function* () { |
| 94 | const migrations = yield* Cloudflare.SqlMigrations("./drizzle"); |
| 95 | |
| 96 | return Effect.gen(function* () { |
| 97 | yield* migrations.apply().pipe(Effect.orDie); |
| 98 | return {}; |
| 99 | }); |
| 100 | }); |
| 101 | ``` |
| 102 | |
| 103 | Pending SQL runs when each object activates, before its public methods are |
| 104 | available. See [SQL migrations](/sql/effect-sql/migrations#durable-object-migrations) |
| 105 | for the full setup, or pass the same `migrations` to |
| 106 | [`Drizzle.DurableObject({ migrations, relations })`](/sql/drizzle/migrations#durable-object-migrations). |
| 107 | |
| 108 | ## Add `increment` and `get` |
| 109 | |
| 110 | Any function you return from the inner Effect that produces an |
| 111 | `Effect` becomes a typed RPC method. Add one to mutate the count |
| 112 | and one to read it: |
| 113 | |
| 114 | ```diff lang="typescript" |
| 115 | Effect.gen(function* () { |
| 116 | const state = yield* Cloudflare.DurableObjectState; |
| 117 | return Effect.gen(function* () { |
| 118 | let count = (yield* state.storage.get<number>("count")) ?? 0; |
| 119 | - return {}; |
| 120 | + return { |
| 121 | + increment: () => |
| 122 | + Effect.gen(function* () { |
| 123 | + count += 1; |
| 124 | + yield* state.storage.put("count", count); |
| 125 | + return count; |
| 126 | + }), |
| 127 | + get: () => Effect.succeed(count), |
| 128 | + }; |
| 129 | }); |
| 130 | }); |
| 131 | ``` |
| 132 | |
| 133 | Workers will see `counter.increment()` returning |
| 134 | `Effect<number>` and `counter.get()` returning `Effect<number>`, |
| 135 | fully type-checked through the Cloudflare RPC machinery. |
| 136 | |
| 137 | ## Bind the DO to the Worker |
| 138 | |
| 139 | Yield the `Counter` class in your Worker's Construction phase to get a |
| 140 | namespace handle: |
| 141 | |
| 142 | ```diff lang="typescript" |
| 143 | // src/worker.ts |
| 144 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 145 | import * as Effect from "effect/Effect"; |
| 146 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 147 | +import Counter from "./counter.ts"; |
| 148 | |
| 149 | export default Cloudflare.Worker( |
| 150 | "Worker", |
| 151 | { main: import.meta.url }, |
| 152 | Effect.gen(function* () { |
| 153 | + const counters = yield* Counter; |
| 154 | |
| 155 | return { |
| 156 | fetch: Effect.gen(function* () { |
| 157 | return HttpServerResponse.text("Hello from my Worker!"); |
| 158 | }), |
| 159 | }; |
| 160 | }), |
| 161 | ); |
| 162 | ``` |
| 163 | |
| 164 | `yield* Counter` in the constructor registers the DO with the Worker |
| 165 | (binding + Durable Object `exports` metadata) and hands you the namespace. |
| 166 | |
| 167 | ## Call the DO from `fetch` |
| 168 | |
| 169 | Inside the `fetch` handler, route `POST /counter/:name` to the DO |
| 170 | by calling `getByName(...)` to obtain a typed stub, then invoking |
| 171 | `increment()`: |
| 172 | |
| 173 | ```diff lang="typescript" |
| 174 | // src/worker.ts |
| 175 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 176 | import * as Effect from "effect/Effect"; |
| 177 | +import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 178 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 179 | import Counter from "./counter.ts"; |
| 180 | |
| 181 | export default Cloudflare.Worker( |
| 182 | "Worker", |
| 183 | { main: import.meta.url }, |
| 184 | Effect.gen(function* () { |
| 185 | const counters = yield* Counter; |
| 186 | |
| 187 | return { |
| 188 | fetch: Effect.gen(function* () { |
| 189 | + const request = yield* HttpServerRequest; |
| 190 | + |
| 191 | + if (request.url.startsWith("/counter/") && request.method === "POST") { |
| 192 | + const name = request.url.split("/").pop()!; |
| 193 | + const next = yield* counters.getByName(name).increment(); |
| 194 | + return HttpServerResponse.text(String(next)); |
| 195 | + } |
| 196 | + |
| 197 | return HttpServerResponse.text("Hello from my Worker!"); |
| 198 | }), |
| 199 | }; |
| 200 | }), |
| 201 | ); |
| 202 | ``` |
| 203 | |
| 204 | `counters.getByName(name)` returns a typed stub: the Worker sees |
| 205 | `increment(): Effect<number>` and `get(): Effect<number>` exactly as |
| 206 | you defined them. Calling `.increment()` round-trips through |
| 207 | Cloudflare's RPC machinery to the durable instance. |
| 208 | |
| 209 | ## Deploy and verify |
| 210 | |
| 211 | Re-deploy. Alchemy plans a Worker update and a new `Counter` |
| 212 | namespace: |
| 213 | |
| 214 | ```sh |
| 215 | bun alchemy deploy |
| 216 | ``` |
| 217 | |
| 218 | Add a test that hits `/counter/foo` twice (expecting `1` then `2`) |
| 219 | and `/counter/bar` once (expecting `1`) — each name addresses its |
| 220 | own stateful instance: |
| 221 | |
| 222 | ```diff lang="typescript" |
| 223 | // test/integ.test.ts |
| 224 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 225 | import * as Test from "@alchemy.run/test/Bun"; |
| 226 | import { expect } from "bun:test"; |
| 227 | import * as Effect from "effect/Effect"; |
| 228 | import * as HttpClient from "effect/http/HttpClient"; |
| 229 | import Stack from "../alchemy.run.ts"; |
| 230 | |
| 231 | const { test, beforeAll, deploy } = Test.make({ |
| 232 | providers: Cloudflare.providers(), |
| 233 | state: Cloudflare.state(), |
| 234 | }); |
| 235 | |
| 236 | const stack = beforeAll(deploy(Stack)); |
| 237 | |
| 238 | +test( |
| 239 | + "Counter persists per key", |
| 240 | + Effect.gen(function* () { |
| 241 | + const { url } = yield* stack; |
| 242 | + |
| 243 | + const a1 = yield* HttpClient.post(`${url}/counter/foo`); |
| 244 | + expect(yield* a1.text).toBe("1"); |
| 245 | + |
| 246 | + const a2 = yield* HttpClient.post(`${url}/counter/foo`); |
| 247 | + expect(yield* a2.text).toBe("2"); |
| 248 | + |
| 249 | + const b1 = yield* HttpClient.post(`${url}/counter/bar`); |
| 250 | + expect(yield* b1.text).toBe("1"); |
| 251 | + }), |
| 252 | +); |
| 253 | ``` |
| 254 | |
| 255 | ```sh |
| 256 | bun test test/integ.test.ts |
| 257 | ``` |
| 258 | |
| 259 | ## Stream RPC return values |
| 260 | |
| 261 | RPC isn't limited to single values — any `Effect` (or `Stream`) you |
| 262 | return becomes a typed RPC method. Let's add a `tick(n)` method that |
| 263 | emits a sequence of numbers `100ms` apart, then expose an HTTP route |
| 264 | that streams them back to the client. |
| 265 | |
| 266 | Add `tick` to `src/counter.ts`: |
| 267 | |
| 268 | ```diff lang="typescript" |
| 269 | // src/counter.ts |
| 270 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 271 | import * as Effect from "effect/Effect"; |
| 272 | +import * as Schedule from "effect/Schedule"; |
| 273 | +import * as Stream from "effect/Stream"; |
| 274 | |
| 275 | export default class Counter extends Cloudflare.DurableObject<Counter>()( |
| 276 | "Counter", |
| 277 | Effect.gen(function* () { |
| 278 | const state = yield* Cloudflare.DurableObjectState; |
| 279 | return Effect.gen(function* () { |
| 280 | let count = (yield* state.storage.get<number>("count")) ?? 0; |
| 281 | |
| 282 | return { |
| 283 | increment: () => |
| 284 | Effect.gen(function* () { |
| 285 | count += 1; |
| 286 | yield* state.storage.put("count", count); |
| 287 | return count; |
| 288 | }), |
| 289 | get: () => Effect.succeed(count), |
| 290 | + tick: (n: number) => |
| 291 | + Stream.iterate(0, (i) => i + 1).pipe( |
| 292 | + Stream.take(n), |
| 293 | + Stream.schedule(Schedule.spaced("100 millis")), |
| 294 | + ), |
| 295 | }; |
| 296 | }); |
| 297 | }), |
| 298 | ) {} |
| 299 | ``` |
| 300 | |
| 301 | Forward the stream from the Worker's `fetch` handler. Use |
| 302 | `HttpServerResponse.stream` to flush each chunk as it arrives: |
| 303 | |
| 304 | ```diff lang="typescript" |
| 305 | // src/worker.ts |
| 306 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 307 | import * as Effect from "effect/Effect"; |
| 308 | +import * as Stream from "effect/Stream"; |
| 309 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 310 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 311 | import Counter from "./counter.ts"; |
| 312 | |
| 313 | export default Cloudflare.Worker( |
| 314 | "Worker", |
| 315 | { main: import.meta.url }, |
| 316 | Effect.gen(function* () { |
| 317 | const counters = yield* Counter; |
| 318 | |
| 319 | return { |
| 320 | fetch: Effect.gen(function* () { |
| 321 | const request = yield* HttpServerRequest; |
| 322 | |
| 323 | if (request.url.startsWith("/counter/") && request.method === "POST") { |
| 324 | const name = request.url.split("/").pop()!; |
| 325 | const next = yield* counters.getByName(name).increment(); |
| 326 | return HttpServerResponse.text(String(next)); |
| 327 | } |
| 328 | |
| 329 | + if (request.url.startsWith("/tick/") && request.method === "GET") { |
| 330 | + const n = Number(request.url.split("/").pop()!); |
| 331 | + const stream = counters.getByName("tick").tick(n).pipe( |
| 332 | + Stream.map((i) => `${i}\n`), |
| 333 | + Stream.encodeText, |
| 334 | + ); |
| 335 | + return HttpServerResponse.stream(stream, { |
| 336 | + headers: { "content-type": "text/plain" }, |
| 337 | + }); |
| 338 | + } |
| 339 | + |
| 340 | return HttpServerResponse.text("Hello from my Worker!"); |
| 341 | }), |
| 342 | }; |
| 343 | }), |
| 344 | ); |
| 345 | ``` |
| 346 | |
| 347 | Add the test: |
| 348 | |
| 349 | ```diff lang="typescript" |
| 350 | // test/integ.test.ts |
| 351 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 352 | import * as Test from "@alchemy.run/test/Bun"; |
| 353 | import { expect } from "bun:test"; |
| 354 | import * as Effect from "effect/Effect"; |
| 355 | +import * as Stream from "effect/Stream"; |
| 356 | import * as HttpClient from "effect/http/HttpClient"; |
| 357 | import Stack from "../alchemy.run.ts"; |
| 358 | |
| 359 | const { test, beforeAll, deploy } = Test.make({ |
| 360 | providers: Cloudflare.providers(), |
| 361 | state: Cloudflare.state(), |
| 362 | }); |
| 363 | |
| 364 | const stack = beforeAll(deploy(Stack)); |
| 365 | |
| 366 | +test( |
| 367 | + "tick streams 5 sequential values", |
| 368 | + Effect.gen(function* () { |
| 369 | + const { url } = yield* stack; |
| 370 | + |
| 371 | + const response = yield* HttpClient.get(`${url}/tick/5`); |
| 372 | + const lines = yield* response.stream.pipe( |
| 373 | + Stream.decodeText, |
| 374 | + Stream.splitLines, |
| 375 | + Stream.runCollect, |
| 376 | + ); |
| 377 | + expect([...lines]).toEqual(["0", "1", "2", "3", "4"]); |
| 378 | + }), |
| 379 | +); |
| 380 | ``` |
| 381 | |
| 382 | The DO produces values lazily, the runtime ferries each chunk back |
| 383 | to the Worker, and the Worker pipes them straight onto the HTTP |
| 384 | response — all type-checked end-to-end. |
| 385 | |
| 386 | ## Schemaless RPC |
| 387 | |
| 388 | Everything you just built *is* RPC — and you never declared a |
| 389 | schema. Any function returning an `Effect` (or a `Stream`) from the |
| 390 | inner block becomes a typed method, and `getByName(name)` hands |
| 391 | callers a stub that mirrors those signatures exactly: |
| 392 | |
| 393 | ```typescript |
| 394 | const counters = yield* Counter; |
| 395 | |
| 396 | const counter = counters.getByName("user-123"); |
| 397 | const value = yield* counter.increment(); // Effect<number> |
| 398 | ``` |
| 399 | |
| 400 | This schemaless, typed-stub pattern — the DO shape of |
| 401 | [Schemaless RPC](/apis/schemaless) — is the recommended way to talk |
| 402 | to a Durable Object. The types flow from the implementation — add a |
| 403 | method, and every caller sees it immediately; change a return type, |
| 404 | and every caller that mismatches fails to compile. The same |
| 405 | mechanism works across Workers: one Worker can host the DO while |
| 406 | others bind to it by class — see |
| 407 | [Bind to another Worker's Durable Object](/cloudflare/compute/cross-worker-durable-object). |
| 408 | |
| 409 | Alchemy also ships a schema-based `RpcDurableObject` that serves an |
| 410 | Effect RPC group on the DO's `fetch`. It is no longer the suggested |
| 411 | path for DO method calls — the schemaless bridge covers typed |
| 412 | methods and streaming without the ceremony. Its one remaining niche |
| 413 | is when return values are `Schema.Class` instances whose identity |
| 414 | must survive the boundary — the schemaless bridge serializes return |
| 415 | values and strips class identity — see |
| 416 | [`Cloudflare.RpcDurableObject`](/cloudflare/apis/effect-rpc#sugar-cloudflarerpcdurableobject). |
| 417 | If you want schema-*validated* procedures (payload validation, |
| 418 | tagged error schemas shared with external clients), reach for |
| 419 | [Effect RPC](/cloudflare/apis/effect-rpc) on a Worker instead. |
| 420 | |
| 421 | ## Place an instance in a region |
| 422 | |
| 423 | A Durable Object is created wherever its **first-ever** request came |
| 424 | from, and it lives there for good. That is the right default when an |
| 425 | instance's traffic all comes from whoever created it — `getByName(userId)` |
| 426 | lands next to that user by construction. |
| 427 | |
| 428 | It is the wrong default as soon as the name stops tracking geography. A |
| 429 | pool sharded by hash (`pool:7`), a fixed roster, a shard index — any of |
| 430 | these can be created by whichever request happened to arrive first, and |
| 431 | every later caller pays for that accident. A Sydney user hashed onto an |
| 432 | instance a Frankfurt request created is making a cross-planet round trip |
| 433 | on every call, forever. |
| 434 | |
| 435 | Pass a `locationHint` to say where a **new** instance should be created: |
| 436 | |
| 437 | ```typescript |
| 438 | const shard = shards.getByName("pool:apac:3", { locationHint: "apac" }); |
| 439 | ``` |
| 440 | |
| 441 | Hints only apply at creation, so this is safe to add to an existing call |
| 442 | site: instances that already exist stay where they are, and nothing you |
| 443 | pass can move them. |
| 444 | |
| 445 | Derive the name and the hint from the same region, so each region |
| 446 | addresses its own shards: |
| 447 | |
| 448 | ```typescript |
| 449 | // in a Worker fetch handler |
| 450 | const region = hintFor(request.cf?.continent); // your own mapping |
| 451 | const shard = shards.getByName(`pool:${region}:${index}`, { |
| 452 | locationHint: region, |
| 453 | }); |
| 454 | ``` |
| 455 | |
| 456 | :::caution |
| 457 | Hint the region you name. If two regions can address one name, they race |
| 458 | to create the single instance behind it and the loser is stuck talking |
| 459 | across the planet — the hint cannot fix it afterwards. |
| 460 | ::: |
| 461 | |
| 462 | Available hints are `wnam`, `enam`, `sam`, `weur`, `eeur`, `apac`, `oc`, |
| 463 | `afr`, and `me`. Each is best-effort: |
| 464 | Cloudflare places the instance in the nearest location it can to the |
| 465 | hinted region, which may not be inside it. Under `alchemy dev` there is |
| 466 | only one location to place anything in, so hints are accepted and |
| 467 | ignored — placement is only observable once deployed. |
| 468 | |
| 469 | ## Keep an instance inside a jurisdiction |
| 470 | |
| 471 | A `locationHint` is best-effort. When data must stay inside a region for |
| 472 | compliance, address the object through `jurisdiction()` instead: |
| 473 | |
| 474 | ```typescript |
| 475 | const room = rooms.jurisdiction("eu").getByName(roomId); |
| 476 | ``` |
| 477 | |
| 478 | Cloudflare creates and stores that object only inside the jurisdiction. |
| 479 | The same name addresses a different object than it does without |
| 480 | `jurisdiction()`, so pick one form per name and keep using it. |
| 481 | |
| 482 | ## Call scope vs isolate scope |
| 483 | |
| 484 | A Durable Object shares its isolate's layer build with the Worker |
| 485 | that hosts it — the entrypoint's constructor runs **once per isolate**, and |
| 486 | every DO activation (including hibernatable-WebSocket wakes, which |
| 487 | re-run the constructor) reuses it. Each method call, `fetch`, |
| 488 | `alarm`, or WebSocket event then runs with a **fresh `Scope`**, |
| 489 | closed via `state.waitUntil` after the call settles — so |
| 490 | `Effect.addFinalizer` inside a method runs after the RPC response is |
| 491 | returned, and a returned `Stream` keeps the scope alive until it |
| 492 | finishes draining. |
| 493 | |
| 494 | As everywhere on workerd, there is no isolate-teardown hook: cleanup |
| 495 | belongs in methods (call scope), not in the class constructor or the Construction phase. |
| 496 | Per-call resources like `Drizzle.Postgres` pools open lazily inside |
| 497 | the method and close with its scope (see the |
| 498 | [SQL connection lifecycle](/sql/effect-sql/lifecycle)). See |
| 499 | [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope) |
| 500 | for the model across all runtimes. |
| 501 | |
| 502 | ## Create an object for scheduled work |
| 503 | |
| 504 | Use `Alchemy.makeCallback` when work must survive the request and run |
| 505 | later. Durable Objects persist these jobs in SQLite and deliver them |
| 506 | through native alarms; a timer or a forked fiber does not provide that |
| 507 | persistence. |
| 508 | |
| 509 | For this example, create a `Document` object that will save its current |
| 510 | body and schedule a revision snapshot: |
| 511 | |
| 512 | ```typescript |
| 513 | // src/document.ts |
| 514 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 515 | import * as Effect from "effect/Effect"; |
| 516 | |
| 517 | export default class Document extends Cloudflare.DurableObject<Document>()( |
| 518 | "Document", |
| 519 | Effect.gen(function* () { |
| 520 | const state = yield* Cloudflare.DurableObjectState; |
| 521 | return Effect.gen(function* () { |
| 522 | return {}; |
| 523 | }); |
| 524 | }), |
| 525 | ) {} |
| 526 | ``` |
| 527 | |
| 528 | Each named `Document` has its own storage and pending jobs, just as each |
| 529 | named `Counter` has its own count. Bind it to a Worker by yielding the |
| 530 | `Document` class in the Worker's Construction phase. |
| 531 | |
| 532 | ## Register a durable callback |
| 533 | |
| 534 | Register the handler in the **inner, per-instance Effect**, before |
| 535 | returning the public methods: |
| 536 | |
| 537 | ```diff lang="typescript" |
| 538 | // src/document.ts |
| 539 | +import * as Alchemy from "alchemy"; |
| 540 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 541 | import * as Effect from "effect/Effect"; |
| 542 | |
| 543 | // Inside Document's outer Effect: |
| 544 | const state = yield* Cloudflare.DurableObjectState; |
| 545 | return Effect.gen(function* () { |
| 546 | + const onSnapshot = yield* Alchemy.makeCallback( |
| 547 | + "snapshot", |
| 548 | + Effect.fn(function* (payload: { revision: string; body: string }) { |
| 549 | + yield* state.storage.put(`revisions:${payload.revision}`, payload.body); |
| 550 | + }), |
| 551 | + ); |
| 552 | return {}; |
| 553 | }); |
| 554 | ``` |
| 555 | |
| 556 | `onSnapshot` is a typed scheduling handle, not an RPC method. Alchemy |
| 557 | re-registers its handler whenever the instance is reconstructed. The |
| 558 | public API is `Alchemy.makeCallback`; Cloudflare Durable Objects are its |
| 559 | first supported host. Registration in a Worker, in the outer Construction |
| 560 | Effect, or later inside an RPC method is unsupported. |
| 561 | |
| 562 | Payloads must be JSON values: objects, arrays, strings, finite numbers, |
| 563 | booleans, or `null`. Values such as `Date`, `undefined`, and `BigInt` are |
| 564 | rejected when scheduling, even if the handler's TypeScript type accepts |
| 565 | them. Encode dates as strings or timestamps before scheduling. |
| 566 | |
| 567 | ## Save and schedule atomically |
| 568 | |
| 569 | Add a method that writes the document and schedules its snapshot in the |
| 570 | same storage transaction: |
| 571 | |
| 572 | ```diff lang="typescript" |
| 573 | -return {}; |
| 574 | +return { |
| 575 | + save: Effect.fn(function* (revision: string, body: string) { |
| 576 | + yield* state.storage.transaction( |
| 577 | + Effect.gen(function* () { |
| 578 | + yield* state.storage.put("document", { revision, body }); |
| 579 | + yield* onSnapshot.schedule(revision, { |
| 580 | + after: "30 seconds", |
| 581 | + payload: { revision, body }, |
| 582 | + }); |
| 583 | + }), |
| 584 | + ); |
| 585 | + }), |
| 586 | +}; |
| 587 | ``` |
| 588 | |
| 589 | The application write, pending callback, and native alarm update commit |
| 590 | or roll back together. This works for SQLite and key/value writes on the |
| 591 | **same Durable Object**. The handler runs later; external HTTP calls, |
| 592 | R2 writes, and other objects' storage are outside this transaction. |
| 593 | |
| 594 | The existing `storage.transaction((txn) => effect)` overload remains |
| 595 | supported. Nested transactions on the same fiber join the active |
| 596 | transaction rather than create a savepoint. Keep transactional operations |
| 597 | on that fiber: sibling-fiber storage access is rejected, as are further |
| 598 | writes after `txn.rollback()`. Storage rollback does not undo assignments |
| 599 | to JavaScript variables. |
| 600 | |
| 601 | ## Replace a pending callback |
| 602 | |
| 603 | Within the same instance, the callback name and job ID identify a pending |
| 604 | job. Scheduling the same pair again replaces its payload and due time. |
| 605 | Use `at` instead of `after` for an absolute time: |
| 606 | |
| 607 | ```typescript |
| 608 | // Inside a Document method; revision and body are method arguments. |
| 609 | yield* onSnapshot.schedule(revision, { |
| 610 | at: new Date("2026-12-01T09:00:00Z"), |
| 611 | payload: { revision, body }, |
| 612 | }); |
| 613 | ``` |
| 614 | |
| 615 | Pass exactly one of `at` or `after`. IDs are independent across callback |
| 616 | names and across Durable Object instances. Replacing a pending job does |
| 617 | not interrupt an invocation that is already running. |
| 618 | |
| 619 | ## Cancel a pending callback |
| 620 | |
| 621 | Cancel from existing application logic; no additional RPC method is needed: |
| 622 | |
| 623 | ```typescript |
| 624 | yield* onSnapshot.cancel(revision); |
| 625 | ``` |
| 626 | |
| 627 | Cancellation joins an active storage transaction, succeeds for absent IDs, |
| 628 | and does not interrupt a running handler. Failures use `Alchemy.CallbackError`. |
| 629 | |
| 630 | ## Retry failed callbacks |
| 631 | |
| 632 | Delivery is **at least once**, not exactly once. A failed or interrupted |
| 633 | handler leaves its job pending. The default recovery delay is 30 seconds; |
| 634 | set a finite, positive delay when registering the handler: |
| 635 | |
| 636 | ```diff lang="typescript" |
| 637 | const onSnapshot = yield* Alchemy.makeCallback( |
| 638 | "snapshot", |
| 639 | Effect.fn(function* (payload: { revision: string; body: string }) { |
| 640 | yield* state.storage.put(`revisions:${payload.revision}`, payload.body); |
| 641 | }), |
| 642 | + { retry: { delay: "10 seconds" } }, |
| 643 | ); |
| 644 | ``` |
| 645 | |
| 646 | Alchemy persists a recovery wake before invoking the handler and |
| 647 | acknowledges the job only after success. A crash between an external write |
| 648 | and acknowledgement can repeat that write, so use idempotency keys for |
| 649 | external operations. This example can repeat safely because it writes the |
| 650 | same revision key and body. Each invocation receives a fresh Effect scope. |
| 651 | Delivery times are earliest eligible times, not exact execution deadlines. |
| 652 | |
| 653 | :::caution[Keep native alarm retries enabled] |
| 654 | Automatic recovery from instance termination relies on Cloudflare's |
| 655 | native alarm retries. `state.abort(reason, { retryAlarm: false })` removes |
| 656 | that guarantee: pending jobs remain stored, but Cloudflare may suppress |
| 657 | the replacement wake until the native alarm is explicitly rearmed. |
| 658 | ::: |
| 659 | |
| 660 | ## Upgrade existing schedules |
| 661 | |
| 662 | Existing `scheduleEvent` jobs stay in `alchemy_scheduled_events`, with |
| 663 | their IDs, timestamps, repeat intervals, and JSON payloads intact. Alchemy |
| 664 | atomically adds separate callback and schema-version tables to the |
| 665 | previously unversioned database. It rejects an unsupported newer schema |
| 666 | without modifying its data. |
| 667 | |
| 668 | **Keep the existing `alarm` handler**, its `Cloudflare.processScheduledEvents` |
| 669 | call, and its application-specific dispatch for pending legacy jobs. |
| 670 | Those jobs are not converted into `makeCallback` registrations, even if |
| 671 | their payload contains a field named `callback`. Repeating legacy jobs |
| 672 | continue to repeat until explicitly cancelled. |
| 673 | |
| 674 | Legacy events and callbacks share the object's single native alarm; |
| 675 | Alchemy coordinates the earliest pending timestamp across both queues. |
| 676 | A callback-only object does not need an `alarm` handler. Avoid manually |
| 677 | setting or deleting the native alarm while either scheduler owns pending |
| 678 | work. |
| 679 | |
| 680 | Callback names and payload formats are also persisted contracts. Keep |
| 681 | old registrations while their jobs are pending, and keep new handlers |
| 682 | compatible with old JSON payloads. Unknown callback names remain pending; |
| 683 | renaming a handler does not migrate those jobs. TypeScript payload types |
| 684 | do not validate data stored by an earlier deployment, so decode evolving |
| 685 | payloads explicitly with a schema when needed. |
| 686 | |
| 687 | ## Adopt a Worker deployed by Wrangler |
| 688 | |
| 689 | Alchemy deploys Durable Object classes with Cloudflare's declarative |
| 690 | [`exports`](https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/) |
| 691 | map, the same flow Wrangler uses since 4.107. An |
| 692 | [adopted](/infrastructure-as-code/resource-lifecycle#adoption) Worker |
| 693 | keeps every namespace it already has, with its data and storage backend: |
| 694 | |
| 695 | ```typescript |
| 696 | const worker = yield* Cloudflare.Worker("Api", { |
| 697 | name: "my-existing-worker", |
| 698 | main: "./src/worker.ts", |
| 699 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 700 | }).pipe(adopt(true)); |
| 701 | ``` |
| 702 | |
| 703 | A namespace whose class is no longer exported by your code stops the |
| 704 | deploy instead of being deleted. Export the class again to keep it. |
| 705 | |
| 706 | :::caution |
| 707 | Cloudflare doesn't allow a Worker to go back to the older `migrations` |
| 708 | flow once it has deployed with `exports`. Alchemy releases from before |
| 709 | this change can no longer deploy a Worker after its first deploy with a |
| 710 | newer release. |
| 711 | ::: |
| 712 | |
| 713 | ## Run containers |
| 714 | |
| 715 | A Durable Object can start a container. Declare one Container per image |
| 716 | with `schedulingPolicy: "durable_object"`, and bind each one the Durable |
| 717 | Object can run. |
| 718 | |
| 719 | An Effect-native Durable Object `yield*`s its Containers: |
| 720 | |
| 721 | ```typescript |
| 722 | export class Agent extends Cloudflare.DurableObject<Agent>()( |
| 723 | "Agent", |
| 724 | Effect.gen(function* () { |
| 725 | const node = yield* Node; |
| 726 | const python = yield* Python; |
| 727 | return Effect.succeed({ |
| 728 | start: () => node.start({ enableInternet: false }), |
| 729 | }); |
| 730 | }), |
| 731 | ) {} |
| 732 | ``` |
| 733 | |
| 734 | An async Worker lists them on the Durable Object binding: |
| 735 | |
| 736 | ```typescript |
| 737 | env: { |
| 738 | AGENT: Cloudflare.DurableObject("Agent", { containers: [Node, Python] }), |
| 739 | } |
| 740 | ``` |
| 741 | |
| 742 | An object runs one container at a time. See |
| 743 | [Several images in one Durable Object](/cloudflare/compute/containers#several-images-in-one-durable-object) |
| 744 | and [on an async Worker](/cloudflare/compute/containers#several-images-on-an-async-worker). |
| 745 | |
| 746 | ## Where next |
| 747 | |
| 748 | Guides that build on Durable Objects: |
| 749 | |
| 750 | - [Accept WebSockets](/cloudflare/compute/hibernatable-websockets) — |
| 751 | WebSocket connections that survive hibernation. |
| 752 | - [Code updates](/cloudflare/compute/code-updates) — when running |
| 753 | objects pick up new code after a deploy, and how to test it. |
| 754 | - [Bind to another Worker's Durable Object](/cloudflare/compute/cross-worker-durable-object) |
| 755 | — one Worker hosts the DO, others get a typed stub; also covers |
| 756 | moving the host to a different Worker with the data intact. |
| 757 | - [Run a Container](/cloudflare/compute/run-a-container) — a long-lived |
| 758 | container managed by a DO. |
| 759 | - [Workflows](/cloudflare/compute/workflows) — durable multi-step |
| 760 | orchestration. |
| 761 | |
| 762 | Related: |
| 763 | |
| 764 | - [Workers](/cloudflare/compute/workers) — the runtime every DO is reached |
| 765 | through. |
| 766 | - [Drizzle migrations](/sql/drizzle/migrations#durable-object-migrations) — |
| 767 | run drizzle-kit's `durable-sqlite` migrations inside the object in the constructor. |
| 768 | |
| 769 | Reference: |
| 770 | |
| 771 | - [DurableObject API reference](/providers/cloudflare/workers/durableobject) |