workflow 5.2.3 → 5.4.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 (48) 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/create-webhook.mdx +1 -1
  9. package/docs/api-reference/workflow/fetch.mdx +2 -0
  10. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +5 -1
  11. package/docs/api-reference/workflow-api/get-run.mdx +4 -0
  12. package/docs/api-reference/workflow-api/resume-hook.mdx +58 -2
  13. package/docs/api-reference/workflow-api/start.mdx +70 -3
  14. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +6 -3
  15. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +68 -0
  16. package/docs/api-reference/workflow-errors/index.mdx +6 -0
  17. package/docs/api-reference/workflow-errors/meta.json +2 -0
  18. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +2 -0
  19. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +58 -0
  20. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +12 -1
  21. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  22. package/docs/changelog/eager-processing.mdx +4 -0
  23. package/docs/changelog/index.mdx +1 -0
  24. package/docs/changelog/lazy-event-creation.md +1 -1
  25. package/docs/changelog/meta.json +1 -0
  26. package/docs/changelog/spec-9.mdx +4019 -0
  27. package/docs/changelog/turbo-mode.md +4 -0
  28. package/docs/configuration/cli-and-web-ui.mdx +4 -2
  29. package/docs/configuration/runtime-tuning.mdx +68 -2
  30. package/docs/configuration/worlds.mdx +13 -1
  31. package/docs/cookbook/advanced/child-workflows.mdx +127 -187
  32. package/docs/cookbook/common-patterns/batching.mdx +3 -1
  33. package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
  34. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +1 -1
  35. package/docs/cookbook/common-patterns/workflow-composition.mdx +5 -5
  36. package/docs/errors/fetch-in-workflow.mdx +15 -29
  37. package/docs/foundations/errors-and-retries.mdx +6 -0
  38. package/docs/foundations/hooks.mdx +3 -1
  39. package/docs/foundations/idempotency.mdx +190 -60
  40. package/docs/foundations/starting-workflows.mdx +3 -7
  41. package/docs/how-it-works/event-sourcing.mdx +6 -0
  42. package/docs/whats-new.mdx +3 -1
  43. package/docs/worlds/building-a-world.mdx +28 -3
  44. package/docs/worlds/local.mdx +6 -0
  45. package/docs/worlds/postgres.mdx +208 -146
  46. package/docs/worlds/upgrading-to-v5.mdx +7 -1
  47. package/docs/worlds/vercel.mdx +9 -7
  48. package/package.json +11 -11
@@ -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({ experimental_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({ experimental_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({ experimental_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`, `world-postgres` and `world-vercel` declare it. 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>
94
+ The command is idempotent, so you can run it on every deploy.
70
95
 
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>
96
+ </Step>
88
97
 
89
- ## Starting the World
98
+ <Step>
90
99
 
91
- ### Experimental invocation delivery
100
+ ### Start the World when your server starts
92
101
 
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:
146
-
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.
184
+ </Callout>
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.
232
225
  </Callout>
233
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,13 +304,18 @@ 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
 
275
316
  Number of concurrent workers polling for jobs. Default: `50`.
276
317
 
277
- This value also bounds how many parent→child workflow polls can be in flight simultaneously. Every `await childRun.returnValue` inside a workflow holds a worker slot until the child run terminates. If you expect recursive or highly-fanned-out parent/child workflows, raise this ceiling above the peak number of concurrent polls. With the default of 50, the included `fibonacciWorkflow` end-to-end test (`fib(6)`, about 24 concurrent polls at peak) passes; deeper recursion or larger fanouts need a correspondingly larger setting.
318
+ A parent workflow awaiting `childRun.returnValue` of a child it started does not hold a worker slot: it suspends on a system hook the child resumes when it finishes (see [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits)). A `returnValue` that falls back to polling still does, for example one awaited inside a step, or any await while `WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0` is set. Each of those holds a worker slot until its child run terminates, so raise this ceiling above the peak number of such polls in flight.
278
319
 
279
320
  ### `WORKFLOW_POSTGRES_POLL_INTERVAL_MS`
280
321
 
@@ -306,6 +347,18 @@ 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.
@@ -320,6 +373,38 @@ For example, `custom` changes the queue topic prefix from `__wkf_workflow_` to `
320
373
 
321
374
  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
375
 
376
+ ## Upgrading
377
+
378
+ 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.
379
+
380
+ <Callout type="warn">
381
+ Migration 0027 converts every timestamp column to `timestamp with time zone`.
382
+ On a server whose time zone is UTC (the default on most hosted providers) it
383
+ only changes the catalog and rebuilds one small index, and the upgrade order
384
+ does not matter. On a server in another time zone it also rewrites each
385
+ `created_at` value from local time to the instant it recorded, about one
386
+ rewrite of each table, holding the tables' locks until it finishes. There, stop
387
+ the previous version's workers, run `bootstrap`, then start the upgraded app:
388
+ older versions read the converted columns shifted by the server's UTC offset,
389
+ so you cannot roll back past this migration either. If your app's connection
390
+ pool set a session time zone other than the server's, pass it to the migration
391
+ with `?options=-c%20workflow.legacy_timezone%3DEurope%2FBerlin` in the
392
+ connection string, or with `ALTER DATABASE ... SET workflow.legacy_timezone =
393
+ 'Europe/Berlin'` where your pooler drops startup `options`. The migration waits
394
+ at most 10 seconds for its locks; if a long transaction holds them,
395
+ `bootstrap` fails and can be run again.
396
+ </Callout>
397
+
398
+ ### Start Hooks
399
+
400
+ Migration `0028_add_start_hook_admissions` adds [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) support. It is required for every Postgres World on this version, 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.
401
+
402
+ Stop workers running a previous version before your app passes `experimental_hook` to `start()`. 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. For the same reason, don't roll back past migration `0028_add_start_hook_admissions` while start Hooks are in use.
403
+
404
+ ## Advanced
405
+
406
+ 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.
407
+
323
408
  ### Programmatic configuration
324
409
 
325
410
  {/*@skip-typecheck: incomplete code sample*/}
@@ -377,65 +462,42 @@ Graphile Worker responds automatically when the application is asked to shut dow
377
462
 
378
463
  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
464
 
380
- ## How it works
381
-
382
- The Postgres World uses PostgreSQL as a durable backend:
383
-
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.
387
-
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).
389
-
390
- ## Security
465
+ ### Experimental invocation delivery
391
466
 
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).
467
+ Invocation delivery is off by default, and you don't need it to run the Postgres World.
393
468
 
394
- ### Protect the queue route
469
+ 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.
395
470
 
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.
471
+ 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.
397
472
 
398
- The other routes under `/.well-known/workflow/v1/` differ:
473
+ 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.
399
474
 
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.
402
-
403
- A queue consumer that registered its own route with `registerRoute()` receives deliveries the same way, so protect that route like the flow route.
475
+ 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.
404
476
 
405
- ### Bringing your own auth
406
-
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:
477
+ 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.
408
478
 
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.
479
+ 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.
413
480
 
414
- ### Data at rest
481
+ 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.
415
482
 
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.
483
+ 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.
417
484
 
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.
485
+ Automatic cleanup of other results, stopping writes from reclaimed handlers, and routing requests across incompatible worker versions remain unimplemented.
419
486
 
420
- ## Deployment
487
+ ## How it works
421
488
 
422
- Deploy your application to any cloud that supports long-running servers:
489
+ The Postgres World uses PostgreSQL as a durable backend:
423
490
 
424
- - Docker containers
425
- - Kubernetes clusters
426
- - Virtual machines
427
- - Platform-as-a-service (PaaS) providers, such as Railway, Render, and Fly.io
491
+ - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
492
+ - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
493
+ - **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.
494
+ - **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
495
 
429
- Ensure your deployment has:
496
+ 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
497
 
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))
498
+ ## Testing & compatibility
435
499
 
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>
500
+ <WorldTestingPerformance worldId="postgres" />
439
501
 
440
502
  ## Limitations
441
503
 
@@ -136,7 +136,7 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
136
136
 
137
137
  | Member | What it buys |
138
138
  | --- | --- |
139
- | `capabilities` | Advertises `hookRetention.active`, `hookResumeDedup`, `hookForceClaim`, `deploymentAffinity`, `maxConcurrency`, and `dynamicWorkflowCode`. See the contract note above about failing closed. Event ID allocation is *not* in here: it is a requirement, not a capability. |
139
+ | `capabilities` | Advertises `hookRetention.active`, `hookResumeDedup`, `hookForceClaim`, `atomicStartHook.active`, `deploymentAffinity`, `maxConcurrency`, `inBandFence`, and `dynamicWorkflowCode`. See the contract note above about failing closed. Event ID allocation is *not* in here: it is a requirement, not a capability. |
140
140
  | `events.createBatch` | Appends an ordered list of events in one durable write, with a per-event outcome for each. Implementing the method *is* the declaration: the runtime folds a suspension's `step_created` / `wait_created` writes into batches only when it exists, and otherwise takes the single-event path unchanged. Implement it with real atomicity per attempt, so a lost race leaves nothing behind, or leave it out. See [Batched event writes](/docs/changelog/batched-event-writes). |
141
141
  | `runs.waitForTerminalStatus` | Long-polls until a run reaches a terminal status. `await run.returnValue` uses it when present, instead of polling on an interval. |
142
142
  | `analytics` | A metadata-only read namespace for observability surfaces. Payload-bearing reads stay on `runs`, `steps`, `events`, and `hooks`. |
@@ -152,7 +152,9 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
152
152
  | `close()` | Releases connection pools and listeners so CLI commands and short-lived processes can exit without `process.exit()`. |
153
153
  | `streams.streamFlushIntervalMs` | Sets the stream flush window. The v5 default is `0`, so the first chunk flushes immediately; set a value to coalesce writes again. |
154
154
  | Hook token retention | `Hook.tokenRetentionUntil` marks the earliest time a token may become available after its run ends. Keep the owning run readable at least that long, and honor `hook_disposed` as an immediate release. Declare `capabilities.hookRetention.active` only once this is implemented, since the runtime otherwise rejects retained hooks before registration. |
155
+ | Atomic start Hooks | Backs [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts): admit a run and create its start Hook in one atomic step, so a duplicate start is refused naming the owner and the start Hook can be resumed from admission. Declare `capabilities.atomicStartHook.active` only once you implement [the contract](/worlds/building-a-world#optional-atomic-start-hook-admission). |
155
156
  | Hook resume dedup | `resumeHook()` writes `hook_received` and dispatches the queue message in parallel when the backend collapses concurrent writes carrying the same `(runId, resumeId)` onto one committed event. Declare `capabilities.hookResumeDedup` only if you enforce that constraint **and** `events.list()` returns the committed event's top-level `resumeId`. A World that omits either guarantee must leave the flag unset, which keeps the sequential path. See [Durable hook resume](/docs/changelog/lazy-hook-resume). |
157
+ | Resolved hook resume | Lets `resumeHook()` deliver to a stored [`Hook`](/docs/api-reference/workflow-api/resume-hook#reuse-a-resolved-hook) without looking up its token again. Declare `capabilities.resolvedHookResume` only if a write carrying `requireHookResumeDedup` either commits with atomic resume deduplication or is refused (400/404) before anything is written. The runtime then looks the token up and delivers as usual. Without the flag, a stored Hook is delivered through the existing path. |
156
158
  | Hook token takeover | Backs [`createHook({ experimental_force: true })`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds). When a forced `hook_created` names a token another live run holds, append `hook_disposed` with `forceClaimedBy: { runId, hookId }` to the holder's log and refuse later `hook_received` writes to it, then re-point the token to the claimer and record `Hook.claimedFrom`. Refuse the takeover with an ordinary `hook_conflict` carrying `forceRefusedReason: 'victim-spec-version'` when the holder was stamped below spec version 8, and answer a `hook_received` refused by a takeover with `HookForceClaimedError` so `resumeHook()` can follow the token. Declare `capabilities.hookForceClaim` only once you give these guarantees. Without it, the runtime fails a forced `createHook()` at registration. |
157
159
 
158
160
  ## If you also maintain a build integration
@@ -182,3 +184,7 @@ The cases worth covering explicitly:
182
184
  `@workflow/world-testing` is the shared suite the first-party Worlds run, and it now covers event ID allocation directly: `numbers events by position` fails a World whose IDs do not decode to slots, whose run is not dense from 1, or whose IDs are not in canonical form. A World padding to a different width sorts its own log incorrectly past ten events. Run it against your World before the end-to-end cases above; it turns the failure that would otherwise appear on a first replay into one line of test output.
183
185
 
184
186
  The first-party implementations in `packages/world-local` and `packages/world-postgres` are the reference for everything else, and their test suites are the closest thing to full conformance while the compatibility tests are being rebuilt.
187
+
188
+ ## Spec 9 (experimental)
189
+
190
+ A World does not need to implement anything for the experimental spec 9 runtime to migrate to v5: `mintedSpecVersion()` with no options keeps creating spec 8 runs. A World that opts in must tell its users to upgrade every deployment and process that shares it before they set `WORKFLOW_SPEC_VERSION=9`, and not to roll back below that release once spec 9 runs exist. See [Implementing spec 9 in a World](/docs/changelog/spec-9#implementing-spec-9-in-a-world) and [The rollback floor](/docs/changelog/spec-9#the-rollback-floor).