PostgreSQL
Ce contenu n’est pas encore disponible dans votre langue.
The Postgres backend provides all three persistence components against a
single PostgreSQL database, via the pg
driver:
PostgresJournal— the event journal forPersistentActors.PostgresSnapshotStore— snapshots to bound recovery.PostgresDurableStateStore— key-value durable state forDurableStateActors. This is the first SQL-backed durable-state store (SQLite and Cassandra ship journal + snapshot only).
Like Cassandra, Postgres is shared across cluster nodes — any node can read or write any persistenceId — but it’s relational, transactional, and almost certainly already in your stack.
Install
Section titled “Install”pg is an optional peer dependency — install it alongside actor-ts:
bun add pgThe framework imports pg only when a Postgres store opens — at startup,
or on first use when the boot-time open is turned off — so it stays out of
your bundle until you opt in.
Register all three stores through the plugins slot of the system’s
options and select them in its configuration. Pass a shared pool so
all three components reuse one connection pool:
import { Pool } from 'pg';import { ActorSystem, ActorSystemOptions,} from 'actor-ts';import { PostgresJournalOptions, PostgresSnapshotStoreOptions, PostgresDurableStateStoreOptions, RegisterPostgresPluginsOptions, registerPostgresPlugins,} from 'actor-ts/persistence';
const postgresSnapshotStoreOptions = PostgresSnapshotStoreOptions.create().withKeepN(3);const registerOptions = RegisterPostgresPluginsOptions.create() // One pool shared by journal + snapshot + durable-state (recommended). .withPool(new Pool({ connectionString: 'postgres://user:pass@host:5432/app' })) .withJournal(PostgresJournalOptions.create() /* .withEventsTable(...).withTagsTable(...).withAutoCreateTables(...) */) .withSnapshotStore(postgresSnapshotStoreOptions) .withDurableStateStore(PostgresDurableStateStoreOptions.create() /* .withTable(...) */);const systemOptions = ActorSystemOptions.create() // Select the Postgres plugins for all three stores. .withConfig({ 'actor-ts': { persistence: { journal: { plugin: 'actor-ts.persistence.journal.postgres' }, 'snapshot-store': { plugin: 'actor-ts.persistence.snapshot-store.postgres' }, 'durable-state': { plugin: 'actor-ts.persistence.durable-state.postgres' }, }, }, }) .withPersistence({ plugins: [(persistence) => registerPostgresPlugins(persistence, registerOptions)] });const system = ActorSystem.create('my-app', systemOptions);The plug-in runs inside ActorSystem.create, so all three stores are
registered before create returns, and the ones the configuration selects
open as part of the startup: a database the node cannot reach fails the
startup rather than the first persisted message — see opening the stores
at startup.
That holds with autoCreateTables off too, since the open then sends a
SELECT 1 where it would have run the DDL, and while the boot-time open is
on, the default: with the boot-time open turned off, the failure moves to the
store’s first operation. It holds for these stores, not for every axis: an
object-storage snapshot or durable-state store selected beside them, or a store
of your own without start(), has nothing to open ahead of time and fails its
first operation instead.
registerPostgresPlugins also returns the durable-state store, for a
caller that would rather wire it by hand; a plug-in keeps it by assigning
the result, (persistence) => { postgres = registerPostgresPlugins(persistence, registerOptions); }.
Since #872 that is a convenience rather than the only route, and a store
wired by hand is not a selected one, so it opens on first use rather than
with the startup.
Without a shared pool, each component builds its own pool from its
url / poolConfig when it opens:
const postgresJournalOptions = PostgresJournalOptions.create().withUrl('postgres://user:pass@host:5432/app');const postgresSnapshotStoreOptions = PostgresSnapshotStoreOptions.create() .withUrl('postgres://user:pass@host:5432/app').withKeepN(3);const postgresDurableStateStoreOptions = PostgresDurableStateStoreOptions.create().withUrl('postgres://user:pass@host:5432/app');const registerPostgresPluginsOptions = RegisterPostgresPluginsOptions.create() .withJournal(postgresJournalOptions) .withSnapshotStore(postgresSnapshotStoreOptions) .withDurableStateStore(postgresDurableStateStoreOptions);const systemOptions = ActorSystemOptions.create().withPersistence({ plugins: [(persistence) => registerPostgresPlugins(persistence, registerPostgresPluginsOptions)],});Configure it from HOCON
Section titled “Configure it from HOCON”The plugin id is the config section, so the block named after the id is the
block that plugin reads (#872). Everything except the live objects can come
from application.conf, which means registerPostgresPlugins(persistence) needs no options at all:
import { ActorSystem, ActorSystemOptions } from 'actor-ts';import { registerPostgresPlugins } from 'actor-ts/persistence';
const systemOptions = ActorSystemOptions.create().withPersistence({ plugins: [(persistence) => registerPostgresPlugins(persistence)],});const system = ActorSystem.create('my-app', systemOptions);actor-ts.persistence { journal { plugin = "actor-ts.persistence.journal.postgres" } snapshot-store { plugin = "actor-ts.persistence.snapshot-store.postgres" } durable-state { plugin = "actor-ts.persistence.durable-state.postgres" }
journal.postgres { url = ${?DATABASE_URL}, events-table = "events" } snapshot-store.postgres { url = ${?DATABASE_URL}, keep-n = 5 } durable-state.postgres { url = ${?DATABASE_URL}, table = "durable_state" }}Options passed to registerPostgresPlugins still win, field by field, and a field you leave
unset falls through to the block rather than blanking it — so a shared
pool in code and the table names in HOCON is a normal mix. A pre-built
pool and a serializer have no leaf at all: they are live objects, and
a config file cannot express one. Neither does poolConfig — the driver’s whole
option surface, which stays code-only. tags-table is read but ships as a comment
rather than a key, because its default is derived from events-table, and
absence is what keeps the two in step.
What you do tune on the pool has typed leaves (#1490), each a comment in the reference configuration so that leaving it out keeps pg’s own default:
actor-ts.persistence.journal.postgres { url = ${?DATABASE_URL} max-pool-size = 20 # pg-pool's max (default 10) idle-timeout = 30s # pg-pool's idleTimeoutMillis (default 10s) connect-timeout = 5s # pg's connectionTimeoutMillis (default: none) ca-file = "/etc/ssl/rds-ca.pem" # read when the pool opens, handed to pg as ssl.ca}Each reaches the driver only when set. The store checks them when it is built:
a size or timeout that is not a positive whole number, or a timeout longer than
a timer can hold, is refused with an OptionsError — and so is a leaf beside the
same key in poolConfig (max-pool-size beside max, say), which names both
instead of letting one quietly win. ca-file is a path the framework reads,
never the certificate itself; a file it cannot read fails the store’s open —
the startup, or its first use when the boot-time open is turned off — naming
the leaf and the path.
A url that switches TLS verification off is refused. sslmode=no-verify,
ssl=no-verify, and — under uselibpqcompat=true — sslmode=prefer,
require or verify-ca make the reader throw a ConfigError naming the leaf
and the switch, in any letter case and whether the url is written out or
substituted from ${?DATABASE_URL}. The refusal is strict about the file: the
block’s url is refused even when registerPostgresPlugins is given a url or a
pool of its own. Only HOCON is inspected — the same string passed to
withUrl(...) is your code’s decision, and that is where an unverified server
belongs if you really mean one. For a private CA, set ca-file and leave the
url’s ssl parameters out, or write sslmode=verify-full&sslrootcert=<CA file> —
one or the other: node-postgres assigns the TLS settings it parses from the url
over the ones it was given, so ca-file beside any url ssl parameter is
refused rather than dropped. sslmode=disable is plaintext rather than
unverified TLS and stays allowed. The reasoning, and the switches in full, are
on TLS everywhere.
durable-state.plugin now selects this backend’s durable-state store. It
used to be built eagerly and handed back from registerPostgresPlugins, so it could only be
wired by threading that instance through application code. The returned handle
still works and still yields the same instance — it is simply built when it is
first asked for rather than at registration, which for a selected store is the
startup.
When to use it
Section titled “When to use it”- You already run Postgres. One less moving part than standing up Cassandra — reuse your existing managed instance (RDS, Cloud SQL, Supabase, …).
- Cluster-shared persistence. Sharded entities that move between nodes, or cross-node projections, need a journal every node can read.
- You want durable state in SQL. The only SQL durable-state store in the framework.
For single-node dev, SqliteJournal is
simpler (one file, no server).
Configuration
Section titled “Configuration”type PostgresConnection = { url?: string; // postgres://user:pass@host:5432/db poolConfig?: Record<string, unknown>; // extra pg.Pool config — the code-only long tail pool?: PgPoolLike; // pre-built / shared pool maxPoolSize?: number; // pg-pool max, default 10 (max-pool-size) idleTimeoutMs?: number; // idleTimeoutMillis, default 10 000 (idle-timeout) connectTimeoutMs?: number; // connectionTimeoutMillis, no limit (connect-timeout) caFile?: string; // PEM file read into ssl.ca (ca-file)};
interface PostgresJournalOptions extends PostgresConnection { eventsTable?: string; // default 'events' tagsTable?: string; // default '<eventsTable>_tags' autoCreateTables?: boolean; // default true}interface PostgresSnapshotStoreOptions extends PostgresConnection { snapshotsTable?: string; // default 'snapshots' keepN?: number; // keep newest N per pid; default 3, <=0 keeps all autoCreateTables?: boolean;}interface PostgresDurableStateStoreOptions extends PostgresConnection { table?: string; // default 'durable_state' autoCreateTables?: boolean;}Table names come from config (not user input) and are validated against a
safe-identifier pattern; everything else — persistenceIds, tags, payloads
— is passed as bind parameters ($1, $2, …), never string-concatenated.
The connection is validated when the store is built, and one combination is
refused that used to pass: a poolConfig.ssl beside a url (or a
poolConfig.connectionString) that carries an ssl parameter. node-postgres
assigns the TLS settings it parses from the connection string over the config
object, so the ssl object was never merged but replaced — run against the
driver, a CA beside sslmode=verify-full was dropped and beside
sslmode=no-verify verification went off with it. Configure TLS in one of the
two places.
Schema
Section titled “Schema”With autoCreateTables (the default), the backend runs
CREATE TABLE IF NOT EXISTS when the store opens — at startup, or on first
use when the boot-time open is turned off:
CREATE TABLE events ( persistence_id TEXT NOT NULL, sequence_nr BIGINT NOT NULL, payload TEXT NOT NULL, -- JSON tags TEXT, -- CSV (also mirrored into events_tags) timestamp BIGINT NOT NULL, PRIMARY KEY (persistence_id, sequence_nr));CREATE TABLE events_tags ( -- indexed tag lookups for projections persistence_id TEXT NOT NULL, sequence_nr BIGINT NOT NULL, tag TEXT NOT NULL, timestamp BIGINT NOT NULL, PRIMARY KEY (tag, timestamp, persistence_id, sequence_nr));CREATE TABLE snapshots ( persistence_id TEXT NOT NULL, sequence_nr BIGINT NOT NULL, payload TEXT NOT NULL, timestamp BIGINT NOT NULL, PRIMARY KEY (persistence_id, sequence_nr));CREATE TABLE durable_state ( persistence_id TEXT PRIMARY KEY, revision BIGINT NOT NULL, payload TEXT NOT NULL, timestamp BIGINT NOT NULL);Pre-provision these (and grant only INSERT/SELECT/UPDATE/DELETE) and set
autoCreateTables: false if your DB role can’t run DDL. With it off, the
store sends a SELECT 1 where it would have run the DDL, so it still reaches
the database when it opens.
Tag queries
Section titled “Tag queries”events_tags is the index behind PersistenceQuery’s by-tag methods.
Its primary key leads with (tag, timestamp, …), so a by-tag read walks
one contiguous range of that index and then joins back to events for
the payload — cost proportional to the tag’s own history rather than to
the journal.
PostgresQuery is what reads it. Wrap the journal instance your actors
write to, then hand the query to a projection — see
Projections for the remaining fields:
import { PostgresJournal, PostgresJournalOptions, PostgresQuery } from 'actor-ts/persistence';
const journalOptions = PostgresJournalOptions.create().withUrl(process.env.DATABASE_URL!);const eventsJournal = new PostgresJournal(journalOptions);const query = new PostgresQuery(eventsJournal);Three filter shapes, three plans:
| Filter | What runs |
|---|---|
'type:Order' / { all: [...] } | index range walk on the first tag, remaining operators refined in process |
{ any: [...] } | t.tag IN (…) with DISTINCT, so an event carrying several listed tags comes back once |
{ not: [...] } alone | no selective tag to seed a walk — falls back to scanning the journal |
Reaching for InMemoryQuery here instead is not wrong, only slow: it
replays every persistence id on every poll. See
Persistence query.
Concurrency model
Section titled “Concurrency model”- Journal append runs
SELECT MAX(sequence_nr)and the inserts inside one transaction; the caller’sexpectedSeqis checked against the current head. A racing writer that slips through trips the primary-key unique constraint (SQLSTATE23505), which is translated toJournalConcurrencyErroras a backstop. An engine that aborts the loser for contention before the key is checked (40001/40P01— reachable atSERIALIZABLE, and the norm on the wire-compatible engines) gets the same treatment, but only once a re-read confirms the head moved: an ordinary lock problem stays aJournalErrorrather than becoming a retry loop. - Durable-state CAS uses the
revisioncolumn: a create (expectedRevision === 0) isINSERT … ON CONFLICT DO NOTHING, and an update isUPDATE … WHERE revision = expected. Zero rows affected ⇒DurableStateConcurrencyError, with the current revision read back for the caller.
BIGINT columns come back from pg as strings; the backend coerces
sequence_nr / revision / timestamp to number at the mapping
boundary.
Pitfalls
Section titled “Pitfalls”Where to next
Section titled “Where to next”- MariaDB — the MySQL-family sibling.
- Cassandra journal — distributed, for scale beyond a single relational instance.
- SQLite journal — single-node, no server.
- Durable state — the state-oriented alternative to event sourcing.
- Snapshots — bound the recovery scan.
