workflow 5.2.2 → 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 (53) 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 +10 -2
  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 +68 -3
  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/index.mdx +1 -1
  21. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  22. package/docs/changelog/eager-processing.mdx +2 -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/resilient-start.mdx +2 -0
  27. package/docs/changelog/spec-9.mdx +4019 -0
  28. package/docs/changelog/turbo-mode.md +4 -0
  29. package/docs/configuration/cli-and-web-ui.mdx +3 -1
  30. package/docs/configuration/runtime-tuning.mdx +65 -3
  31. package/docs/configuration/worlds.mdx +18 -1
  32. package/docs/cookbook/advanced/child-workflows.mdx +2 -2
  33. package/docs/cookbook/common-patterns/batching.mdx +3 -1
  34. package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
  35. package/docs/errors/fetch-in-workflow.mdx +7 -1
  36. package/docs/errors/index.mdx +2 -2
  37. package/docs/errors/max-events-exceeded.mdx +80 -0
  38. package/docs/errors/replay-timeout.mdx +48 -0
  39. package/docs/errors/run-expired.mdx +3 -1
  40. package/docs/foundations/errors-and-retries.mdx +8 -2
  41. package/docs/foundations/hooks.mdx +3 -1
  42. package/docs/foundations/idempotency.mdx +190 -60
  43. package/docs/how-it-works/encryption.mdx +1 -1
  44. package/docs/how-it-works/event-sourcing.mdx +8 -2
  45. package/docs/observability/index.mdx +2 -0
  46. package/docs/observability/retention.mdx +8 -0
  47. package/docs/whats-new.mdx +4 -2
  48. package/docs/worlds/building-a-world.mdx +47 -8
  49. package/docs/worlds/local.mdx +6 -0
  50. package/docs/worlds/postgres.mdx +230 -129
  51. package/docs/worlds/upgrading-to-v5.mdx +8 -1
  52. package/docs/worlds/vercel.mdx +162 -8
  53. package/package.json +11 -11
@@ -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.
56
+
57
+ </Step>
41
58
 
42
- Configure the required environment variables to use the world and point it to your PostgreSQL database:
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,75 +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
- ## Starting the World
96
+ </Step>
72
97
 
73
- ### Experimental invocation delivery
98
+ <Step>
74
99
 
75
- Set `WORKFLOW_POSTGRES_INVOKE=1`, or pass `enableInvoke: true` to the Postgres
76
- World's factory, to send hook inputs to the run's executor and wait for its
77
- response. Invocation is off by default. Apply the migrations and upgrade
78
- producers and workers together before enabling it.
79
-
80
- The executor validates the hook input and writes its event before responding.
81
- Workflow user code can consume the event later. The World stores inputs and
82
- responses in `workflow.workflow_invocations`. Inserting an input and enqueueing
83
- a workflow execution job share one transaction. Retries also enqueue an execution
84
- job, including when a retained response already exists, so committed events can
85
- be replayed after a runner failure.
86
-
87
- With the default job prefix, Graphile uses `workflow_flows_executor` for workflow
88
- execution and `workflow_flows` for step jobs and health checks. Execution jobs
89
- use a named queue per run, `workflow_flows:<runId>:executor`. Graphile permits
90
- one active job on each named queue across workers. Other runs, steps, and health
91
- checks can run concurrently. `queueConcurrency` limits total active jobs per
92
- worker process and defaults to 50. A custom job prefix replaces `workflow_` in
93
- these names.
94
-
95
- The HTTP receiver checks each execution request against its active Graphile job
96
- before processing pending inputs. Updated workers and receivers move legacy
97
- orchestration requests to the run's named queue. Before acknowledging an execution
98
- job, the World finishes any input already being processed and replays newly
99
- committed events. These entry checks do not stop an old handler from writing
100
- after its job is reclaimed.
101
-
102
- The caller receives a stored return value or a restored Workflow error. Terminal
103
- errors are retained as outcomes; transient or unrecognized failures leave inputs
104
- pending for Graphile to retry. Migration 0022 preserves the meaning of responses
105
- stored by earlier previews. Failure to store or read a response leaves the
106
- processing outcome unknown. Durable resume identities deduplicate the hook event
107
- when response storage must be retried.
108
-
109
- A shared `LISTEN/NOTIFY` connection signals changes to pending inputs and
110
- responses. Notifications contain identifiers, and readers fetch data from the
111
- table. Use a session-capable connection for `LISTEN`. Readers fall back to polling
112
- at 1s intervals if notifications fail, and connection retries use a 1s backoff.
113
- Notification failure and recovery are logged once per transition without
114
- payloads or connection details.
115
-
116
- The response-wait timeout defaults to 30s and can be set with `timeoutMs`. Encoded
117
- inputs and outcomes are limited to 1 MiB each. A timeout does not cancel
118
- processing. `$retention: 0` purges invocation data and prevents late writes from
119
- restoring it. Callers whose result has expired receive a 410 error with code
120
- `INVOCATION_DATA_EXPIRED`, even if the hook event committed earlier.
121
-
122
- Automatic cleanup of other results, stopping writes from reclaimed handlers, and
123
- routing requests across incompatible worker versions remain unimplemented.
124
-
125
- ### Server startup
126
-
127
- 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
128
101
 
129
- <Callout type="warn">
130
- This step is specific to worlds that run a background worker, such as Postgres
131
- World. Worlds whose queue delivers work over HTTP, including the Vercel World,
132
- have no worker to subscribe, so `start()` does nothing there while the import
133
- still adds overhead. Pulling in `workflow/runtime` from a server-startup hook puts
134
- the whole runtime into the cold-start path before the first request is served.
135
- </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:
136
103
 
137
104
  <TabsWithChildren tabs={["Next.js","SvelteKit","Nitro"]}>
138
105
 
@@ -210,9 +177,83 @@ Learn more about [Nitro Plugins](https://v3.nitro.build/docs/plugins).
210
177
  </TabsWithChildren>
211
178
 
212
179
  <Callout type="info">
213
- 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.
214
184
  </Callout>
215
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
+
216
257
  ## Observability
217
258
 
218
259
  Use the Workflow CLI to inspect workflows stored in PostgreSQL:
@@ -232,13 +273,26 @@ If `WORKFLOW_POSTGRES_URL` is not set, the CLI defaults to `postgres://world:wor
232
273
 
233
274
  Learn more in the [Observability](/docs/observability) documentation.
234
275
 
235
- ## Testing & compatibility
236
-
237
- <WorldTestingPerformance worldId="postgres" />
238
-
239
276
  ## Configuration
240
277
 
241
- 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 |
242
296
 
243
297
  ### `WORKFLOW_POSTGRES_URL`
244
298
 
@@ -250,7 +304,12 @@ The `bootstrap` migration command uses the same precedence.
250
304
 
251
305
  ### `WORKFLOW_POSTGRES_JOB_PREFIX`
252
306
 
253
- 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
+
254
313
 
255
314
  ### `WORKFLOW_POSTGRES_WORKER_CONCURRENCY`
256
315
 
@@ -288,10 +347,32 @@ A delivery executes the workflow body inline, so the handler responds only once
288
347
 
289
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.
290
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
+
291
362
  ### `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`
292
363
 
293
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.
294
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
+
295
376
  ### `WORKFLOW_QUEUE_NAMESPACE`
296
377
 
297
378
  Queue topic namespace shared by build output and the Postgres World. Default: unset.
@@ -302,6 +383,32 @@ For example, `custom` changes the queue topic prefix from `__wkf_workflow_` to `
302
383
 
303
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.
304
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
+
305
412
  ### Programmatic configuration
306
413
 
307
414
  {/*@skip-typecheck: incomplete code sample*/}
@@ -320,14 +427,31 @@ export default createWorld({
320
427
  });
321
428
  ```
322
429
 
323
- You can also pass an existing `pg.Pool` as `pool` instead of a connection string. On a pool it creates, the World logs and drops an idle connection that the database closes, for example on a restart. A pool you pass needs its own `pool.on("error", ...)` listener. Without one, Node.js throws the error as an uncaught exception and the process exits.
324
-
325
430
  Options passed to `createWorld()` take precedence over the environment variables above. Export the World from a module and point `WORKFLOW_TARGET_WORLD` at that module:
326
431
 
327
432
  ```bash title=".env"
328
433
  WORKFLOW_TARGET_WORLD="./my-world.ts"
329
434
  ```
330
435
 
436
+ You can also pass an existing `pg.Pool` as `pool` instead of a connection string. The World then leaves that pool's `'error'` events to you. A connection the server ends, in a restart, a failover or an idle timeout, emits one, and an `'error'` event with no listener ends the process. Listen on each client the pool connects as well as on the pool: pg-pool listens only on idle clients, and the World holds a checked-out client across a transaction's statements.
437
+
438
+ {/*@skip-typecheck: requires pg, which the docs type-check does not install*/}
439
+
440
+ ```typescript title="my-world.ts" lineNumbers
441
+ import { createWorld } from "@workflow/world-postgres";
442
+ import { Pool } from "pg";
443
+
444
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
445
+ pool.on("connect", (client) =>
446
+ client.on("error", (error) => console.error(error.message))
447
+ );
448
+ pool.on("error", () => {}); // An idle client's error, logged just above
449
+
450
+ export default createWorld({ pool });
451
+ ```
452
+
453
+ A pool the World creates from `connectionString` already has these listeners.
454
+
331
455
  ### Queue consumers other than the Workflow SDK
332
456
 
333
457
  The worker delivers every job over HTTP, and by default to the Workflow SDK's flow route, `/.well-known/workflow/v1/flow`. A library that consumes messages of its own on the same World, such as a durable agent harness, uses its own queue prefix (`__{namespace}_wkf_workflow_`) and registers where those go: `world.registerRoute(prefix, "/api/agent/queue")` to deliver them to its own route, or `world.registerHandler(prefix, handler)` to deliver them inside the process that took the job, without HTTP. A job keeps the prefix it was enqueued under and the route its producer had registered, so a worker in another process delivers it to the same place. Register before calling `start()`, which re-enqueues each active run to the queue namespace it recorded at creation (`executionContext.queueNamespace`).
@@ -342,65 +466,42 @@ Graphile Worker responds automatically when the application is asked to shut dow
342
466
 
343
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.
344
468
 
345
- ## How it works
346
-
347
- The Postgres World uses PostgreSQL as a durable backend:
348
-
349
- - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
350
- - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
351
- - **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.
352
-
353
- 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).
354
-
355
- ## Security
469
+ ### Experimental invocation delivery
356
470
 
357
- 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).
471
+ Invocation delivery is off by default, and you don't need it to run the Postgres World.
358
472
 
359
- ### Protect the queue route
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.
360
474
 
361
- `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.
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.
362
476
 
363
- The other routes under `/.well-known/workflow/v1/` differ:
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.
364
478
 
365
- - `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.
366
- - `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.
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.
367
480
 
368
- A queue consumer that registered its own route with `registerRoute()` receives deliveries the same way, so protect that route like the flow 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.
369
482
 
370
- ### Bringing your own auth
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.
371
484
 
372
- 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:
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.
373
486
 
374
- - **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.
375
- - **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.
376
- - **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.
377
- - **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.
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.
378
488
 
379
- ### Data at rest
489
+ Automatic cleanup of other results, stopping writes from reclaimed handlers, and routing requests across incompatible worker versions remain unimplemented.
380
490
 
381
- 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.
382
-
383
- 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.
384
-
385
- ## Deployment
491
+ ## How it works
386
492
 
387
- Deploy your application to any cloud that supports long-running servers:
493
+ The Postgres World uses PostgreSQL as a durable backend:
388
494
 
389
- - Docker containers
390
- - Kubernetes clusters
391
- - Virtual machines
392
- - 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.
393
499
 
394
- 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).
395
501
 
396
- - Network access to your PostgreSQL database
397
- - Environment variables configured correctly
398
- - The `start()` function called on server initialization
399
- - `/.well-known/workflow/v1/flow` restricted so untrusted clients cannot reach it (see [Security](#security))
502
+ ## Testing & compatibility
400
503
 
401
- <Callout type="info">
402
- The Postgres World is not compatible with Vercel deployments. On Vercel, workflows automatically use the [Vercel World](/worlds/vercel) with zero configuration.
403
- </Callout>
504
+ <WorldTestingPerformance worldId="postgres" />
404
505
 
405
506
  ## Limitations
406
507
 
@@ -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`. |
@@ -145,13 +145,16 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
145
145
  | `getRuntimeDeadline()` | The absolute time the current invocation will be terminated. The runtime derives its inline replay budget from this, so a host with a long function timeout gets more work per invocation. Without it, the budget is a flat two minutes. See [`WORKFLOW_V2_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_v2_timeout_ms). |
146
146
  | `getEnvironment()` | The environment your World's writes are attributed to. Must be synchronous, side-effect free, and match what the backend will actually apply. A wrong answer is worse than `undefined`, because callers use it to detect cross-environment mismatches. Worlds with a single tenant should omit it. |
147
147
  | `createRunId(options)` | Mints the bare run ID; the core adds the `wrun_` prefix. Return a valid ULID. You may embed World-specific metadata in it, as `@workflow/world-vercel` does with a region identifier. Read only the option keys you recognize and ignore the rest. |
148
+ | `regionForRunId(runId)` | The region an existing run's data lives in, decoded from its ID. Lets replays keep the original run's region. Omit it if your World has no regional dimension. |
148
149
  | `describeRun(run)` | World-specific display fields for observability surfaces. |
149
150
  | `getEncryptionKeyForRun()` | Returns a ready-to-use 32-byte AES-256 key. Without it, data is stored unencrypted. Two overloads: pass the `WorkflowRun` when you have it, or a `runId` plus opaque World context when the entity is not available locally. |
150
151
  | `resolveLatestDeploymentId()` | Resolves `deploymentId: 'latest'`. Only meaningful for Worlds where deployment routing exists. |
151
152
  | `close()` | Releases connection pools and listeners so CLI commands and short-lived processes can exit without `process.exit()`. |
152
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. |
153
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({ 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). |
154
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. |
155
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. |
156
159
 
157
160
  ## If you also maintain a build integration
@@ -181,3 +184,7 @@ The cases worth covering explicitly:
181
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.
182
185
 
183
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).