---
title: Encrypting Postgres World data
description: Enable end-to-end encryption for the Postgres World by adding getEncryptionKeyForRun in a World module, and plan the key source, rotation and rollout.
docs_index: /llms.txt
lastUpdated: 2026-12-04
type: guide
summary: Encrypt workflow payloads stored by the Postgres World with a root key and per-run HKDF keys.
prerequisites:
  - /worlds/postgres
related:
  - /docs/how-it-works/encryption
  - /worlds/self-hosted-web-ui
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Encrypt the workflow inputs, return values, hook payloads and stream chunks that the [Postgres World](/worlds/postgres) stores, so a leaked database credential, backup or `pg_dump` exposes only ciphertext. The Postgres World has no built-in `getEncryptionKeyForRun()` method, so you add one in a World module of your own that wraps `createWorld()`.

## How Postgres World encryption works

The runtime [encrypts payloads end to end](/docs/how-it-works/encryption) with AES-256-GCM before the World writes them, whenever the World's `getEncryptionKeyForRun()` returns a key for the run. That page lists what is encrypted, what stays plaintext, and what encryption doesn't protect against. For the Postgres World, the key comes from four parts:

- **A root key.** 32 random bytes per application, kept outside the database in a secret store or wrapped by a key management service (KMS).
- **A per-run key.** Your module derives each run's key from the root key and the run ID with HKDF-SHA256. Every process derives the same key without I/O or storage, and each run gets its own AES key and keypair.
- **A key list.** Each root key has an ID and a `from` time, and the run ID's timestamp selects the entry. Runs created before the first `from` stay unencrypted, which lets you enable encryption, rotate keys, and disable encryption without touching runs in flight.
- **A World module.** Your module wraps `createWorld()` from `@workflow/world-postgres`, and every process that touches runs loads it, including your application, its workers, the web UI, and the CLI.

## Enable encryption

### 1. Generate a root key

Generate 32 random bytes, encoded as base64:

```bash
openssl rand -base64 32
```

Store the value in your secret store, such as a Kubernetes Secret. To keep the plaintext key out of configuration, wrap it with a KMS instead (see [Where the root key comes from](#where-the-root-key-comes-from)).

### 2. Add the World module

Install `ulid`, which the module uses to read the creation time from a run ID:

```bash
npm install ulid
```

Then create a module that wraps `createWorld()` and adds `getEncryptionKeyForRun()` to the World it returns:

```typescript title="my-world.ts" lineNumbers
import { hkdfSync } from "node:crypto";
import type { WorkflowRun } from "@workflow/world";
import { createWorld as createPostgresWorld } from "@workflow/world-postgres";
import { decodeTime } from "ulid";

type KeyEntry = { id: string; from: number; root: Buffer | null };

function loadKeys(): KeyEntry[] {
  const raw = process.env.WORKFLOW_ENCRYPTION_KEYS;
  // Refuse to start rather than claim encrypted runs without a key.
  if (!raw) throw new Error("WORKFLOW_ENCRYPTION_KEYS is not set");
  const entries: { id: string; from: string; key: string | null }[] =
    JSON.parse(raw);
  return entries
    .map(({ id, from, key }) => {
      const root = key === null ? null : Buffer.from(key, "base64");
      if (root && root.length !== 32) throw new Error(`${id}: need 32 bytes`);
      if (Number.isNaN(Date.parse(from))) throw new Error(`${id}: bad from`);
      return { id, from: Date.parse(from), root };
    })
    .sort((a, b) => b.from - a.from); // Newest first
}

export function createWorld() {
  const world = createPostgresWorld();
  const keys = loadKeys();

  async function getEncryptionKeyForRun(run: WorkflowRun | string) {
    const runId = typeof run === "string" ? run : run.runId;
    // `wrun_` plus a ULID minted when the run started
    const createdAt = decodeTime(runId.slice("wrun_".length));
    const entry = keys.find((key) => key.from <= createdAt);
    // Before the first cutoff, or after a "no key" entry: unencrypted
    if (!entry?.root) return undefined;
    const info = `workflow-postgres|${runId}`;
    return new Uint8Array(
      hkdfSync("sha256", entry.root, new Uint8Array(32), info, 32)
    );
  }

  return Object.assign(world, { getEncryptionKeyForRun });
}
```

The module reads its key list from `WORKFLOW_ENCRYPTION_KEYS`, an environment variable that the module defines and the SDK doesn't read. Each entry's `key` is a base64-encoded 32-byte root key, or `null` for "no key". The key function ignores the `context` argument, because every deployment of the application shares one key list.

### 3. Deploy the key list with a future cutoff

Set the key list and point your application at the module:

```bash title=".env"
WORKFLOW_TARGET_WORLD="./my-world.ts"
WORKFLOW_ENCRYPTION_KEYS='[{ "id": "k1", "from": "2027-01-15T00:00:00Z", "key": "your_root_key_base64_here" }]'
```

Set `from` to a time after every process has loaded the key list, such as a day after the deploy. A process without the key fails any encrypted run it picks up, and runs created before `from` stay unencrypted, so a future cutoff gives every process time to load the key list first. See [Roll out without failing runs](#roll-out-without-failing-runs) for how much margin you need.

With a raw root key, the whole `WORKFLOW_ENCRYPTION_KEYS` value is a secret. Store it in your secret store, not in a committed `.env` file.

### 4. Point the web UI and the CLI at the module

The observability tools decrypt only with a World that implements `getEncryptionKeyForRun()`. With the stock `@workflow/world-postgres` backend, encrypted fields show as `🔒 Encrypted` placeholders. To decrypt in the CLI, set the same `WORKFLOW_TARGET_WORLD` and `WORKFLOW_ENCRYPTION_KEYS` as your application, along with `WORKFLOW_POSTGRES_URL`:

```bash
WORKFLOW_TARGET_WORLD=./my-world.ts npx workflow inspect run <run-id> --decrypt
```

For the [self-hosted web UI](/worlds/self-hosted-web-ui), set `WORKFLOW_TARGET_WORLD` to your module, or pass your World to `createWorkflowWebHandler({ world })`. To show run structure only, use `WORKFLOW_TARGET_WORLD=@workflow/world-postgres` without the key list; the wrapper above refuses to start without it. See [Decide who can decrypt](#decide-who-can-decrypt).

### 5. Check that new runs are encrypted

After the cutoff, start a run and inspect it with the CLI, without `--decrypt`:

```bash
npx workflow inspect run <run-id>
```

The run's `input` and `output` show as `🔒 Encrypted` placeholders, and the run has an `encryptionPublicKey`. Runs created before the cutoff show their data in readable form and have no public key.

## Where the root key comes from

The root key has to come from outside the database. Pick one of these sources:

| Source                             | How it works                                                                                                                                                          | Who can read the root key                                                     | Startup dependency                               |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------ |
| **Raw secret**                     | A Kubernetes Secret or a secrets manager value, read as an environment variable                                                                                       | Whoever can read the secret or the process environment                        | The secret store                                 |
| **KMS-wrapped data key in config** | A KMS such as AWS KMS, GCP Cloud KMS or Vault Transit wraps the root key. The wrapped form ships as plain configuration, and each process unwraps it once at startup. | Only identities the KMS lets decrypt, and each unwrap is in the KMS audit log | The KMS, once per process start                  |
| **Envelope key in the database**   | The first process generates a root key, has the KMS wrap it, and stores the wrapped form in a table. Every process reads and unwraps it at startup.                   | Same as a KMS-wrapped data key                                                | The database and the KMS, once per process start |

A raw secret is the simplest choice. Whoever creates it sees the plaintext, and so does anyone who can read the secret.

A KMS-wrapped data key keeps the plaintext out of configuration and out of the hands of the people who deploy. Generate the data key so that no one sees its plaintext. AWS KMS `GenerateDataKeyWithoutPlaintext` and Vault Transit's `datakey/wrapped` endpoint return only the wrapped form. GCP Cloud KMS has no data key operation, so generate 32 random bytes in a short-lived process and encrypt them. Grant decrypt access through the KMS key policy, scoped to your application's identity, and bind the wrapped key to an encryption context (or additional authenticated data) that names the application, so one application can't unwrap another's root key.

To use a KMS-wrapped root key, store the wrapped form in the key list and make `createWorld()` async, so it unwraps each entry with your KMS client before returning the World. The World module loader awaits an async `createWorld()`, so a failed unwrap stops the World from starting.

An envelope key in the database avoids shipping configuration, but adds a table, a race between the first processes to start, and a database read before the World can start. A database leak exposes only the wrapped key, which is useless without the KMS.

### Why identifiers can't be key material

Don't derive the root key from anything an attacker with database access can see or guess. A key derived only from values like these can be derived again by whoever reads the database, so it protects nothing:

- **Deployment IDs.** Every run stores its deployment ID in plaintext. With [`WORKFLOW_POSTGRES_DEPLOYMENT_ID`](/worlds/postgres#workflow_postgres_deployment_id) it is an image tag or a commit SHA; without it, every run records `postgres`.
- **Rollout identifiers.** Image digests, commit SHAs and Kubernetes pod template hashes are visible in your registry, your CI logs and the cluster's own objects.
- **Run IDs.** They are the primary keys of the tables you are protecting.

### Why derive a key per run

Return a derived key, not the root key itself. If every run returned the root key, all runs would share one AES key and one keypair, so a payload copied from one run into another would decrypt there, and the random-nonce budget of AES-GCM would apply to all of your data at once. The [Vercel World](/worlds/vercel) uses the same HKDF construction with its deployment key.

The HKDF `info` label (`workflow-postgres|<runId>` in the sample) is part of every run's key. Changing it changes every run's key, so treat a label change like a new root key and apply it only to runs created after a cutoff.

## Rotate, disable and retire keys

Every change to encryption is a change to the key list. For each run, the key function picks the newest entry whose `from` is at or before the run's creation time:

```json
[
  { "id": "k2", "from": "2027-03-01T00:00:00Z", "key": "your_new_root_key_base64_here" },
  { "id": "k1", "from": "2027-01-15T00:00:00Z", "key": "your_root_key_base64_here" }
]
```

The run ID carries the creation time. The Postgres World doesn't mint its own run IDs, so the runtime creates each one as `wrun_` plus a [ULID](https://github.com/ulid/spec) when the run starts, and the ULID's first 48 bits are a millisecond timestamp. Every process maps a run to the same entry without I/O, and no per-run key ID has to be stored.

- **Enable.** Add the first entry. Runs created before its `from` stay unencrypted.
- **Rotate.** Add a new entry. Runs created before its `from` keep using the old root key.
- **Disable.** Add an entry with `"key": null`. New runs are stored unencrypted, and older entries still decrypt older runs.
- **Retire.** Remove an entry once every run created in its window has finished and you no longer need to read its data. Payloads encrypted with it, including those in backups and snapshots, become unreadable, which is the point of retiring it. With [`experimental_retention: 0`](/docs/observability/retention), a finished run's payloads are deleted, so retiring loses nothing outside backups.

Give each new entry a `from` later than the moment every process has loaded it, such as a day after the deploy (see [Roll out without failing runs](#roll-out-without-failing-runs)).

After a suspected key compromise, add a new entry with a near `from` and retire the old one once its runs finish. The old root key still decrypts every copy of the data it protected, including backups, until those expire.

## Roll out without failing runs

Encryption has to start at a time when every process that can touch a run already has the key, because a process without the key fails any encrypted run it picks up. That start time is the first entry's `from`. How much margin you need depends on whether runs are pinned to their deployment:

- **Unpinned** (no `WORKFLOW_POSTGRES_DEPLOYMENT_ID`). Every process claims every run. During a rolling update, processes of the previous release claim runs that new processes start. If the new release encrypted from the moment it started, the old processes would fail those runs. Deploy the key list with a future `from`, and let the cutoff pass only after no process of a release without the key list is left.
- **Pinned** (each release sets `WORKFLOW_POSTGRES_DEPLOYMENT_ID`). Each release runs only the runs it started, so old releases don't execute runs started by new ones. Payloads still cross releases: a newer release that calls `resumeHook()` on a run an older release started writes the payload. It seals the payload to the run's public key when the run has one. A run started without a key has none, so the newer release falls back to `getEncryptionKeyForRun()`, which returns `undefined` for runs created before the cutoff, and the payload stays plaintext. A run that a release without the key starts after the cutoff (for example from traffic it still receives, or as a child run of one of its steps) would get an encrypted payload it can't read. Pick a cutoff after the last release without the key list has stopped starting runs.

Rollback has the same hazard. Rolling back to a build without the key list after the cutoff fails the encrypted runs that build picks up. Ship the key list at least one release before its `from`, so that rolling back one release keeps it.

Make the World refuse to start when the key list is configured but can't be loaded, for example because the KMS is unreachable. A process that starts without the key list creates plaintext runs, which is harmless, but fails every encrypted run it claims.

## Why per-deployment keys buy little

A separate root key per deployment looks like it would isolate versions from each other, but for the Postgres World it doesn't change who can read the data:

- **Shared identity.** All deployments of an application share the database credentials and usually the same KMS permissions, so a compromised process can unwrap every deployment's root key anyway.
- **Cross-version reads.** A newer deployment reads older runs' data, such as hook metadata when it looks up or resumes a hook, streams, and return values. The web UI and the CLI read every run, so each of them needs every deployment's key.
- **Unpinned runs.** Without `WORKFLOW_POSTGRES_DEPLOYMENT_ID`, every run's deployment ID is `postgres`, so per-deployment keys collapse into one key.

Resumes across deployments work with any of these schemes, because the writer [seals to the run's public key](/docs/how-it-works/encryption#writes-from-other-processes). Per-deployment keys add storage, key creation on each deploy, and more KMS calls.

## Operations

### Decide who can decrypt

Any process that loads your World module with the key list can decrypt every run, so decide which tools get it:

- **The web UI.** When someone clicks **Decrypt**, the UI's server returns that run's derived key to the browser, which decrypts locally. Fetching the key is a read, so users with read-only access can do it, and it doesn't write an audit line (the UI writes those for changes only). Everyone the UI lets in can read every run. Use the stock `@workflow/world-postgres` backend without the key list to show run structure only, or load your World module with the key list and restrict who can sign in.
- **Operators.** Rather than handing out the raw root key, give operators a World module that unwraps the root key through the KMS with their own credentials. The KMS then decides and logs who decrypted.

### When the KMS is unavailable

With a KMS-wrapped root key, each process unwraps it once at startup and keeps it in memory, so running processes are unaffected by a KMS outage. New processes can't start until the KMS recovers, which affects scale-up and restarts. Don't call the KMS per run, because that puts the KMS on the path of every `start()` and every cold worker, and spends KMS request quota.

### Cost

One HKDF derivation takes about 10 µs with `node:crypto` `hkdfSync` and about 50 µs with Web Crypto on a laptop. The runtime also derives each run's X25519 keypair from the key, which takes about 0.1 ms. With a few key resolutions per delivery, that is well under a millisecond, typically less than one database round trip. A KMS-wrapped root key adds one KMS decrypt call per process start.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)