Postgres

Postgres

The tables the engine keeps in your database, how to create and migrate them, which clients connect to them, what erasure deletes, and what to watch as volume grows.

This page is for whoever owns the database the engine runs on. At the end you will know what the engine stores and why it lives in your Postgres, how to create and upgrade its tables with your own migrations, how each host connects, what forgetUser deletes, and where volume accumulates.

Why your database

Every host keeps its data in a Postgres you run. Cloudflare Workflows and Lambda durable functions only execute; the events, profiles, entry ledger, message copies, opens and clicks are rows in your database, next to your app's. That is what lets the studio read real numbers with a connection string, lets you join journey data with your own tables, and keeps a user's erasure inside your own data boundary. Postgres 15 or later is required: the suppression table uses UNIQUE NULLS NOT DISTINCT.

One schema of its own

The tables live in one Postgres schema, workflow unless the config says otherwise, so their short names (event, profile, message) never meet the app's:

ts
export default defineConfig({
  // ...
  database: { schema: 'journeys' },
});

Each host passes this to the store: store: (env, database) => postgresJsStore(url, database).

One schema per engine. The routing tables (trigger, segment, the live deployment row) are global, so two engines on one schema swap each other's routes on every deploy. Give staging and production their own schema or database.

The tables

TableHolds
eventEvery ingested event, the fact base for performed(...). Unique on (user_id, event_id), so a redelivery is a no-op
profileIdentified properties per user; /ingest merges into props
visitorVisitors heard from, and the user each became
devicePush devices, one row per device, holding only the current owner
suppressionOpt-outs: a topic on a channel, or the whole channel when topic is null
erasureErasure tombstones; every write about a user is conditional on no row here
segment, segment_member, segment_start, segment_snapshotDeployed segments, who is in each and since when, starts still owed, sizes per sweep
trigger, segment_trigger, date_triggerThe routes, each carrying the workflow's re-entry policy
date_runHow far each date-triggered send got, kept across deploys
sweep_passWhere an unfinished sweep pass stands, so the next sweep carries on
entryThe entry ledger, one row per entry, unique on (workflow, user_id, occurrence)
subscriptionWake routing for waits
deploymentWhich code version's bundle the routes came from
irWorkflow IR, content-addressed by hash
instanceOne row per journey instance: the node it is on and how it ended
messageOne row per message copy (a push fans out per device), with its claim and delivery times
message_link, message_open, message_clickA sent email's links, and every open and click with its human or machine verdict
executionAWS only: durable executions whose start is an asynchronous submit
run, run_stepNode only: instances and checkpoints of the self-hosted runtime

The tables a host does not use stay empty; the schema check knows one set of tables for every runtime. Why the entry ledger looks the way it does is on re-entry.

Creating and migrating the tables

The host owns the migrations. Nothing creates or alters the tables at runtime: POST /bundle/deploy, and a new version applying its own bundle, check the live database first and refuse with a 503 listing every missing table or column. The check covers unique indexes and constraints as well as columns.

With drizzle

sendwend generate (from @sendwend/studio) writes the tables as one drizzle file on the config's schema:

bash
pnpm exec sendwend generate --out src/db/schema/workflow.ts

Re-export it from your drizzle schema, include the schema in drizzle-kit's schemaFilter, and let drizzle-kit write the migration like any other. Do not edit the file; regenerate it.

ts
// src/db/schema/index.ts
export * from './workflow';

Run the check in CI. It writes nothing and fails when the file is out of date with the installed SDK; formatting differences do not count, because the file is laid out the way a prettier-compatible formatter at 100 columns lays it out:

bash
pnpm exec sendwend generate --out src/db/schema/workflow.ts --check

The monorepo layout around this is on Monorepo.

Without drizzle

renderPostgresDdl(schema?) from sendwend/store returns the same tables as plain DDL (CREATE SCHEMA IF NOT EXISTS and CREATE TABLE IF NOT EXISTS), for a host with another migration tool. renderDrizzleSchema(schema?) is what generate writes.

ts
import { renderPostgresDdl } from 'sendwend/store';

await sql.unsafe(renderPostgresDdl());

IF NOT EXISTS makes it a first-time script only: it does not alter a table an older version created. For upgrades, diff against the new output or move to the drizzle file.

Upgrading the SDK

After every SDK upgrade: regenerate, let drizzle-kit write the migration, apply it, then deploy. Migrate before the new version serves. The deploy check refuses to apply a bundle until the tables match, but a version already serving does not wait for a column it reads. The README lists each version that changed the tables; the recent ones:

  • 12.7 adds run and run_step, the state of sendwend/node. Required on every runtime; they stay empty on Cloudflare and AWS.
  • 12.5 adds sweep_pass. A sweep now stops after about 30 seconds and the next one carries on, so its response may say finished: false with empty sizes.
  • 12.3 adds date_trigger and date_run, and a trigger.date workflow now runs. Check the date triggers you have before upgrading: one whose time is still ahead fires at that time.
  • 12.0 is breaking with no migration path for old data: every workflow needs a reentry policy, the IR version changes, and entry becomes one row per entry. Drain or reset the engine's data, regenerate, migrate and redeploy.

Connection clients

sendwend/postgres-js

postgresJsStore(connectionString, { schema, connection }) opens a store over postgres.js for one request or run and returns { store, close }. Its defaults suit a Worker with Hyperdrive: one connection, closed after 2 seconds idle, no type fetch on connect, prepared statements. A journey run lives for days, and a run holding its connection through its sleeps would hold one per sleeping instance, so idle connections close and the next query opens a fresh one. Override with connection (postgres.js options).

postgresJsClient(sql) wraps an existing postgres.js pool as the store's minimal SqlClientLike (query and transaction). The Node host takes it. It also writes JavaScript arrays as Postgres array literals, which postgres.js's unsafe would otherwise send in a form the store's = ANY($1::text[]) queries reject. Another driver needs a few lines implementing the same interface.

Hyperdrive

On Cloudflare the connection string is Hyperdrive's (env.HYPERDRIVE.connectionString). Turn Hyperdrive's query caching off for this database (caching: { disabled: true }): the engine reads wake subscriptions, profiles and segment membership right after writing them, and a cached answer up to 60 seconds old misses wakes and decides on stale data. Setup is on Cloudflare.

Pooling on Node and AWS

On Lambda each invocation opens a store and closes it when the invocation ends. On Node one pool serves the process, and a connection is held for a query rather than for an action, so the pool need not grow with concurrency (self-hosting).

Locking and consistency

Every write about a user runs in a transaction that first sets READ COMMITTED and takes a transaction-scoped advisory lock on the user (pg_advisory_xact_lock over the schema and the user id's hashtext). Concurrent ingests for one user are therefore applied one after another, the re-entry decision reads a consistent ledger, and an erasure and a write never interleave. Nothing outside the database (a send, a platform call, a wait) runs inside the locked transaction, so locks cover short database work only. A connection that defaults to REPEATABLE READ is fine; the store pins each transaction itself.

Reporting

With Postgres, the default observer records instances, every message copy, and every open and click. With WORKFLOW_ORIGIN set, email links and an open pixel are tracked through the host's /t/... routes, and each open and click is classified as a person's or a machine's (Apple Mail Privacy Protection, link scanners, prefetches), with the deciding rule kept in reason. Following an unsubscribe link counts as an open but not as a click of the copy. A push carries message_id; report the tap with messageOpened. @sendwend/studio/postgres reads all of it for the studio. These are ordinary tables, so you can query them for your own reports too.

Erasing a user's data

POST /users/forget (journeys.forgetUser(userId)) commits an erasure tombstone first, under the user's lock. Every write about the user is conditional on that tombstone from then on, so a write either committed before it and is deleted by the erase, or waited for the lock and is refused. The host then stops the user's running instances, and only once each is known stopped deletes, in one transaction:

  • message_open, message_click and message_link rows of the user's messages, then message
  • run_step and run rows of the user's instances (Node)
  • instance, entry, execution, subscription, segment_start, segment_member
  • suppression (nothing is ever sent to the id again), device, event and profile

The tombstone stays, marked erased, so a late write cannot bring the user back and the id is refused with a 410 on /ingest and /devices forever. erased: false means an instance would not stop yet; the scheduled sweep retries it. A visitor's link to its user is kept, so a late report of that visitor finds the tombstone instead of starting a new visitor. Anything you copied out of these tables is yours to erase.

What grows, and what to watch

The engine prunes some data on its own:

  • A visitor who never signs in is deleted 90 days after they were last heard from, unless a journey of theirs is still running.
  • On Node, a run that ended is removed after retentionMs (7 days).

Everything else stays until a user is erased. The tables that grow with traffic are event (one row per event), message and its message_open and message_click children (one row per copy, open and click), instance and entry (one row per journey entered), and segment_snapshot (one row per segment per sweep). The engine creates the indexes its own queries need, including (user_id, name, ts) on event for condition reads and (workflow, sent_at) on message for reporting; add your own for queries of your own.

As volume grows, watch:

  • Disk and autovacuum on event and the message tables. If you need to archive old events, remember that every count- and window-based condition reads the event log: an event a performed(..., { within }) or a segment still looks at must stay.
  • Sweep progress. A sweep spends about 30 seconds on segments, and the next one carries on. If its response keeps saying finished: false, segment sizes and seeding lag; run the sweep more often or look at the cost of your segment conditions.
  • Connections. On Cloudflare, Hyperdrive keeps the pool; on Node, size the pool for queries, not actions.
  • Database CPU on Node. The measured limit of the Node host on a 2 vCPU Postgres was about 450 runs a second, with the database the bottleneck (benchmark).

Pitfalls

  • Editing the generated file. The next generate --check fails, and the next regeneration drops your change.
  • Applying migrations after the deploy. A version already serving reads the new column at once.
  • Query caching in front of the engine. Hyperdrive's cache, or any read replica with lag, breaks wakes.
  • Sharing a schema between environments. Routes flip on every deploy.