TypeORM
The TypeORM StateStore adapter. Register the durable entities on your DataSource, pass it to TypeOrmStateStore, and run on Postgres, MySQL/MariaDB or SQLite — with auto-schema on boot or an ensureTypeOrmDurableSchema helper for your own migration.
@dudousxd/nestjs-durable-store-typeorm persists runs and step checkpoints through TypeORM, on
any dialect it supports — Postgres, MySQL/MariaDB, SQLite. It declares typeorm as a peer and
rides the DataSource you already configure.
pnpm add @dudousxd/nestjs-durable-store-typeorm1. Register the durable entities
The adapter uses dataSource.getRepository(...) for each durable table, so its entities must be
registered on your DataSource. The package exports them as ENTITIES:
import { DataSource } from 'typeorm';
import { ENTITIES as DURABLE_ENTITIES } from '@dudousxd/nestjs-durable-store-typeorm';
export const dataSource = new DataSource({
type: 'postgres',
// …host, database, etc.
entities: [...DURABLE_ENTITIES, /* your own entities */],
});ENTITIES is the five durable_* entities the engine owns — WorkflowRunEntity,
StepCheckpointEntity, RunAttributeEntity, SignalWaiterEntity, BufferedSignalEntity.
Column naming
ENTITIES uses the canonical snake_case columns. To read a table an older, unpinned setup wrote in
camelCase, or to supply a custom mapping, build the schemas with durableEntities({ naming }) instead:
import { durableEntities } from '@dudousxd/nestjs-durable-store-typeorm';
export const dataSource = new DataSource({
type: 'postgres',
entities: [...durableEntities({ naming: 'snake_case' }), /* your own entities */],
});naming accepts 'snake_case' (default), 'preserve' (the legacy camelCase this adapter used to
produce), or (property: string) => string. Same contract as the MikroORM adapter's
durableEntities — the physical column names must agree
across adapters so a run written by one store stays readable by another.
Database schema
By default the tables live in the connection's current schema (Postgres) or database (MySQL). To keep
them in one of their own, build the entities and the store with the same schema:
TypeOrmModule.forRoot({
// ...
entities: [...durableEntities({ schema: 'durable' })],
});
new TypeOrmStateStore(dataSource, { schema: 'durable' });Every statement then names it: "durable"."durable_workflow_runs" on Postgres, and on MySQL the
durable database (`durable`.`durable_workflow_runs`). Auto-schema creates the schema (or
database) when it is missing; the role needs CREATE for that. If the store's schema doesn't match
the entities', ensureSchema() fails and says which to change. SQLite has no schemas: there,
schema fails at boot. The name must be a plain identifier of at most 63 characters.
Don't put the tables in another schema with search_path (or a connection's ?schema=). Behind
PgBouncer in transaction mode a SET search_path leaks to other clients' connections. The
schema option writes the schema into every statement instead.
2. Wire the store into the module
TypeOrmStateStore takes the DataSource:
import { DataSource } from 'typeorm';
import { TypeOrmStateStore } from '@dudousxd/nestjs-durable-store-typeorm';
DurableModule.forRootAsync({
inject: [DataSource],
useFactory: (ds: DataSource) => ({
store: new TypeOrmStateStore(ds),
transport,
}),
});Schema: auto on boot, or your own migration
With auto-schema on (the default), the module calls store.ensureSchema(), which runs the
dialect-aware ensureTypeOrmDurableSchema(dataSource) — additive, never destructive. It quotes
identifiers per driver, uses varchar(191) for keyed columns (MySQL can't index a text column)
and longtext for the free-form JSON payloads on MySQL (its text caps at 64 KB and would
silently truncate a large fan-out step's events).
To own the schema yourself, disable it and call the helper from a migration:
import { ensureTypeOrmDurableSchema } from '@dudousxd/nestjs-durable-store-typeorm';
export class AddDurableTables implements MigrationInterface {
async up(q: QueryRunner) {
await ensureTypeOrmDurableSchema(q.connection);
}
}DurableModule.forRoot({ store, transport, autoSchema: false });Postgres: the owed-lifecycle index
The timer poller lists the settled runs that still owe a lifecycle event (tag
durable:lifecycle:pending) every 10 s. A tag filter is a leading-wildcard LIKE, which no B-tree
serves, so on Postgres the schema helper adds a partial index over just those rows:
CREATE INDEX CONCURRENTLY IF NOT EXISTS "durable_runs_lifecycle_pending_idx"
ON "durable_workflow_runs" ("created_at") WHERE "tags" LIKE '%"durable:lifecycle:pending"%';It is built CONCURRENTLY (writes go on during the build), or plainly when the connection is inside
a transaction block. An invalid leftover of a build that died is rebuilt on the next boot, and a
build that fails is warned and retried on the next boot. The listing sends that predicate as a
literal, so every plan can use the index. MySQL has no partial indexes and SQLite's would only match
the exact predicate text, so both keep the scan, once per 10 s per instance.
MySQL timestamp precision and large tables
Every timestamp column is created with microsecond precision: datetime(6) on MySQL (timestamptz
on Postgres already is). A bare MySQL datetime holds whole seconds and rounds the milliseconds
away, which moves lease expiry, wakeAt and buffered-event order by up to half a second: a timer can
fire early, and an engine can take a lease it acquired just after booting for one left by its
previous process.
Durable tables created by an older version on MySQL hold plain datetime, so the first boot on this
version changes those columns to datetime(6). MySQL cannot do that type change in place: it copies
the table and blocks writes to it until the copy finishes. On a small table that takes moments;
on a large durable_step_checkpoints it can take minutes, stall every run, and get the pod killed by
its probes halfway through (rolling the change back, to restart on the next boot). So the heal only
runs a column type change on an existing table whose estimated row count
(information_schema.tables.table_rows) is at most blockingAlterRowLimit (default 100000). On a
bigger table it skips the change and logs it instead, one ALTER per table (all of a table's
columns change in one statement, so the table is copied once):
[nestjs-durable] store-typeorm did NOT apply 2 durable-schema column type change(s) at boot.
MySQL rebuilds a table to change a column type and blocks writes to it until the copy ends, and these tables hold more than blockingAlterRowLimit (100000) rows:
-- durable_step_checkpoints, ~2400000 rows
ALTER TABLE `durable_step_checkpoints` MODIFY COLUMN `wake_at` datetime(6) NULL, MODIFY COLUMN `enqueued_at` datetime(6) NULL, MODIFY COLUMN `started_at` datetime(6) NOT NULL, MODIFY COLUMN `finished_at` datetime(6) NOT NULL;
-- durable_workflow_runs, ~145000 rows
ALTER TABLE `durable_workflow_runs` MODIFY COLUMN `wake_at` datetime(6) NULL, MODIFY COLUMN `locked_until` datetime(6) NULL, MODIFY COLUMN `created_at` datetime(6) NOT NULL, MODIFY COLUMN `updated_at` datetime(6) NOT NULL;
Run them in a maintenance window or with an online schema change tool (gh-ost, pt-online-schema-change), or raise blockingAlterRowLimit to let a boot run them. …The store keeps working on the old columns meanwhile, and the warning repeats on every boot until the
column matches. Run the logged statement yourself (in a maintenance window, or with gh-ost /
pt-online-schema-change to keep the table writable), or raise the limit to let a boot do it:
new TypeOrmStateStore(dataSource, { schemaBlockingAlterRowLimit: Number.POSITIVE_INFINITY });
// or, from a migration / script:
await ensureTypeOrmDurableSchema(dataSource, { blockingAlterRowLimit: Number.POSITIVE_INFINITY });Postgres and SQLite need no change.
Schema repair warning
When ensureTypeOrmDurableSchema changes a durable schema that already existed (it creates a table
that was missing while the others exist, adds a column, creates an index, or widens a MySQL JSON
column from text to longtext), it logs one warning that lists each change:
[nestjs-durable] store-typeorm repaired the durable schema at boot: created table
durable_schedules; added column durable_workflow_runs.origin; created index
durable_runs_namespace_status_idx on durable_workflow_runs. The database had drifted from the
schema this library version expects … add a migration that calls
`ensureTypeOrmDurableSchema(queryRunner.connection)`. …It means the database was behind the library, the boot fixed it, and your migration history doesn't
know. Add a migration that calls ensureTypeOrmDurableSchema(q.connection) so the change is recorded
(it is idempotent, so on an already-repaired database it does nothing). An already-current schema
logs nothing. A fresh install (no durable table existed yet) also logs nothing, because creating
every table on the first boot is expected, not drift. The MySQL widen now runs only for columns that
are not longtext yet, so a current schema issues no ALTER at all.
The warning goes to console.warn by default. To send it to your own logger, pass anything with a
warn(message) method (Nest's Logger works):
new TypeOrmStateStore(dataSource, { schemaLogger: new Logger('DurableSchema') });
// or, from a migration / script:
await ensureTypeOrmDurableSchema(dataSource, { logger });Two gaps versus the MikroORM adapter, worth knowing before you pick this one:
- No
withScope. This adapter doesn't implement the tenant-namespace-scoped-view capability, soDurableModule'sscopeReads: trueoption is a silent no-op here — the store keeps returning every namespace's runs regardless of the setting. Only the MikroORM adapter honors it today. - No fingerprint gate.
ensureTypeOrmDurableSchemare-runs itsCREATE TABLE IF NOT EXISTS/ALTER TABLE ... ADD COLUMNdiff on every boot, unconditionally — there's no marker-table short-circuit like MikroORM'sdurable_schema_metafingerprint check. It's a much lighter diff than MikroORM's whole-schema introspection (this one only ever touches the durable tables), but it's still real DDL-planning work repeated on every pod's every boot rather than skipped on a steady-state boot where nothing changed.
MikroORM
The reference StateStore adapter. Register the durable entities with your MikroORM config, pass the ORM to MikroOrmStateStore, and run on Postgres, MySQL or SQLite — with auto-schema on boot or an ensure* helper for your own migration.
Prisma
The Prisma StateStore adapter. Add the durable models to your schema.prisma, prisma generate, and pass your PrismaClient to PrismaStateStore. Schema is owned by Prisma Migrate — there is no auto-schema.