@sewdn/workflow-store-postgres
v0.1.1
Published
PostgreSQL adapters for the ports of the workflow runtime, for servers: events, snapshots, read models, commands, outbox and timers.
Readme
@sewdn/workflow-store-postgres
PostgreSQL adapters for the storage ports of @sewdn/workflow-runtime, for servers. Several runtime processes
can share one database. Built on effect 4.1.4 and @effect/sql-pg 4.1.4 (Effect's own PostgreSQL client).
import { layerFromConfig } from "@sewdn/workflow-store-postgres";
const stores = layerFromConfig(
{ host: "db.internal", database: "app", username: "app", password: Redacted.make(secret) },
{ schema: "workflow" },
);
program.pipe(Effect.provide(stores));| Export | Provides | Needs |
| ------------------------------ | ---------------------------------------------------------------------------- | ----------- |
| layerFromConfig(conn, opts?) | every port below, on its own pool (PgClient.PgPoolConfig), migrating first | nothing |
| layer(opts?) | every port below, migrating first | SqlClient |
| layerEventStore(opts?) | EventStore | SqlClient |
| layerSnapshotStore(opts?) | SnapshotStore | SqlClient |
| layerReadModelStore(opts?) | ReadModelStore | SqlClient |
| layerCommandLog(opts?) | CommandLog | SqlClient |
| layerOutbox(opts?) | Outbox | SqlClient |
| layerScheduler(opts?) | Scheduler | SqlClient |
| layerMigrate(opts?) | nothing; runs migrate when built | SqlClient |
| migrate(opts?) | an effect: creates the schema and brings its tables up to date | SqlClient |
| make* (one per port) | the service as an effect, for composing by hand | SqlClient |
The port layers do not migrate: provide layerMigrate under them, or run migrate at deploy time. With an
existing client, give the layers PgClient.layer(…) (which provides both PgClient and SqlClient), or any
other SqlClient; only with a PgClient does the event store LISTEN.
Notifier and Directory are not here: they front the application's mail and people, not this database.
Layout version 2 requires a fresh schema. An existing schema from the first layout is rejected before opening its stores.
Options
| Option | Default | Meaning |
| -------------- | -------- | ----------------------------------------------------------------------------- |
| schema | public | the PostgreSQL schema of the tables; [a-z_][a-z0-9_]*, at most 48 chars |
| pollInterval | 1 second | how long an idle subscription waits for a wake-up before it polls anyway |
| batchSize | 500 | events per subscription query |
| listen | true | LISTEN on wf_events.<schema> to wake subscriptions as soon as others append |
One schema is one store: two schemas in one database share nothing.
Schema
Migration 2_create_tables, recorded in <schema>.wf_migrations by Effect's Migrator. migrate takes an
advisory lock per schema, so processes starting together migrate once.
| Table | Columns | Keys and indexes |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| wf_events | position bigserial, id, stream, sequence, type, version, payload jsonb, recorded_at timestamptz, actor_kind, actor_id, command_id, command_receipt jsonb, causation_id, correlation_id | primary key position; unique (stream, sequence); unique id; (type, position) |
| wf_snapshots | stream, sequence, version, state jsonb, saved_at | primary key (stream, sequence) |
| wf_read_models | model, key, value jsonb | primary key (model, key) |
| wf_commands | command_id, identity jsonb, outcome jsonb, recorded_at | primary key command_id |
| wf_outbox | id, seq bigserial, kind, payload jsonb, available_at, attempts, leased_until, acknowledged_at | primary key id; partial (available_at NULLS FIRST, seq) where not acknowledged |
| wf_timers | timer_id, due_at, command jsonb, seq bigserial, leased_until | primary key timer_id; (due_at, seq) |
Stream ids, models and keys are COLLATE "C": they sort by bytes, which is the memory adapter's code unit
order for every character below U+10000.
How the guarantees are kept
- Append runs in one transaction: it takes a transaction-scoped advisory lock for the schema, checks the
stream's last sequence, inserts the batch (one statement, the batch as one JSON parameter) and sends
NOTIFY. A different last sequence isSequenceConflict; the unique(stream, sequence)is the backstop and is also reported asSequenceConflict. Events are stamped withstampEventsbefore the transaction. - Global position is the
bigserial, drawn under that lock and committed before the lock is released. So positions commit in increasing order, and a subscriber that reads "every position above the last one I saw" never skips a position that commits late. The price: appends to different streams of one schema wait for each other, one short transaction each. - Subscribe polls
position > lastin pages ofbatchSize. When a page comes back empty it waits for a wake-up: an append of the same layer (immediately), aNOTIFYfrom another process (with aPgClientandlisten), orpollInterval. The poll timer runs on the live clock, so subscriptions keep moving under aTestClock.from: "now"starts at the highest committed position when the subscription is established. - Outbox take is one
UPDATE … FROM (SELECT … FOR UPDATE SKIP LOCKED): concurrent takers in any number of processes get disjoint entries. A lease runs out whenleased_until <= now; the entry then comes back with the next attempt number. - Scheduler claim is the same kind of statement: concurrent claimers split the due timers, and each claimed
timer is leased (
leased_until) so a later claim skips it until the lease runs out or the timer is rescheduled. A timer claimed and never cancelled comes back after its lease (at least once). - Command log record inserts with
ON CONFLICT DO NOTHINGand, when that inserted nothing, reads the first record in a second statement (a concurrent first record is visible only to a new statement). - Times come from Effect's
Clock, never from the database'snow(), and are stored astimestamptz(milliseconds survive the round trip).
Operational notes
- Connections. One pool per process. A subscription holds no connection while it waits; the LISTEN wake-up
holds one connection per event store layer. With PgBouncer in transaction mode, set
prepare: falseandlisten: false(LISTEN needs a session); subscriptions then wake by polling. - Indexes. Subscriptions scan the primary key from their last position.
(type, position)serves subscriptions filtered by type.streams(prefix)scans the(stream, sequence)index; it is meant for administration, not hot paths. Add indexes for your own read-modelwherefields (for exampleCREATE INDEX ON workflow.wf_read_models (model, (value->>'seat'))) once a model is large. - Retention. Events are never deleted by the adapter; the history is the record.
SnapshotStore.savedeletes the stream's older snapshots in the same transaction and keeps the newestkeep(default 1). Acknowledged outbox rows (acknowledged_atset) and old command records keep enqueue and record idempotent: delete them only past the window in which a repeat can still arrive (for exampleDELETE FROM wf_outbox WHERE acknowledged_at < now() - interval '30 days'). Cancelled timers are deleted at once. - Vacuum.
wf_outboxandwf_timersare update- and delete-heavy queues: let autovacuum visit them often (ALTER TABLE … SET (autovacuum_vacuum_scale_factor = 0.01)).wf_eventsis append-only and needs little besides analyze.wf_read_modelschurns with projections; it follows the default settings. - JSON. Payloads, states and values are
jsonb: object key order and duplicate keys are not kept, numbers beyond double precision lose digits as in JavaScript, and a string holding\u0000is refused by PostgreSQL (StoreUnavailable). - Errors. Every database failure of a port operation is
StoreUnavailable, with theSqlErroras cause. A row that does not decode is a defect (corrupt data or a schema mismatch).
Tests
bun run typecheck
bun run test # the adapter suite and the two-process tests
bun run buildBy default the tests run on an in-process PGlite behind a small wire-protocol server on a free port. PGlite is
one session: the server hands it to one connection at a time per transaction, so it covers the SQL, the
transactions and the logic, but not real lock contention between sessions (SKIP LOCKED, the advisory lock under
load) nor LISTEN/NOTIFY between connections. Set WORKFLOW_TEST_POSTGRES_URL to run every file against a real
server instead (each case in a schema of its own, named per run by testSchema, so the database needs no clearing
between runs):
docker run -d --rm --name wf-pg -e POSTGRES_PASSWORD=<random> -p 127.0.0.1:<port>:5432 postgres:17.6-alpine
WORKFLOW_TEST_POSTGRES_URL=postgres://postgres:<random>@127.0.0.1:<port>/postgres bun run test
docker stop wf-pg@sewdn/workflow-store-postgres/testing exports the test database (testDatabase.start/stop, testConnection(),
testDatabaseKind(), testSchema(prefix), startPgliteServer) for other packages' tests, as @sewdn/workflow-server's suite over HTTP
uses it. It imports PGlite, a development dependency: test code only.
