workflow 5.2.3 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/internal/errors.d.ts +1 -1
  5. package/dist/internal/errors.d.ts.map +1 -1
  6. package/dist/internal/errors.js +2 -2
  7. package/docs/api-reference/workflow/create-hook.mdx +8 -0
  8. package/docs/api-reference/workflow/fetch.mdx +6 -0
  9. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +5 -1
  10. package/docs/api-reference/workflow-api/get-run.mdx +4 -0
  11. package/docs/api-reference/workflow-api/resume-hook.mdx +58 -2
  12. package/docs/api-reference/workflow-api/start.mdx +64 -1
  13. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +6 -3
  14. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +68 -0
  15. package/docs/api-reference/workflow-errors/index.mdx +6 -0
  16. package/docs/api-reference/workflow-errors/meta.json +2 -0
  17. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +2 -0
  18. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +58 -0
  19. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +12 -1
  20. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  21. package/docs/changelog/eager-processing.mdx +2 -0
  22. package/docs/changelog/index.mdx +1 -0
  23. package/docs/changelog/lazy-event-creation.md +1 -1
  24. package/docs/changelog/meta.json +1 -0
  25. package/docs/changelog/spec-9.mdx +4019 -0
  26. package/docs/changelog/turbo-mode.md +4 -0
  27. package/docs/configuration/runtime-tuning.mdx +61 -2
  28. package/docs/configuration/worlds.mdx +12 -0
  29. package/docs/cookbook/advanced/child-workflows.mdx +2 -2
  30. package/docs/cookbook/common-patterns/batching.mdx +3 -1
  31. package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
  32. package/docs/errors/fetch-in-workflow.mdx +7 -1
  33. package/docs/foundations/errors-and-retries.mdx +6 -0
  34. package/docs/foundations/hooks.mdx +3 -1
  35. package/docs/foundations/idempotency.mdx +190 -60
  36. package/docs/how-it-works/event-sourcing.mdx +6 -0
  37. package/docs/whats-new.mdx +3 -1
  38. package/docs/worlds/building-a-world.mdx +28 -3
  39. package/docs/worlds/local.mdx +6 -0
  40. package/docs/worlds/postgres.mdx +211 -145
  41. package/docs/worlds/upgrading-to-v5.mdx +7 -1
  42. package/docs/worlds/vercel.mdx +11 -5
  43. package/package.json +11 -11
@@ -179,6 +179,8 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
179
179
 
180
180
  - **`start()` from inside a workflow.** Spawn a child run or hand off to a new run directly in a workflow function, without wrapping it in a step. See [Starting workflows](/docs/foundations/starting-workflows).
181
181
  - **Hook token takeover.** Pass `experimental_force: true` to [`createHook()`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds) when the newest run should own a token another run still holds. The previous owner is woken and its `await hook` rejects with [`HookForceClaimedError`](/docs/api-reference/workflow-errors/hook-force-claimed-error), while `resumeHook()` callers, including one already in flight, are routed to the new owner without noticing. Supported by all three first-party Worlds.
182
+ - **Idempotent starts.** Pass `hook: { token }` to [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) to admit at most one run per token. A duplicate throws `HookConflictError` naming the owner and never becomes a run, and the owner's start Hook can be resumed right away. See [Run idempotency](/docs/foundations/idempotency#start-a-run-once-per-key).
183
+ - **Resume a stored Hook without another lookup.** Pass the `Hook` returned by `getHookByToken()` or `resumeHook()` back to [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook#reuse-a-resolved-hook) instead of its token, and later deliveries skip the token lookup. The Hook survives JSON serialization, so you can keep it with your server-side session state. Supported on the Vercel World.
182
184
  - **Stronger hook coordination.** `hook.getConflict()` resolves with the conflicting [`Run`](/docs/api-reference/workflow-api/get-run) rather than a bare `{ runId }`, so a duplicate can `await conflict.status`, `await conflict.returnValue`, or `await conflict.cancel()` directly. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
183
185
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
184
186
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
@@ -199,7 +201,7 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
199
201
  | `hook.getConflict()` resolves with a `Run` | Replace `conflict.runId` round trips through `getRun()` inside a step with the accessors on `conflict` directly. `conflict.runId` still works. |
200
202
  | `hook.metadata` is a Promise on hooks returned by `getHookByToken()` and `resumeHook()` | Write `await hook.metadata` where you read it. Hydrating metadata can add network round trips, and those are now paid only by code that reads it, so the lookup itself is a single read. The `Hook` type is exported from `workflow/api`; the World-level record from `world.hooks.getByToken()` is unchanged. See [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token). |
201
203
  | `experimental_setAttributes` removed | Import `setAttributes` instead, and `SetAttributesOptions` in place of `ExperimentalSetAttributesOptions`. The deprecated aliases are gone. |
202
- | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#starting-the-world). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
204
+ | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#start-the-world-when-your-server-starts). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
203
205
  | Duplicate step or workflow IDs fail the build | 4.x resolved collisions across non-exported workspace files last-write-wins. If you start encountering build failures after upgrading, rename the colliding functions. |
204
206
  | The generated bundles are renamed, and the step route is gone | Only affects apps that wire the output of `workflow build` into their own server instead of using a framework integration. `flow.js` and `webhook.js` are now `flow.mjs` and `webhook.mjs` with named exports only, so a default import resolves to `undefined`. `step.js` became `__step_registrations.mjs`, an internal module that `flow.mjs` imports: delete the `POST /.well-known/workflow/v1/step` route rather than repointing it, because the flow handler now serves step deliveries too. See [Framework integrations](/docs/how-it-works/framework-integrations). |
205
207
  | Default trace mode is `linked` | Update dashboards that assume one trace per run, or set `WORKFLOW_TRACE_MODE=continuous`. |
@@ -41,6 +41,9 @@ interface WorldCapabilities {
41
41
  hookRetention?: {
42
42
  active: boolean;
43
43
  };
44
+ atomicStartHook?: {
45
+ active: boolean;
46
+ };
44
47
  maxConcurrency?: boolean;
45
48
  inBandFence?: boolean;
46
49
  hookForceClaim?: boolean;
@@ -64,7 +67,7 @@ interface World extends Storage, Queue, Streamer {
64
67
 
65
68
  `specVersion` is required. See [Declaring the spec version](#declaring-the-spec-version).
66
69
 
67
- The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence).
70
+ The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({ hook })` throws before it enqueues anything.
68
71
 
69
72
  [Slot-numbered event IDs](#event-id-allocation) are a contract requirement rather than a capability, so there is no flag or fallback path.
70
73
 
@@ -225,7 +228,7 @@ Two properties have to hold, and both are about what a reader can conclude from
225
228
  - **Uniqueness.** Two writers racing to append must not both take a position. Settle it where the store settles it, with a unique constraint on `(runId, eventId)` or a conditional write, rather than reading the maximum and adding one in your own process.
226
229
  - **Density.** Positions run from 1 with no holes, which is what lets a reader tell a complete log from a truncated one by its length alone. A writer that loses a race must re-derive its position from the store and take the next free one. Incrementing a local number after a loss leaves a permanent hole, and the runtime treats a hole as a log it cannot safely replay across.
227
230
 
228
- Allocate the position **at the commit** in the same operation that appends the event. This makes a reader's log a *prefix* of the run's log rather than a prefix with a hole. Nothing can land behind a position that a reader has passed. Assigning a position earlier, such as in a request handler, and committing later breaks the property that every replay depends on. This is the one case where you may need [a stale-write rejection](#optional-rejecting-a-stale-write) to compensate.
231
+ Allocate the position **at the commit** in the same operation that appends the event. This makes a reader's log a *prefix* of the run's log rather than a prefix with a hole. Nothing can land behind a position that a reader has passed. Assigning a position earlier, such as in a request handler, and committing later breaks the property that every replay depends on, unless you seal abandoned positions as described below. This is the one case where you may need [a stale-write rejection](#optional-rejecting-a-stale-write) to compensate.
229
232
 
230
233
  #### Optional: pre-assigned positions and `noop` sealing
231
234
 
@@ -270,7 +273,7 @@ The runtime handles a rejection wherever it arrives. It restarts the replay in-p
270
273
 
271
274
  The in-band writer fence keeps a run to one orchestrator writer when two orchestrator invocations of the same run overlap, for example a delivery that outlives its queue lease while a redelivery of the run is already running. A write made by the run's orchestrator is **in-band** (`params.inBand: true`). Everything else is **out-of-band**: a background step's own events, `hook_received` from `resumeHook()` and webhooks, `run_cancelled` from `cancel()`, and `attr_set` from `setAttributes()` outside the workflow.
272
275
 
273
- The fence is optional, and the runtime does not send `inBand` yet, so a World without it stays fully supported. Declare `capabilities.inBandFence: true` when you implement all of the following:
276
+ The fence is optional. The runtime sends `inBand` only on runs of the experimental spec 9 runtime, so a World without the fence stays fully supported and keeps creating spec 8 runs. Declare `capabilities.inBandFence: true` when you implement all of the following:
274
277
 
275
278
  - **Two counters per run.** Next to whatever allocates event positions, keep `seq`, the highest position allocated to any write, and `seqInBand`, the number of positions allocated to in-band writes. `run_created` counts as in-band and is never fenced itself, so a new run holds `seq = 1, seqInBand = 1` (`IN_BAND_SEQ_AT_RUN_CREATION` from `@workflow/world`).
276
279
  - **List snapshot, or counters on a refusal.** On every `events.list()` page of a slot-numbered run, return `snapshot: { seq, seqInBand }`, read before the listing. A full load, followed to `hasMore: false`, covers every position up to the first page's `seq`. A fenced writer takes its count from that first page, never from counting events, because a count cannot tell which positions were in-band. If your store cannot read the counters on a list, you may list no snapshot, as long as every refusal carries both counters, read together (see below).
@@ -291,6 +294,24 @@ A writer that was refused while writing stops writing from the log it held; only
291
294
 
292
295
  The conformance suite in [`packages/world/src/test-support/in-band-fence-conformance.ts`](https://github.com/vercel/workflow/blob/main/packages/world/src/test-support/in-band-fence-conformance.ts) checks each rule against a World's `events` storage, and `createTestSuite()` from `@workflow/world-testing` checks the counters (from the snapshot, or from a refusal where the World lists none) and a stale in-band write end to end when the World declares the capability.
293
296
 
297
+ ### Optional: atomic start Hook admission
298
+
299
+ [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) makes a start idempotent on a Hook token, and gives the run a **start Hook** that can be resumed from the moment the run is admitted. `start()` enqueues the candidate run first and then writes `run_created`; the queue consumer's `run_started` carries the same request in `eventData.startHook`, and either write may reach the World first. Declare `capabilities.atomicStartHook: { active: true }` when `events.create()` implements all of the following for a `run_created`, or a `run_started` that creates the run, carrying `eventData.startHook = { token, tokenRetentionUntil?, metadata? }`:
300
+
301
+ - **Atomic admission.** Claim the token, record the decision, and create the start Hook as one atomic step. A run must never exist for a candidate that was refused, and a crash partway through must be recoverable by retrying the candidate.
302
+ - **One immutable decision per candidate `runId`.** Every later attempt for the same `runId`, through either write, returns the first decision even if the token has since changed hands: an accepted candidate returns its run (never `EntityConflictError`), and a refused one throws `HookConflictError` with the same `conflictingRunId`.
303
+ - **The start Hook exists from admission.** Its id is `startHookId(runId)` from `@workflow/world`, and it is an ordinary Hook record with the start's `token`, `metadata` and `tokenRetentionUntil`, and `isWebhook: false`. `hooks.getByToken()` and `hooks.get()` return it as soon as admission is durable. `run_created` stands for its `hook_created`: never write a `hook_created` for it, and refuse a `hook_created` whose `correlationId` is `startHookId(runId)` with a 400-class validation error.
304
+ - **Echo.** The run returned from `run_created`, `run_started` and `runs.get` carries `startHook`, including its `hookId`. Keep `token`, `hookId` and `tokenRetentionUntil` in the `run_created` event's `eventData.startHook` (you may drop `metadata` there): the runtime binds the workflow's `createHook({ token })` to the start Hook from it on every replay.
305
+ - **Deliveries to a pending run.** Accept `hook_received` for `startHookId(runId)` while the run is `pending` or `running` (ordinary Hooks stay running-only), and wake the run as for any resume. Never commit a delivery before the run's `run_created` event. If your World admits the run in more than one write and the run doesn't exist yet when a delivery arrives, wait briefly, then answer a retryable error with a `retryAfter` rather than not found.
306
+ - **Ordinary lifecycle.** From then on the start Hook behaves like a Hook the run created. Another run's `start({ hook })` or `createHook()` with the token conflicts, naming the owner. `hook_disposed` for the start Hook frees the token at once, even when `tokenRetentionUntil` is set, and a later `createHook({ token })` in the run is an ordinary `hook_created`. At run end, release the Hook as for any other, or, with `tokenRetentionUntil`, keep it findable by `hooks.getByToken()` but refuse deliveries until that time.
307
+ - **Force claims.** A forced `createHook()` takes the start Hook like any other, including before the owning workflow opens it, and writes `hook_disposed` with `forceClaimedBy` for `startHookId(runId)` to the owner's log. If the owner's run does not exist yet and can still be created, answer a retryable refusal instead.
308
+ - **Orphans.** A candidate that was admitted but whose run was never created must not hold the token forever. A candidate older than `START_HOOK_CANDIDATE_MAX_AGE_MS` (the same bound `run_created` applies to client-minted run IDs) can never be created. While it can still be created, never release its token, and treat deliveries as for a pending run that doesn't exist yet. Once it can't, or once it is fenced, release the token and answer not found.
309
+ - **Permanent refusals.** A request you will never admit (an invalid retention, a candidate past the orphan bound) throws `WorkflowWorldError` with `code: START_HOOK_ADMISSION_REJECTED`, so the queued copy stops retrying. Every copy of the candidate must get the same answer. Set its `reason` to one of `invalid`, `expired`, `token_mismatch`, `ordinary_run` or `disabled` (`StartHookRejectionReason`), which `start()` and the queued copy record on their spans as `workflow.start_hook.rejection_reason`.
310
+ - **Cancelling an uncreated candidate.** A `run_cancelled` for a run ID with no run but an accepted decision fences the candidate (no copy can create it any more), releases its token as for an ended run, and throws `WorkflowWorldError` with `code: START_HOOK_CANDIDATE_CANCELLED`. With no decision, throw `WorkflowRunNotFoundError` as for any missing run.
311
+ - **Switching admission off.** If you can switch admission off, either record the refusal as the candidate's decision and answer `START_HOOK_ADMISSION_REJECTED`, or throw `WorkflowWorldError` with `code: START_HOOK_ADMISSION_DISABLED` and record nothing. The second is not final: `start()` reports it as `WorkflowStartError`, and the queued copy is redelivered, because another copy may be admitted once admission is back on.
312
+
313
+ `world-local` declares it; `world-postgres` declares it only with `WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK=1`, and `world-vercel` only with `WORKFLOW_VERCEL_EXPERIMENTAL_START_HOOK=1`. The conformance suite in [`packages/world/src/test-support/atomic-start-hook-conformance.ts`](https://github.com/vercel/workflow/blob/main/packages/world/src/test-support/atomic-start-hook-conformance.ts) checks these rules against a World's storage.
314
+
294
315
  ## Queue interface
295
316
 
296
317
  The Queue interface handles asynchronous workflow execution, including queued step work:
@@ -680,3 +701,7 @@ Your World will then appear on the [Worlds ecosystem](/worlds) page with its com
680
701
  "docs": "https://github.com/you/your-world#readme"
681
702
  }
682
703
  ```
704
+
705
+ ## Supporting spec 9 runs (experimental)
706
+
707
+ Everything above is the contract for spec 8 runs, which every World needs. A World may also let its users opt in to the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=9`). To do so it implements the [in-band writer fence](#optional-the-in-band-writer-fence), serializes each spec 9 run's orchestrator deliveries, follows the spec 9 queue and deduplication rules, declares `capabilities.inBandFence: true`, and passes it on as `mintedSpecVersion(process.env, { inBandFence: true })`. `mintedSpecVersion()` called with no options never returns 9, so a World that does none of this keeps creating spec 8 runs. See [Implementing spec 9 in a World](/docs/changelog/spec-9#implementing-spec-9-in-a-world) and [World contract changes](/docs/changelog/spec-9#world-contract-changes).
@@ -86,6 +86,12 @@ Whether queue deliveries go out through Node's built-in `node:http` and `node:ht
86
86
 
87
87
  Whether pending and running runs found in the data directory are re-enqueued when the World starts. Set to `0` or `false` to skip recovery and leave stale runs untouched. Default: `true`.
88
88
 
89
+ Recovery also hands back to the queue any step that was running inline when the previous process exited. The step runs again right away instead of after the inline-ownership lease (about 14 minutes), and the interrupted attempt counts toward its retries. A step with `maxRetries: 0` that was interrupted mid-body therefore fails on restart with an "exceeded max retries" error instead of running again once the lease expires, as it already does after a crash on the Vercel World.
90
+
91
+ If you turn recovery off and re-enqueue runs yourself, call `releaseOrphanedSteps(runId)` before re-enqueueing each run. It is a method of `LocalWorld`, the type `createWorld()` from `@workflow/world-local` returns. The `World` type that `getWorld()` returns does not declare it, so a caller holding a `World` needs the `LocalWorld` type to call it.
92
+
93
+ A step counts as abandoned only if it started before the Local World loaded in the current process or worker thread. Steps started since then are never released, so runs this process picks up during or after recovery are not affected, and calling `releaseOrphanedSteps()` late is safe. Recovery assumes that nothing else is running workflows on the same data directory and `tag`. That includes an earlier worker thread of the same process: some dev servers reload into a new worker thread, and until the old one stops, the new one may dispatch a step the old one is still running, so the step can run twice. If several processes or workers run workflows on one data directory, turn recovery off or give each one its own `tag`.
94
+
89
95
  ### `WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS`
90
96
 
91
97
  Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Local World, in days. Default: `30`. Set this to the same limit as your production World so oversized values fail during local development.
@@ -21,32 +21,59 @@ Use the Postgres World to deploy workflows on your own infrastructure outside Ve
21
21
  routes. For production use-cases we recommend cloning it and adapting it to
22
22
  your persistence, network stack, scale, and security requirements. If you
23
23
  deploy it as is, you must restrict those routes yourself. Read
24
- [Security](#security) first.
24
+ [Security](#security) before you expose the app.
25
25
  </Callout>
26
26
 
27
- ## Installation
27
+ ## Quickstart
28
28
 
29
- Install the Postgres World package in your workflow project:
29
+ These steps take an existing workflow app (see [Getting Started](/docs/getting-started)) from the Local World to the Postgres World. Everything after this section is for production and tuning, and none of it is needed to get a first run going.
30
+
31
+ <Steps>
32
+
33
+ <Step>
34
+
35
+ ### Start a PostgreSQL database
36
+
37
+ Any PostgreSQL database works, self-hosted or managed. For local development, this container matches the World's default connection string, `postgres://world:world@localhost:5432/world`:
38
+
39
+ ```bash
40
+ docker run -d --name workflow-postgres -p 127.0.0.1:5432:5432 \
41
+ -e POSTGRES_USER=world -e POSTGRES_PASSWORD=world -e POSTGRES_DB=world \
42
+ postgres:18-alpine
43
+ ```
44
+
45
+ </Step>
46
+
47
+ <Step>
48
+
49
+ ### Install the package
30
50
 
31
51
  ```package-install
32
52
  @workflow/world-postgres
33
53
  ```
34
54
 
35
- <Callout type="info">
36
- Keep `workflow` and `@workflow/world-postgres` on the same major version and release
37
- cycle. If your app uses a prerelease Workflow version, install the matching prerelease Postgres
38
- World package. Mismatched versions fail before starting a run with an error that names the
39
- spec versions the runtime supports and the one the World declares.
40
- </Callout>
55
+ Keep `workflow` and `@workflow/world-postgres` on the same major version and release cycle, including prereleases. A mismatch fails before starting a run, with an error that names the spec versions the runtime supports and the one the World declares.
41
56
 
42
- Configure the required environment variables to use the world and point it to your PostgreSQL database:
57
+ </Step>
58
+
59
+ <Step>
60
+
61
+ ### Point your app at the World
43
62
 
44
63
  ```bash title=".env"
45
64
  WORKFLOW_TARGET_WORLD="@workflow/world-postgres"
46
- WORKFLOW_POSTGRES_URL="postgres://user:password@host:5432/database"
65
+ WORKFLOW_POSTGRES_URL="postgres://world:world@localhost:5432/world"
47
66
  ```
48
67
 
49
- Run the migration script to create the necessary tables in your database. Ensure `WORKFLOW_POSTGRES_URL` or `DATABASE_URL` is set when running this command:
68
+ `WORKFLOW_POSTGRES_URL` falls back to `DATABASE_URL`, then to the default above. See [Configuration](#configuration) for everything else you can set.
69
+
70
+ </Step>
71
+
72
+ <Step>
73
+
74
+ ### Create the tables
75
+
76
+ Run the migrations against the same database. The command reads `WORKFLOW_POSTGRES_URL` or `DATABASE_URL`:
50
77
 
51
78
  ```bash tab="npm"
52
79
  npx --package=@workflow/world-postgres bootstrap
@@ -64,93 +91,15 @@ yarn dlx --package @workflow/world-postgres bootstrap
64
91
  bunx --package @workflow/world-postgres bootstrap
65
92
  ```
66
93
 
67
- <Callout type="info">
68
- The migration is idempotent and can safely be run as a post-deployment lifecycle script. Run it again when you upgrade `@workflow/world-postgres`: a release can add migrations that the upgraded World needs before it handles workflows.
69
- </Callout>
70
-
71
- <Callout type="warn">
72
- Migration 0027 converts every timestamp column to `timestamp with time zone`.
73
- On a server whose time zone is UTC (the default on most hosted providers) it
74
- only changes the catalog and rebuilds one small index, and the upgrade order
75
- does not matter. On a server in another time zone it also rewrites each
76
- `created_at` value from local time to the instant it recorded, about one
77
- rewrite of each table, holding the tables' locks until it finishes. There, stop
78
- the previous version's workers, run `bootstrap`, then start the upgraded app:
79
- older versions read the converted columns shifted by the server's UTC offset,
80
- so you cannot roll back past this migration either. If your app's connection
81
- pool set a session time zone other than the server's, pass it to the migration
82
- with `?options=-c%20workflow.legacy_timezone%3DEurope%2FBerlin` in the
83
- connection string, or with `ALTER DATABASE ... SET workflow.legacy_timezone =
84
- 'Europe/Berlin'` where your pooler drops startup `options`. The migration waits
85
- at most 10 seconds for its locks; if a long transaction holds them,
86
- `bootstrap` fails and can be run again.
87
- </Callout>
94
+ The command is idempotent, so you can run it on every deploy.
88
95
 
89
- ## Starting the World
96
+ </Step>
90
97
 
91
- ### Experimental invocation delivery
98
+ <Step>
92
99
 
93
- Set `WORKFLOW_POSTGRES_INVOKE=1`, or pass `enableInvoke: true` to the Postgres
94
- World's factory, to send hook inputs to the run's executor and wait for its
95
- response. Invocation is off by default. Apply the migrations and upgrade
96
- producers and workers together before enabling it.
97
-
98
- The executor validates the hook input and writes its event before responding.
99
- Workflow user code can consume the event later. The World stores inputs and
100
- responses in `workflow.workflow_invocations`. Inserting an input and enqueueing
101
- a workflow execution job share one transaction. Retries also enqueue an execution
102
- job, including when a retained response already exists, so committed events can
103
- be replayed after a runner failure.
104
-
105
- With the default job prefix, Graphile uses `workflow_flows_executor` for workflow
106
- execution and `workflow_flows` for step jobs and health checks. Execution jobs
107
- use a named queue per run, `workflow_flows:<runId>:executor`. Graphile permits
108
- one active job on each named queue across workers. Other runs, steps, and health
109
- checks can run concurrently. `queueConcurrency` limits total active jobs per
110
- worker process and defaults to 50. A custom job prefix replaces `workflow_` in
111
- these names.
112
-
113
- The HTTP receiver checks each execution request against its active Graphile job
114
- before processing pending inputs. Updated workers and receivers move legacy
115
- orchestration requests to the run's named queue. Before acknowledging an execution
116
- job, the World finishes any input already being processed and replays newly
117
- committed events. These entry checks do not stop an old handler from writing
118
- after its job is reclaimed.
119
-
120
- The caller receives a stored return value or a restored Workflow error. Terminal
121
- errors are retained as outcomes; transient or unrecognized failures leave inputs
122
- pending for Graphile to retry. Migration 0022 preserves the meaning of responses
123
- stored by earlier previews. Failure to store or read a response leaves the
124
- processing outcome unknown. Durable resume identities deduplicate the hook event
125
- when response storage must be retried.
126
-
127
- A shared `LISTEN/NOTIFY` connection signals changes to pending inputs and
128
- responses. Notifications contain identifiers, and readers fetch data from the
129
- table. Use a session-capable connection for `LISTEN`. Readers fall back to polling
130
- at 1s intervals if notifications fail, and connection retries use a 1s backoff.
131
- Notification failure and recovery are logged once per transition without
132
- payloads or connection details.
133
-
134
- The response-wait timeout defaults to 30s and can be set with `timeoutMs`. Encoded
135
- inputs and outcomes are limited to 1 MiB each. A timeout does not cancel
136
- processing. `$retention: 0` purges invocation data and prevents late writes from
137
- restoring it. Callers whose result has expired receive a 410 error with code
138
- `INVOCATION_DATA_EXPIRED`, even if the hook event committed earlier.
139
-
140
- Automatic cleanup of other results, stopping writes from reclaimed handlers, and
141
- routing requests across incompatible worker versions remain unimplemented.
142
-
143
- ### Server startup
144
-
145
- To subscribe to the graphile-worker queue, your workflow app needs to start the world on server start. Here are examples for a few frameworks:
100
+ ### Start the World when your server starts
146
101
 
147
- <Callout type="warn">
148
- This step is specific to worlds that run a background worker, such as Postgres
149
- World. Worlds whose queue delivers work over HTTP, including the Vercel World,
150
- have no worker to subscribe, so `start()` does nothing there while the import
151
- still adds overhead. Pulling in `workflow/runtime` from a server-startup hook puts
152
- the whole runtime into the cold-start path before the first request is served.
153
- </Callout>
102
+ The Postgres World runs a background worker that pulls jobs from graphile-worker, so your app has to start it once when the server boots:
154
103
 
155
104
  <TabsWithChildren tabs={["Next.js","SvelteKit","Nitro"]}>
156
105
 
@@ -228,9 +177,83 @@ Learn more about [Nitro Plugins](https://v3.nitro.build/docs/plugins).
228
177
  </TabsWithChildren>
229
178
 
230
179
  <Callout type="info">
231
- The Postgres World requires a long-lived worker process that polls the database for jobs. This does not work on serverless environments. For Vercel deployments, use the [Vercel World](/worlds/vercel) instead.
180
+ Only Worlds with a background worker need this hook. If the same app also
181
+ deploys with the [Vercel World](/worlds/vercel), skip it there: `start()` does
182
+ nothing on that World, and importing `workflow/runtime` from a startup hook puts
183
+ the whole runtime on the cold-start path.
232
184
  </Callout>
233
185
 
186
+ </Step>
187
+
188
+ <Step>
189
+
190
+ ### Run a workflow
191
+
192
+ Start your dev server and trigger a workflow as usual. Then check that the run landed in PostgreSQL, from the terminal or in the web UI:
193
+
194
+ ```bash
195
+ # List workflow runs
196
+ npx workflow inspect runs --backend @workflow/world-postgres
197
+
198
+ # Launch the web UI
199
+ npx workflow web --backend @workflow/world-postgres
200
+ ```
201
+
202
+ </Step>
203
+
204
+ </Steps>
205
+
206
+ ## Deploying to production
207
+
208
+ The Postgres World needs a long-lived process to run its worker, so it does not work on serverless platforms. Deploy your application to any cloud that supports long-running servers:
209
+
210
+ - Docker containers
211
+ - Kubernetes clusters
212
+ - Virtual machines
213
+ - Platform-as-a-service (PaaS) providers, such as Railway, Render, and Fly.io
214
+
215
+ Before you go live, make sure that:
216
+
217
+ - The app can reach your PostgreSQL database, and `WORKFLOW_TARGET_WORLD` and `WORKFLOW_POSTGRES_URL` are set in its runtime environment
218
+ - `bootstrap` runs on every deploy, for example as a post-deployment lifecycle script (see [Upgrading](#upgrading))
219
+ - `start()` is called on server initialization
220
+ - `/.well-known/workflow/v1/flow` is restricted so untrusted clients cannot reach it (see [Security](#security))
221
+ - If more than one process shares the database, you have set [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) to the same value on every process, so another process picks up the jobs of one that dies
222
+
223
+ <Callout type="info">
224
+ The Postgres World is not compatible with Vercel deployments. On Vercel, workflows automatically use the [Vercel World](/worlds/vercel) with zero configuration.
225
+ </Callout>
226
+
227
+ ## Security
228
+
229
+ Unlike the [Vercel World](/worlds/vercel), which authenticates and [encrypts](/docs/how-it-works/encryption) workflow traffic automatically, the Postgres World does **not** automatically authenticate requests that drive workflow execution. Adding that is your responsibility and should be in place before an app using this World is used in production and reachable by untrusted clients. We also recommend [enabling encryption](/docs/how-it-works/encryption#custom-world-implementations).
230
+
231
+ ### Protect the queue route
232
+
233
+ `POST /.well-known/workflow/v1/flow` is where the worker delivers workflow orchestration and queued step invocations. It is mounted in your application like any other route, so it is publicly reachable by default, and it accepts any request whose headers and body are well-formed: there is no signature, shared secret, or caller check. Anyone who can reach it can forge or replay a workflow or step invocation, including steps your application would only reach after its own gating. Restrict it before you expose the app.
234
+
235
+ The other routes under `/.well-known/workflow/v1/` differ:
236
+
237
+ - `webhook/:token`, created by [`createWebhook()`](/docs/api-reference/workflow/create-webhook), is authorized by the token in the URL and nothing else. Use [`createHook()`](/docs/api-reference/workflow/create-hook) behind your own authenticated route and [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) when you need more than that.
238
+ - `manifest.json` responds with `404` unless the app was built with `WORKFLOW_PUBLIC_MANIFEST=1`. That variable is read at build time, so unsetting it in the runtime environment of an already-built deployment does not withdraw the manifest. Leave it unset outside of testing, because the manifest lists your workflow and step names.
239
+
240
+ A queue consumer that registered its own route with [`registerRoute()`](#queue-consumers-other-than-the-workflow-sdk) receives deliveries the same way, so protect that route like the flow route.
241
+
242
+ ### Bringing your own auth
243
+
244
+ Workflow does not prescribe an auth mechanism for self-hosted Worlds, so restrict the flow route at the network edge rather than inside the application:
245
+
246
+ - **Keep the flow route unreachable from outside.** By default the worker delivers to a loopback address (`http://localhost:{PORT}`, or `WORKFLOW_LOCAL_BASE_URL` when set), so in the common single-process topology nothing outside the container needs to reach it. Blocking external requests to `/.well-known/workflow/v1/flow` at your ingress, reverse proxy, or firewall costs you nothing, because loopback delivery never traverses that layer. Do not block the whole `/.well-known/workflow/` prefix if you use [`createWebhook()`](/docs/api-reference/workflow/create-webhook): its `webhook/:token` route sits under the same prefix and has to stay reachable by whoever calls it.
247
+ - **Authenticate at the proxy when the routes must cross hosts.** If your web tier and workers are separate deployments, require mTLS or a shared-secret header at the proxy in front of the application, and strip any client-supplied copy of that header at the edge.
248
+ - **Do not gate these paths in framework middleware.** The [Next.js setup guide](/docs/getting-started/next) tells you to exclude `/.well-known/workflow/*` from your proxy matcher, because a handler that consumes the internal request body breaks execution. Adding the paths back in order to gate them reintroduces that failure mode.
249
+ - **Do not expect the World to present a credential.** It does not sign its delivery requests or attach a secret to them, so an in-application check that requires one will reject the World's own deliveries.
250
+
251
+ ### Data at rest
252
+
253
+ The Postgres World does not currently implement `getEncryptionKeyForRun()`, so it does not participate in Workflow's [end-to-end encryption](/docs/how-it-works/encryption): workflow and step inputs and return values, hook payloads and metadata, and stream chunks are all stored in your database in readable form. A World derived from this one can opt in by implementing that one method; see [Custom World implementations](/docs/how-it-works/encryption#custom-world-implementations). Until then, protect the database, its credentials, and its backups accordingly.
254
+
255
+ The [observability UI](/docs/observability) has no authentication of its own either. If you self-host `@workflow/web` against your Postgres database, put it behind your own auth layer, because everyone who can reach it can read every run.
256
+
234
257
  ## Observability
235
258
 
236
259
  Use the Workflow CLI to inspect workflows stored in PostgreSQL:
@@ -250,13 +273,26 @@ If `WORKFLOW_POSTGRES_URL` is not set, the CLI defaults to `postgres://world:wor
250
273
 
251
274
  Learn more in the [Observability](/docs/observability) documentation.
252
275
 
253
- ## Testing & compatibility
254
-
255
- <WorldTestingPerformance worldId="postgres" />
256
-
257
276
  ## Configuration
258
277
 
259
- You can set all configuration options through environment variables or programmatically through `createWorld()`.
278
+ The defaults work for a single process on a local database, so most apps set only `WORKFLOW_TARGET_WORLD` and `WORKFLOW_POSTGRES_URL`. You can set every option through environment variables, or programmatically through `createWorld()` (see [Programmatic configuration](#programmatic-configuration)).
279
+
280
+ | Variable | Default | Controls |
281
+ | --- | --- | --- |
282
+ | [`WORKFLOW_POSTGRES_URL`](#workflow_postgres_url) | `DATABASE_URL`, then `postgres://world:world@localhost:5432/world` | Database connection |
283
+ | [`WORKFLOW_POSTGRES_JOB_PREFIX`](#workflow_postgres_job_prefix) | `workflow_` | Job name prefix, for sharing a database between apps |
284
+ | [`WORKFLOW_POSTGRES_WORKER_CONCURRENCY`](#workflow_postgres_worker_concurrency) | `50` | Concurrent jobs per process |
285
+ | [`WORKFLOW_POSTGRES_POLL_INTERVAL_MS`](#workflow_postgres_poll_interval_ms) | `500` ms | Idle job polling |
286
+ | [`WORKFLOW_POSTGRES_MAX_POOL_SIZE`](#workflow_postgres_max_pool_size) | `10` | Connection pool size |
287
+ | [`WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN`](#workflow_postgres_application_managed_shutdown) | off | Who coordinates shutdown |
288
+ | [`WORKFLOW_POSTGRES_RUN_STATUS_POLL_INTERVAL_MS`](#workflow_postgres_run_status_poll_interval_ms) | `1000` ms | Backstop for `await run.returnValue` |
289
+ | [`WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`](#workflow_postgres_headers_timeout_ms) | `0` ms (no deadline) | Hung delivery detection |
290
+ | [`WORKFLOW_POSTGRES_BODY_TIMEOUT_MS`](#workflow_postgres_body_timeout_ms) | `0` ms (no deadline) | Stalled response detection |
291
+ | [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) | `0` s (off) | Redelivery after a process dies |
292
+ | [`WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`](#workflow_postgres_hook_retention_limit_days) | `30` days | Maximum hook retention |
293
+ | [`WORKFLOW_QUEUE_NAMESPACE`](#workflow_queue_namespace) | unset | Queue topic namespace |
294
+ | [`WORKFLOW_STREAM_FLUSH_INTERVAL_MS`](#workflow_stream_flush_interval_ms) | `0` ms | Stream write batching |
295
+ | [`WORKFLOW_POSTGRES_INVOKE`](#experimental-invocation-delivery) | off | Experimental: hook resumes only |
260
296
 
261
297
  ### `WORKFLOW_POSTGRES_URL`
262
298
 
@@ -268,7 +304,12 @@ The `bootstrap` migration command uses the same precedence.
268
304
 
269
305
  ### `WORKFLOW_POSTGRES_JOB_PREFIX`
270
306
 
271
- Prefix for graphile-worker queue job names. Useful when sharing a database between multiple applications. Default: `workflow_`
307
+ Prefix for graphile-worker queue job names. Default: `workflow_`
308
+
309
+ Give each application that shares a database its own prefix. A World claims jobs only under its own prefix and stamps that prefix on every run it creates. On `start()`, it re-enqueues only the active runs stamped with its prefix, so restarting one application does not hand another application's runs to its worker. `WORKFLOW_QUEUE_NAMESPACE` does not separate applications that share a database.
310
+
311
+ Set the prefix through `WORKFLOW_POSTGRES_JOB_PREFIX` rather than only in code. The CLI and the observability UI build their World from the environment, so a run they create, such as a re-run, is stamped with the prefix they see, and only a World with that prefix runs and recovers it.
312
+
272
313
 
273
314
  ### `WORKFLOW_POSTGRES_WORKER_CONCURRENCY`
274
315
 
@@ -306,10 +347,32 @@ A delivery executes the workflow body inline, so the handler responds only once
306
347
 
307
348
  Maximum gap in milliseconds between response body chunks from the workflow handler before the delivery is failed and redelivered. Default: `0` (no deadline). The same caution as `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS` applies.
308
349
 
350
+ ### `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
351
+
352
+ Seconds a running delivery's job lock may go unrenewed before another process releases the job for redelivery. Default: `0` (off). `30` is a good value when more than one process shares the database. Programmatic option: `jobLockStaleSeconds`.
353
+
354
+ When set, a running delivery renews its lock every quarter of this window, and at least every 10 seconds. When a process dies mid-delivery, another process redelivers its jobs within about one and a half windows (about 45 seconds at `30`), instead of after Graphile Worker's fixed 4 hour stale-lock reset or the next restart.
355
+
356
+ Use the same value on every process that shares the database, and keep it well above the longest a process can go without running its timers (synchronous work that blocks the event loop) or getting a pool connection. A delivery whose renewals stall past the window is redelivered while it still runs.
357
+
358
+ It's off by default because of rolling upgrades. A process on an earlier version doesn't renew its locks, so a process that has this on would redeliver any of that process's deliveries that run longer than the window. When the earlier-version process then finishes such a delivery, its acknowledgement, which isn't fenced on the lock holder, can delete the redelivered job's row, and the redelivery loses its retry.
359
+
360
+ To turn it on, set `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS=30` (or `jobLockStaleSeconds: 30`) on every process that shares the database, once all of them run a version that includes this option.
361
+
309
362
  ### `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`
310
363
 
311
364
  Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Postgres World, in days. Default: `30`. Set this to the same limit as your production World so oversized values fail during development.
312
365
 
366
+ ### `WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK`
367
+
368
+ Set to `1` (or `true`) to enable [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) on the Postgres World. Off by default; without it, `start({ hook })` throws before it enqueues anything.
369
+
370
+ Stop workers running a previous version before you turn it on. The queue does not route by deployment, so an older worker that picks up a candidate's queued message would create its run without the start Hook, and the start would no longer be idempotent (`start()` reports that the World did not confirm the start Hook). An older runtime replaying a start Hook run can't bind the workflow's `createHook({ token })` to the start Hook either.
371
+
372
+ For the same reason, don't roll back past migration `0028_add_start_hook_admissions` while start Hooks are live.
373
+
374
+ Migration `0028_add_start_hook_admissions` is required even with this variable unset, because every Hook insert writes its `claims_token` column. It takes table locks on `workflow_hooks` and then `workflow_runs` (building the new unique index scans `workflow_hooks` first), and gives up after 10 seconds (unless the session sets its own `lock_timeout`), leaving the migration to retry, rather than stall traffic. Apply it with the rest of the migrations before deploying this version.
375
+
313
376
  ### `WORKFLOW_QUEUE_NAMESPACE`
314
377
 
315
378
  Queue topic namespace shared by build output and the Postgres World. Default: unset.
@@ -320,6 +383,32 @@ For example, `custom` changes the queue topic prefix from `__wkf_workflow_` to `
320
383
 
321
384
  Group-commit window, in milliseconds, for the leading chunk of an idle stream. Default: `0` (dispatch immediately). A positive value holds the first chunk up to that long to collect a group, trading first-chunk latency for fewer requests. Chunks arriving while a request is in flight always coalesce into the next group regardless.
322
385
 
386
+ ## Upgrading
387
+
388
+ Run `bootstrap` again whenever you upgrade `@workflow/world-postgres`: a release can add migrations that the upgraded World needs before it handles workflows. Upgrade `workflow` alongside it so both stay on the same release cycle.
389
+
390
+ <Callout type="warn">
391
+ Migration 0027 converts every timestamp column to `timestamp with time zone`.
392
+ On a server whose time zone is UTC (the default on most hosted providers) it
393
+ only changes the catalog and rebuilds one small index, and the upgrade order
394
+ does not matter. On a server in another time zone it also rewrites each
395
+ `created_at` value from local time to the instant it recorded, about one
396
+ rewrite of each table, holding the tables' locks until it finishes. There, stop
397
+ the previous version's workers, run `bootstrap`, then start the upgraded app:
398
+ older versions read the converted columns shifted by the server's UTC offset,
399
+ so you cannot roll back past this migration either. If your app's connection
400
+ pool set a session time zone other than the server's, pass it to the migration
401
+ with `?options=-c%20workflow.legacy_timezone%3DEurope%2FBerlin` in the
402
+ connection string, or with `ALTER DATABASE ... SET workflow.legacy_timezone =
403
+ 'Europe/Berlin'` where your pooler drops startup `options`. The migration waits
404
+ at most 10 seconds for its locks; if a long transaction holds them,
405
+ `bootstrap` fails and can be run again.
406
+ </Callout>
407
+
408
+ ## Advanced
409
+
410
+ Most apps don't need anything in this section. It covers building your own World module, sharing the queue with other consumers, coordinating shutdown yourself, and an experimental delivery mode.
411
+
323
412
  ### Programmatic configuration
324
413
 
325
414
  {/*@skip-typecheck: incomplete code sample*/}
@@ -377,65 +466,42 @@ Graphile Worker responds automatically when the application is asked to shut dow
377
466
 
378
467
  Closing the world stops new queue claims and waits for active jobs. After Graphile Worker's grace period, a pending workflow HTTP request is aborted. Graphile Worker unlocks that same row through its normal failure handling. The already-claimed delivery consumes a Graphile attempt and is retried only if its attempt budget remains; a one-attempt or final-attempt job is not retried. The shutdown handler does not insert a successor row. Because a client abort does not prove the server handler stopped, workflow and step handlers must tolerate at-least-once execution.
379
468
 
380
- ## How it works
469
+ ### Experimental invocation delivery
381
470
 
382
- The Postgres World uses PostgreSQL as a durable backend:
471
+ Invocation delivery is off by default, and you don't need it to run the Postgres World.
383
472
 
384
- - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
385
- - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
386
- - **Streaming**: PostgreSQL NOTIFY/LISTEN enables real-time event distribution. If the database drops the `LISTEN` connection, the World reconnects every second and re-reads persisted chunks for open stream readers, so readers don't miss chunks written during the outage.
473
+ Normally [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) writes the hook's event itself and then enqueues the run to wake up. With invocation delivery on, `resumeHook()` instead sends the payload to the run's executor and resolves once the executor has validated the input and persisted the hook event. It covers hook resumes only for now.
387
474
 
388
- This architecture ensures workflows survive application restarts with all state reliably persisted. For implementation details, see the [source code](https://github.com/vercel/workflow/tree/main/packages/world-postgres).
475
+ To turn it on, set `WORKFLOW_POSTGRES_INVOKE=1` or pass `enableInvoke: true` to `createWorld()`. Apply the migrations and upgrade producers and workers together before enabling it.
389
476
 
390
- ## Security
477
+ Workflow user code can consume the event later. The World stores inputs and responses in `workflow.workflow_invocations`. Inserting an input and enqueueing a workflow execution job share one transaction. Retries also enqueue an execution job, including when a retained response already exists, so committed events can be replayed after a runner failure.
391
478
 
392
- Unlike the [Vercel World](/worlds/vercel), which authenticates and [encrypts](/docs/how-it-works/encryption) workflow traffic automatically, the Postgres World does **not** automatically authenticate requests that drive workflow execution. Adding that is your responsibility and should be in place before an app using this World is used in production and reachable by untrusted clients. We also recommend [enabling encryption](/docs/how-it-works/encryption#custom-world-implementations).
479
+ With the default job prefix, Graphile uses `workflow_flows_executor` for workflow execution and `workflow_flows` for step jobs and health checks. Execution jobs use a named queue per run, `workflow_flows:<runId>:executor`. Graphile permits one active job on each named queue across workers. Other runs, steps, and health checks can run concurrently. `queueConcurrency` limits total active jobs per worker process and defaults to 50. A custom job prefix replaces `workflow_` in these names.
393
480
 
394
- ### Protect the queue route
481
+ The HTTP receiver checks each execution request against its active Graphile job before processing pending inputs. Updated workers and receivers move legacy orchestration requests to the run's named queue. Before acknowledging an execution job, the World finishes any input already being processed and replays newly committed events. These entry checks do not stop an old handler from writing after its job is reclaimed.
395
482
 
396
- `POST /.well-known/workflow/v1/flow` is where the worker delivers workflow orchestration and queued step invocations. It is mounted in your application like any other route, so it is publicly reachable by default, and it accepts any request whose headers and body are well-formed: there is no signature, shared secret, or caller check. Anyone who can reach it can forge or replay a workflow or step invocation, including steps your application would only reach after its own gating. Restrict it before you expose the app.
483
+ The caller receives a stored return value or a restored Workflow error. Terminal errors are retained as outcomes; transient or unrecognized failures leave inputs pending for Graphile to retry. Migration 0022 preserves the meaning of responses stored by earlier previews. Failure to store or read a response leaves the processing outcome unknown. Durable resume identities deduplicate the hook event when response storage must be retried.
397
484
 
398
- The other routes under `/.well-known/workflow/v1/` differ:
399
-
400
- - `webhook/:token`, created by [`createWebhook()`](/docs/api-reference/workflow/create-webhook), is authorized by the token in the URL and nothing else. Use [`createHook()`](/docs/api-reference/workflow/create-hook) behind your own authenticated route and [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) when you need more than that.
401
- - `manifest.json` responds with `404` unless the app was built with `WORKFLOW_PUBLIC_MANIFEST=1`. That variable is read at build time, so unsetting it in the runtime environment of an already-built deployment does not withdraw the manifest. Leave it unset outside of testing, because the manifest lists your workflow and step names.
485
+ A shared `LISTEN/NOTIFY` connection signals changes to pending inputs and responses. Notifications contain identifiers, and readers fetch data from the table. Use a session-capable connection for `LISTEN`. Readers fall back to polling at 1s intervals if notifications fail, and connection retries use a 1s backoff. Notification failure and recovery are logged once per transition without payloads or connection details.
402
486
 
403
- A queue consumer that registered its own route with `registerRoute()` receives deliveries the same way, so protect that route like the flow route.
487
+ The response-wait timeout defaults to 30s and can be set with `timeoutMs`. Encoded inputs and outcomes are limited to 1 MiB each. A timeout does not cancel processing. `$retention: 0` purges invocation data and prevents late writes from restoring it. Callers whose result has expired receive a 410 error with code `INVOCATION_DATA_EXPIRED`, even if the hook event committed earlier.
404
488
 
405
- ### Bringing your own auth
489
+ Automatic cleanup of other results, stopping writes from reclaimed handlers, and routing requests across incompatible worker versions remain unimplemented.
406
490
 
407
- Workflow does not prescribe an auth mechanism for self-hosted Worlds, so restrict the flow route at the network edge rather than inside the application:
408
-
409
- - **Keep the flow route unreachable from outside.** By default the worker delivers to a loopback address (`http://localhost:{PORT}`, or `WORKFLOW_LOCAL_BASE_URL` when set), so in the common single-process topology nothing outside the container needs to reach it. Blocking external requests to `/.well-known/workflow/v1/flow` at your ingress, reverse proxy, or firewall costs you nothing, because loopback delivery never traverses that layer. Do not block the whole `/.well-known/workflow/` prefix if you use [`createWebhook()`](/docs/api-reference/workflow/create-webhook): its `webhook/:token` route sits under the same prefix and has to stay reachable by whoever calls it.
410
- - **Authenticate at the proxy when the routes must cross hosts.** If your web tier and workers are separate deployments, require mTLS or a shared-secret header at the proxy in front of the application, and strip any client-supplied copy of that header at the edge.
411
- - **Do not gate these paths in framework middleware.** The [Next.js setup guide](/docs/getting-started/next) tells you to exclude `/.well-known/workflow/*` from your proxy matcher, because a handler that consumes the internal request body breaks execution. Adding the paths back in order to gate them reintroduces that failure mode.
412
- - **Do not expect the World to present a credential.** It does not sign its delivery requests or attach a secret to them, so an in-application check that requires one will reject the World's own deliveries.
413
-
414
- ### Data at rest
415
-
416
- The Postgres World does not currently implement `getEncryptionKeyForRun()`, so it does not participate in Workflow's [end-to-end encryption](/docs/how-it-works/encryption): workflow and step inputs and return values, hook payloads and metadata, and stream chunks are all stored in your database in readable form. A World derived from this one can opt in by implementing that one method; see [Custom World implementations](/docs/how-it-works/encryption#custom-world-implementations). Until then, protect the database, its credentials, and its backups accordingly.
417
-
418
- The [observability UI](/docs/observability) has no authentication of its own either. If you self-host `@workflow/web` against your Postgres database, put it behind your own auth layer, because everyone who can reach it can read every run.
419
-
420
- ## Deployment
491
+ ## How it works
421
492
 
422
- Deploy your application to any cloud that supports long-running servers:
493
+ The Postgres World uses PostgreSQL as a durable backend:
423
494
 
424
- - Docker containers
425
- - Kubernetes clusters
426
- - Virtual machines
427
- - Platform-as-a-service (PaaS) providers, such as Railway, Render, and Fly.io
495
+ - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
496
+ - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
497
+ - **Crash recovery**: The next `start()` re-enqueues active runs. With [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) set, a running delivery also renews its job lock, and if its process dies, any other process redelivers the job once its lock has gone unrenewed for that many seconds.
498
+ - **Streaming**: PostgreSQL NOTIFY/LISTEN enables real-time event distribution. If the database drops the `LISTEN` connection, the World reconnects every second and re-reads persisted chunks for open stream readers, so readers don't miss chunks written during the outage.
428
499
 
429
- Ensure your deployment has:
500
+ This architecture ensures workflows survive application restarts with all state reliably persisted. For implementation details, see the [source code](https://github.com/vercel/workflow/tree/main/packages/world-postgres).
430
501
 
431
- - Network access to your PostgreSQL database
432
- - Environment variables configured correctly
433
- - The `start()` function called on server initialization
434
- - `/.well-known/workflow/v1/flow` restricted so untrusted clients cannot reach it (see [Security](#security))
502
+ ## Testing & compatibility
435
503
 
436
- <Callout type="info">
437
- The Postgres World is not compatible with Vercel deployments. On Vercel, workflows automatically use the [Vercel World](/worlds/vercel) with zero configuration.
438
- </Callout>
504
+ <WorldTestingPerformance worldId="postgres" />
439
505
 
440
506
  ## Limitations
441
507