Aviary
State stores

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.

@dudousxd/nestjs-durable-store-mikro-orm is the reference adapter — the one every other store is checked against. It persists runs and step checkpoints through MikroORM, on any driver MikroORM supports (Postgres, MySQL, SQLite), using native datetime columns so wakeAt and timestamps never overflow.

pnpm add @dudousxd/nestjs-durable-store-mikro-orm

It declares @mikro-orm/core as a peer — it rides the MikroORM instance you already configure.

1. Register the durable entities

The adapter reads and writes through MikroORM repositories, so the durable entities must be part of your ORM's entity set. The package exports them as ENTITIES:

mikro-orm.config.ts
import { ENTITIES as DURABLE_ENTITIES } from '@dudousxd/nestjs-durable-store-mikro-orm';

export default defineConfig({
  // …your driver, dbName, etc.
  entities: [...DURABLE_ENTITIES, /* your own entities */],
});

ENTITIES is [WorkflowRunEntity, StepCheckpointEntity, RunAttributeEntity, SignalWaiterEntity, BufferedSignalEntity, BufferedEventEntity, SignalIdEntity, ScheduleEntity] — the tables the engine owns (durable_workflow_runs, durable_step_checkpoints, durable_run_attributes, durable_signal_waiters, durable_buffered_signals, durable_buffered_events, durable_signal_ids, durable_schedules). They never reference your entities.

Custom repositories

Each entity comes with a repository class, so app code that reads a durable table injects a typed handle instead of passing the entity class to every call:

import {
  WorkflowRunEntity,
  WorkflowRunRepository,
} from '@dudousxd/nestjs-durable-store-mikro-orm';
import { InjectRepository } from '@mikro-orm/nestjs';

@Injectable()
export class RunsService {
  constructor(
    @InjectRepository(WorkflowRunEntity)
    private readonly runs: WorkflowRunRepository,
  ) {}

  failed() {
    return this.runs.findAll({ where: { status: 'failed' } });
  }
}

em.getRepository(WorkflowRunEntity) returns the same thing, correctly typed — the entity declares its repository through MikroORM's [EntityRepositoryType] symbol. The full set is WorkflowRunRepository, StepCheckpointRepository, RunAttributeRepository, SignalWaiterRepository, BufferedSignalRepository and BufferedEventRepository.

They are wired onto the schemas that durableEntities() builds, so they come along with any naming — including a second call with a different mapping. Their bodies are empty: the engine's own reads and writes go through MikroOrmStateStore, and these exist purely as an injectable handle for your code. Subclass one in your app if you want to hang query helpers off it.

Repository reads are ordinary EntityManager reads, so the namespace global filter below applies to them. On an EntityManager that never sets the filter param this is a no-op (you see every namespace, the operator view); on one scoped to a tenant, the repository is scoped with it.

Column naming

ENTITIES is pinned to the canonical snake_case columns. If you need a different mapping — e.g. 'preserve' to read a table an older, unpinned setup wrote in camelCase, or a custom function — build the schemas yourself with durableEntities({ naming }) instead of importing ENTITIES:

import { durableEntities } from '@dudousxd/nestjs-durable-store-mikro-orm';

export default defineConfig({
  entities: [...durableEntities({ naming: 'snake_case' }), /* your own entities */],
});

naming accepts 'snake_case' (default), 'preserve', or (property: string) => string. The mapping is pinned explicitly on the entity schema rather than left to MikroORM's own naming strategy, since depending on the host strategy is what silently diverges the adapters — a run written by MikroORM has to stay readable by TypeORM, Prisma or Drizzle against the same table.

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:

MikroOrmModule.forRoot({
  // ...
  entities: [...durableEntities({ schema: 'durable' })],
});

new MikroOrmStateStore(orm, { schema: 'durable' });

Every statement then names it: "durable"."durable_workflow_runs" on Postgres, and on MySQL the durable database. Auto-schema creates the schema (or database) when it is missing, along with its durable_schema_meta marker table; the role needs CREATE for that. If the store's schema doesn't match the entities', the store fails at construction 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

MikroOrmStateStore takes the MikroORM instance. Inject it and build the store in the factory:

app.module.ts
import { MikroORM } from '@mikro-orm/core';
import { MikroOrmStateStore } from '@dudousxd/nestjs-durable-store-mikro-orm';

DurableModule.forRootAsync({
  inject: [MikroORM],
  useFactory: (orm: MikroORM) => ({
    store: new MikroOrmStateStore(orm),
    transport, // any transport — the store is independent of it
  }),
});

Each store operation runs on a forked EntityManager, so it owns its own unit of work and won't interfere with request-scoped EMs.

Step checkpoints (listCheckpoints, listCheckpointsForReplay, getCheckpoints, saveCheckpoints, saveCheckpointsIfPending, settleCheckpointsIfPending) go through the query builder rather than managed entities: rows are mapped to entity properties with the same type conversions as em.find, but never hydrated into the identity map, and upserts are insert().onConflict().merge(), 500 rows a statement. A wide fan's checkpoints are tens of thousands of rows, and hydrating them cost several times the query; 40,000 rows read in about 0.14 s. Entity lifecycle hooks and EventSubscribers on StepCheckpointEntity therefore don't fire for these calls.

Tenant-scoped reads with withScope

MikroOrmStateStore is the only bundled adapter that implements withScope(scope) — derive a store confined to one tenant namespace, sharing the same underlying connection:

const tenantStore = store.withScope({ namespace: 'acme-corp' });

This is what powers DurableModule's scopeReads: true option: the module receives an already-built store and can't reconstruct it, so it asks for a scoped view through this optional capability. Reads (listRuns, listIncompleteRuns, getRun, …) go through a forked EntityManager with a namespace global filter active; writes bypass MikroORM global filters and are unaffected. Pass { namespace: undefined } to get back the unscoped operator view.

TypeORM, Prisma and Drizzle don't implement withScope — turning on scopeReads against any of them is a silent no-op (the store keeps returning every namespace's runs). This is currently a MikroORM-only capability.

Schema: auto on boot, or your own migration

By default the module calls store.ensureSchema() on boot, which runs MikroORM's schema.updateSchema({ safe: true }) — additive only, it never drops a column. Zero setup in dev.

In production, turn it off and own the schema from a migration. The package exports ensureMikroOrmDurableSchema(orm) so your migration applies the exact same additive update:

import { ensureMikroOrmDurableSchema } from '@dudousxd/nestjs-durable-store-mikro-orm';

export class AddDurableTables extends Migration {
  async up() {
    await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm());
  }
}
disable auto-schema in production
DurableModule.forRoot({ store, transport, autoSchema: false });

It only ever adds durable_workflow_runs, durable_step_checkpoints, durable_run_attributes, durable_signal_waiters, durable_buffered_signals, durable_buffered_events, durable_signal_ids and durable_schedules — your tables are untouched.

The heal is fingerprint-gated

ensureMikroOrmDurableSchema runs on every boot of every pod, and a full heal means getUpdateSchemaSQL({ safe: true }) introspecting the whole database's information_schema (the store typically shares the host app's ORM) before filtering down to the durable tables — expensive to repeat on every steady-state boot. So a marker table, durable_schema_meta, records a SHA-256 fingerprint of the durable entity metadata last applied. On boot the module computes the current fingerprint and compares it to the stored one with two cheap round-trips (a CREATE TABLE IF NOT EXISTS for the marker plus one PK read); if they match, it returns immediately, skipping both the introspection and the collation check below.

Only a fresh database (no marker row yet), an actual entity change, or a hand-bumped internal schema-revision constant triggers the full heal — done under a best-effort advisory lock (MySQL GET_LOCK / Postgres pg_advisory_lock) so concurrent pods don't race the same DDL, with a re-check after acquiring in case a sibling pod already healed while this one waited.

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"::text LIKE '%"durable:lifecycle:pending"%';

Its predicate there is "tags"::text LIKE …, matching the listing. 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 keeps the schema fingerprint unrecorded, so the next boot tries again. 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.

Collation auto-convergence (MySQL/MariaDB)

MikroORM's auto-schema creates tables with the server's default collation (utf8mb4_0900_ai_ci on MySQL 8.4) and ignores the ORM's configured collate option. If your own tables are pinned to a different collation (commonly utf8mb4_unicode_ci via migrations), a JOIN between one of your tables and a durable table throws "Illegal mix of collations". The heal converges this automatically: after creating/extending the durable tables, it reads the ORM's configured collate, checks each durable table's current collation via information_schema.tables, and runs ALTER TABLE ... CONVERT TO CHARACTER SET ... COLLATE ... on any table that doesn't already match.

This is idempotent (already-aligned tables are skipped), non-fatal (a failed CONVERT is logged as a warning, never crashes boot), and a no-op on Postgres/SQLite or when no collate is configured. It only runs as part of a full heal — the fingerprint gate above skips it too on a steady-state boot.

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-mikro-orm 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 `wake_at` datetime(6) null, modify `enqueued_at` datetime(6) null, modify `started_at` datetime(6) not null, modify `finished_at` datetime(6) not null;
  -- durable_workflow_runs, ~145000 rows
  alter table `durable_workflow_runs` modify `wake_at` datetime(6) null, modify `locked_until` datetime(6) null, modify `created_at` datetime(6) not null, modify `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 (the fingerprint marker is not written while a statement is outstanding, so those boots run the full heal rather than the two-query fast path). 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 MikroOrmStateStore(orm, { schemaBlockingAlterRowLimit: Number.POSITIVE_INFINITY });
// or, from a migration / script:
await ensureMikroOrmDurableSchema(orm, { blockingAlterRowLimit: Number.POSITIVE_INFINITY });

Postgres and SQLite need no change.

Schema repair warning

When the heal changes a durable schema that already existed (it creates a table that was missing while the others exist, adds a column or index, changes a column type, or converts a collation), it logs one warning that lists each change:

[nestjs-durable] store-mikro-orm repaired the durable schema at boot: created index
durable_schedules_due_idx on durable_schedules; added column durable_workflow_runs.origin;
converted durable_signal_waiters collation from utf8mb4_0900_ai_ci to utf8mb4_unicode_ci. The
database had drifted from the schema this library version expects … add a migration that calls
`ensureMikroOrmDurableSchema(orm)`. …

It means the database was behind the library, the boot fixed it, and your migration history doesn't know. Add a migration that calls ensureMikroOrmDurableSchema(orm) 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. Because of the fingerprint gate, a column dropped by hand after the marker was written is only noticed on the next full heal: after an upgrade, or after you delete the durable_schema_meta row.

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 MikroOrmStateStore(orm, { schemaLogger: new Logger('DurableSchema') });
// or, from a migration / script:
await ensureMikroOrmDurableSchema(orm, { logger });

On this page