npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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 is SequenceConflict; the unique (stream, sequence) is the backstop and is also reported as SequenceConflict. Events are stamped with stampEvents before 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 > last in pages of batchSize. When a page comes back empty it waits for a wake-up: an append of the same layer (immediately), a NOTIFY from another process (with a PgClient and listen), or pollInterval. The poll timer runs on the live clock, so subscriptions keep moving under a TestClock. 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 when leased_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 NOTHING and, 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's now(), and are stored as timestamptz (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: false and listen: 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-model where fields (for example CREATE 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.save deletes the stream's older snapshots in the same transaction and keeps the newest keep (default 1). Acknowledged outbox rows (acknowledged_at set) and old command records keep enqueue and record idempotent: delete them only past the window in which a repeat can still arrive (for example DELETE FROM wf_outbox WHERE acknowledged_at < now() - interval '30 days'). Cancelled timers are deleted at once.
  • Vacuum. wf_outbox and wf_timers are update- and delete-heavy queues: let autovacuum visit them often (ALTER TABLE … SET (autovacuum_vacuum_scale_factor = 0.01)). wf_events is append-only and needs little besides analyze. wf_read_models churns 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 \u0000 is refused by PostgreSQL (StoreUnavailable).
  • Errors. Every database failure of a port operation is StoreUnavailable, with the SqlError as 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 build

By 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.