Aviary
State stores

Overview

Where durable state lives. A StateStore interface with MikroORM, TypeORM, Prisma and Drizzle adapters that run on Postgres, MySQL, SQLite or libSQL, an in-memory store for tests, and auto-schema on boot (opt-out, with a migration helper).

A state store persists workflow runs and step checkpoints — the source of truth for both durability and the dashboard. It's a pluggable StateStore interface, independent of the transport.

Writing a custom store? The interface includes renewRunLock(runId, owner, leaseUntilMs) (for lease renewal while a run executes) and listPendingRuns(limit) (so workers can poll for pending runs to dispatch). All bundled adapters implement both.

It also declares runFacets(query) — (status, origin) counts, which is what lets the console page its run list while its chips keep reporting the whole set. That one is optional: a store that omits it still works, with the caller falling back to counting a full listing. Every bundled adapter pushes it down to a GROUP BY, and RunQuery.origin accepts null there and in listRuns to select the runs carrying no origin at all.

runValueFacets(axis, query, opts?) is optional in the same way: the distinct VALUES of one filter axis with counts, which is what lets a console offer a picker instead of a text box. A store that omits it leaves those controls as free text. Every bundled adapter answers the run-table axes with a GROUP BY; tag and the search-attribute axes are counted over a bounded scan, since their values live outside the row being counted.

Writing a custom store: the fan and hot-path methods

Several StateStore methods exist only to keep wide fans and busy deployments cheap. All but one are optional, and the engine falls back to something slower but correct when a store leaves one out. Run the shared store contract (runStateStoreContract) against your adapter. Its listDueTimers case checks the ordering and the limit. Its cases for listOrphanedRuns, updateRunIf, countCheckpoints, hasCheckpoints, getCheckpoints, saveCheckpoints, saveCheckpointIfPending, saveCheckpointsIfPending, settleCheckpointsIfPending, getCheckpointsForSettle, listCheckpointsForReplay, registerChildWaits, listCheckpointsByNamePrefix, getRuns, checkpointStats and queryCheckpoints expect the method to exist, because every bundled adapter has it: a custom store that leaves one out fails those cases even though the engine would fall back.

MethodRequired?What the engine uses it forWithout it
listDueTimers(nowMs, namespace?, limit?)required; honoring limit is optionalthe due-timer pass. Return the most overdue first (wakeAt ascending), at most limit runs. The engine passes its timerBatchSize (default 500).A store that ignores limit still works; every instance then loads the whole due set on each tick.
listOrphanedRuns(nowMs, limit, namespace?)optionalthe periodic recovery pass. Return the running and cancelling runs whose lease is free (lockedUntil null or <= nowMs), oldest createdAt first, at most limit (the engine asks for 500), restricted to namespace when given. On a healthy fleet that is about zero rows per tick.The engine lists every incomplete run with listIncompleteRuns on every tick, on every worker, and drops the leased ones in memory.
updateRunIf(runId, expectedStatuses, patch)optionala compare-and-set on the run's status: apply patch only while the run's status is one of expectedStatuses, and resolve whether it wrote (a missing run resolves false, never throws). A turn settles its outcome (completed, failed, suspended, blocked) through it, so a run that reached cancelled, completed or dead through another path while the turn ran (an operator's cancel(), a timeout sweep, a dead-letter) keeps that state. The predicate must be in the UPDATE … WHERE itself.The engine re-reads the run and then writes, which narrows the race to the gap between the two but cannot close it.
hasCheckpoints(runId, fromSeq, toSeq, statuses)optionala step fan's join barrier asks, once its queue of waiting results drains, whether any checkpoint in the fan's seq range is still pending. Read from the top of the range down and stop at the first match: a fan's steps are dispatched in seq order, so its highest seqs settle last and the answer comes from the first rows read. An empty statuses answers false.The engine asks countCheckpoints instead.
countCheckpoints(runId, fromSeq, toSeq, statuses)optionalhow many checkpoints in a seq range have one of statuses; the barrier's fallback when a store has no hasCheckpoints. Must be a COUNT, not a load. An empty statuses counts 0.The engine loads the run's checkpoints and counts in memory, each time it asks.
getCheckpoints(runId, seqs)optionalthe run's checkpoints at seqs, in seq order, leaving out a seq with none. The engine reads a batch of one run's step results' checkpoints with one call, and the turn that joins a step fan re-reads, 1,000 seqs a call, only the fan steps its replay snapshot does not hold settled.One getCheckpoint per result; the joining turn lists every checkpoint of the run.
saveCheckpoints(checkpoints)optionalsaveCheckpoint for many rows in a few statements and one transaction (a rejection writes nothing). The engine writes a step fan's new pending checkpoints in rounds of up to 2,000, one call per round, and dispatches each round once its call resolves, while the next round is written.One saveCheckpoint per step of the fan.
saveCheckpointIfPending(checkpoint)optionala compare-and-set: overwrite (runId, seq) only while the stored row is still pending, and resolve whether it wrote. Used to settle a step from its result (which also drops a duplicate delivery), to stamp a redispatch deadline, and to re-dispatch.The engine uses saveCheckpoint, which keeps the race where a turn writes a settled step back to pending and the step runs twice.
saveCheckpointsIfPending(checkpoints)optionalsaveCheckpointIfPending for many rows in one call, resolving one boolean per entry in input order. It must give the same answers as calling saveCheckpointIfPending on each entry in turn: a second entry for the same row is compared against the first one's write. Each row's compare-and-set stays atomic, and so does the call: if it rejects, it wrote nothing. The engine settles a batch of one run's step results with one call, so it should be a few statements per batch (the bundled stores lock the still-pending rows with one read and write the winners with one multi-row write), not one per row.One saveCheckpointIfPending per result.
settleCheckpointsIfPending(settlements)optionalsettles steps from their results: per entry and in input order, while the row at (runId, seq) is still pending, write only the columns a result changes (status, output, error, events, startedAt, finishedAt; an absent one is stored empty) and leave every other column, input among them, as it is stored. Resolves one boolean per entry. Claims like saveCheckpointsIfPending: a second entry for a row the first settled loses, and a rejection writes nothing. The engine settles a batch of one run's step results with one call (a single result too), so a step whose input is large, such as an LLM step carrying its whole prompt, does not have that input written a second time when its result lands.saveCheckpointsIfPending (or saveCheckpointIfPending per result) with the whole rows, input included.
getCheckpointsForSettle(runId, seqs)optionalthe rows getCheckpoints returns, each without its input, left out of the query itself. A step result's settle reads the step's row for its status, name, group and timings only, so an LLM step's prompt is not read back when its answer lands. The engine reads through it only when the store also has settleCheckpointsIfPending: the whole-row write it otherwise falls back to needs the input.getCheckpoints (or getCheckpoint per result), input included.
listCheckpointsForReplay(runId)optionalthe replay snapshot every turn of a run reads: the rows listCheckpoints returns, in the same order, except that a completed row comes without its input. Leave the column out of the query itself; dropping it after the read saves nothing. A row that is not completed (still pending, running, or failed) keeps its input, since a re-dispatch or a retry writes it again. Replay needs a completed step's output only, so a conversation whose every turn is an LLM step does not re-read every earlier prompt on each resume. The run detail, engine.listCheckpoints, retry and re-dispatch keep reading the full rows.listCheckpoints on every turn, every input included.
hasSignalWaiter(runId, tokenPrefix)optionala child fan's join barrier.The parent replays once per settled child, which is O(N²) over the fan.
registerChildWaits(entries)optionalwrites a child fan's waiters and running placeholders in one transaction, 500 at a time.Waiters and placeholders are written one by one.
compactCheckpoints(runId, fromSeq, toSeq, into)optionalfolds a settled child fan (or wave) of 100+ into one fan: checkpoint.Settled fans keep one checkpoint per child.
listCheckpointsByNamePrefix(runId, prefixes)optionalreads a fan's existing checkpoints in one prefix query.listCheckpoints plus a prefix filter in memory.
listSignalWaitersByRun(runIds)optionalrun-scoped waiter reads (run detail, cancel, purge, the timer pass).Those reads scan every waiter.
getRuns(runIds)optionalthe runs with these ids that exist, in one IN (...) read; the engine passes at most 500. A replaying fan reads which of its children exist (to start the missing ones) and which already finished (to settle a completion that never reached the parent).One getRun per child, 50 at a time.
checkpointStats(runId, { group? })optional, paired with queryCheckpointsthe console's summarized run detail and fan pages, and their ETag. One GROUP BY parallel_group, status, <name kind> returning a CheckpointStat per bucket: count, seq and name bounds, earliest enqueuedAt (read as startedAt when null), start and finish bounds, attempt sum. The name kind is child (signal:child:), folded (fan:), spawn (spawn:) or step.StoreRunGateway reads every checkpoint of the run and summarizes in memory, on every poll. A 40,000-member fan is a full read each time.
queryCheckpoints(runId, { group?, excludeGroups?, statuses?, namePrefixes?, offset?, limit? })optional, paired with checkpointStatsthe rows the summary still needs (those outside wide fans, folded checkpoints, a fan's first 20 failures, the first child edges) and one page of a fan's members. Seq order. excludeGroups keeps ungrouped rows. An empty statuses or namePrefixes matches nothing.Same as above: one full read per detail and per page.

Every bundled adapter (MikroORM, TypeORM, Prisma, Drizzle on SQLite/MySQL and on Postgres, and the in-memory store) implements listDueTimers with limit and ordering and every optional method in the table. A run's own row is written one statement at a time in each: createRun is one INSERT (then the attribute side-table), and updateRun with a patch that does not settle the run is one UPDATE of the patched columns, with no read of the row first and no transaction around it (Prisma's client still wraps each write in a transaction of its own; Drizzle Postgres keeps one when search attributes are written with the row). A run of one step writes its row this way about five times, and each statement holds a pooled connection for a round trip, so a burst of short runs is bounded by them. updateRunIf is a single conditional UPDATE … WHERE id = ? AND status IN (…) in each, and saveCheckpointIfPending a single conditional UPDATE … WHERE status = 'pending', never a read followed by a write, hasCheckpoints one SELECT seq … ORDER BY seq DESC LIMIT 1 over the run's seq range, and countCheckpoints one COUNT(*) over it. saveCheckpointsIfPending is one UPDATE … FROM (VALUES …) WHERE status = 'pending' RETURNING per 500 rows on Drizzle Postgres. On MikroORM, TypeORM and Drizzle SQLite it locks the still-pending rows with one read and writes the winners with one multi-row upsert per chunk, and on Prisma it replaces them with a deleteMany and a createMany. It is one commit per batch either way. settleCheckpointsIfPending has the same shape, but writes only the six result columns: Drizzle Postgres's UPDATE … FROM (VALUES …) sets just those, and the upsert's conflict branch on MikroORM, TypeORM and Drizzle SQLite merges just those (its insert never happens, since the rows are locked). Prisma's client has no multi-row update with a value per row, so its store settles a batch with raw SQL on the models' table and column names, 500 rows a statement, in one transaction: UPDATE … FROM (VALUES …) WHERE status = 'pending' RETURNING on Postgres and SQLite, and on MySQL a SELECT … FOR UPDATE of the still-pending rows followed by one UPDATE … JOIN of the values. A client without $queryRawUnsafe, or on another provider, settles with one conditional updateMany per entry. getCheckpointsForSettle is getCheckpoints' SELECT with every column but input, and listCheckpointsForReplay is one SELECT of every column but input, then one of (seq, input) for the rows that are not completed (by seq, 500 at a time), skipped when there are none.

checkpointStats is one aggregate query. Each SQL store also declares a durable_step_checkpoints_group_idx index on (run_id, parallel_group, seq) for the per-fan reads. MikroORM and TypeORM add it on boot, Drizzle Postgres's DURABLE_PG_DDL creates it IF NOT EXISTS, and Prisma and Drizzle SQLite get it from your next migration.

Two things the store must not try to do in SQL: decide whether a child failed, or count the children a folded checkpoint stands for. Both live in the payload ({ ok: false }, output.values), which a CodecStateStore may have encrypted. Core loads those rows through queryCheckpoints and reads them after decoding. On a collation that ignores case (MySQL's default), the name kind and the namePrefixes match ignore case too. Engine-written names are lower-case, so in practice only a step you named something like FAN:x would be affected.

CodecStateStore exposes an optional method only when the store it wraps has it, so wrapping a store never hides a capability or invents one. It encodes the payload for updateRunIf (like updateRun), for saveCheckpointIfPending and for every entry of saveCheckpointsIfPending and settleCheckpointsIfPending, forwards hasCheckpoints, countCheckpoints and checkpointStats verbatim (none reads a payload), decodes the rows queryCheckpoints, getCheckpointsForSettle and listCheckpointsForReplay return, and decodes the runs listDueTimers and listOrphanedRuns return.

Adapters

Each adapter has its own page with the full setup — register/copy the schema, wire the store, and own migrations:

StoreDatabaseSchema
InMemoryStateStore (in core)——For tests and local dev. Not durable.
MikroORMPostgres · MySQL · SQLiteauto-schema or ensure*The reference adapter.
TypeORMPostgres · MySQL/MariaDB · SQLiteauto-schema or ensure*Register ENTITIES on your DataSource.
Prismaany Prisma datasourcePrisma MigrateAdd the models, prisma generate, pass your PrismaClient.
DrizzleSQLite / libSQL (Turso, edge)drizzle-kitBuild your db with the package's schema.
Drizzle (Postgres)PostgreSQLdrizzle-kit or auto-schema@dudousxd/nestjs-durable-store-drizzle/pg — any drizzle Postgres driver.

The MikroORM and TypeORM adapters work on any SQL database their ORM supports — Postgres, MySQL or SQLite (timestamps use native datetime columns, so epoch values never overflow). The quickest wire is one factory:

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

DurableModule.forRootAsync({
  inject: [MikroORM],
  useFactory: (orm) => ({ store: new MikroOrmStateStore(orm), transport }),
});

Auto-schema

For the MikroORM, TypeORM and Drizzle (Postgres) adapters, the module creates the durable tables on boot (durable_workflow_runs, durable_step_checkpoints, durable_run_attributes, durable_signal_waiters, durable_buffered_signals) — zero setup in dev. Turn it off in production and own the schema via a migration:

DurableModule.forRoot({ store, autoSchema: false });

Each of those adapters exports the exact function to call from your own migration — ensureMikroOrmDurableSchema(orm), ensureTypeOrmDurableSchema(dataSource) and ensureDrizzlePgDurableSchema(db) (whose SQL is also exported as DURABLE_PG_DDL). See the MikroORM and TypeORM pages for the full migration snippets. It only ever adds the durable tables — it never touches yours.

The Prisma and Drizzle (SQLite) adapters have no auto-schema: their ORMs already own your schema and migration history, so you create the durable tables with prisma migrate / drizzle-kit (the autoSchema option is a no-op for them). The Drizzle Postgres store supports both: re-export its pgTables into your drizzle-kit schema, or let auto-schema create the identical tables.

Column naming

All four adapters agree on physical column names for the durable_* tables so a run written by one is readable by another. The MikroORM and TypeORM adapters expose this as an explicit choice — durableEntities({ naming }) — rather than leaving it to the host ORM's naming strategy, which is what silently diverged the adapters in the past:

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

entities: durableEntities({ naming: 'snake_case' }); // default; or 'preserve', or a (property) => string fn

'snake_case' is the default and canonical (matched by the Prisma and Drizzle schemas too). 'preserve' keeps the camelCase property name verbatim — only for reading a table an old, unpinned TypeORM/Prisma adapter produced. See the MikroORM and TypeORM pages for the full signature.

Exactly-once DB writes with ctx.transaction

A plain ctx.step is at-least-once: if the process dies after the step's business write commits but before its checkpoint does, the step re-runs on replay. ctx.transaction(name, fn) closes that gap by writing the business row and the checkpoint in the same store transaction, so they commit or fail together:

await ctx.transaction('create-order', async (tx) => {
  await this.orders.insert(tx, { id: orderId, total }); // your write, on the store-native tx handle
  // checkpoint commits atomically with the write above — never done-but-unrecorded
});

fn receives the store-native transaction handle (a TypeORM/MikroORM EntityManager, a Prisma tx client, or a Drizzle tx) — run your own writes on it, not on your app's regular connection. Needs a SQL store that implements transaction() (all four bundled adapters do); throws on a store that doesn't.

Encrypting payloads

CodecStateStore wraps ANY store and runs run/step payloads (input/output) through a PayloadCodec — encoded on write, decoded on read — so they're never persisted in the clear. Metadata the dashboard and queries need (id, status, workflow, tags, timestamps) is left untouched, and by default so are the structured error and step events (see Coverage):

import { CodecStateStore } from '@dudousxd/nestjs-durable-core';

const store = new CodecStateStore(new TypeOrmStateStore(dataSource), {
  encode: (value) => aesEncrypt(value),
  decode: (value) => aesDecrypt(value),
});

DurableModule.forRoot({ store, transport });

Both encode/decode are synchronous — wrap an async KMS call yourself if you need one. It's adapter-agnostic, so it composes with any of the four stores.

Coverage

A third constructor argument picks what goes through the codec:

const store = new CodecStateStore(inner, codec, { coverage: 'extended' });
Field'payloads' (default)'extended'
Run input / outputencodedencoded
Checkpoint input / outputencodedencoded
Schedule spec.input, buffered signal and event payloadsencodedencoded
Checkpoint events (step logs, sub-step outcomes)clearencoded
Checkpoint errorclearencoded
Run errorclearencoded
Ids, status, workflow, version, tags, search attributes, namespace, origin, timestamps, leasesclearclear

The default is 'payloads', which is how the wrapper has always behaved. It leaves step logs and error messages (message, stack, details) as written, so a step that logs or throws sensitive data stores it in the clear. 'extended' covers those too, on every write and read path: createRun, updateRun, updateRunIf, the checkpoint saves (plain, if-pending, batched, inside transaction), registerChildWaits, compactCheckpoints, and every run and checkpoint reader. Queryable metadata stays clear in both modes, so filters, facets and the dashboard keep working. A patch with error: undefined still clears the error.

Only turn on 'extended' on a fresh table, or with a codec whose decode recognizes its own ciphertext and returns anything else unchanged. Rows written before the switch hold events and error as plaintext, and a decode that can't tell the two apart will garble them on read.

Retention & pruning

Terminal runs (completed, failed, cancelled, dead) otherwise accumulate forever. The retention module option sweeps them on an interval, hard-deleting whatever falls outside your policies:

DurableModule.forRoot({
  store,
  transport,
  retention: {
    sweepInterval: '1m',
    batchSize: 1_000,
    policies: [
      { statuses: ['completed', 'cancelled'], maxAge: '14d', maxCount: 200 },
      { statuses: ['failed'], maxAge: '90d' }, // keep failures longer for debugging
    ],
  },
});

Each RetentionPolicy targets a set of terminal statuses (disjoint per scope — a policy can be confined to a namespace, tags, workflows or search attributes); a run is kept only while it satisfies every bound you set on its status (maxAge, maxCount, or both — the most-restrictive wins) and is pruned the moment it violates one. sweepInterval: 0 runs the sweep once on boot only. Pruning needs the store to implement pruneTerminalRuns — optional on StateStore, so a custom store without it no-ops with a warning instead of failing boot. Every bundled adapter implements it, along with the bulk deleteRuns behind engine.purgeRuns (see Retention).

withScope is MikroORM + Drizzle (Postgres) only. Multi-tenant setups can turn on scopeReads: true (with namespace set) to confine the operator's own reads to one tenant. The module applies this by asking the store for a scoped view via an optional withScope(scope) capability — today only the MikroORM and Drizzle Postgres adapters implement it. Against TypeORM, Prisma or Drizzle (SQLite), scopeReads silently has no effect: the store keeps returning every namespace's runs. If you need tenant-scoped reads on one of those adapters, scope the query yourself rather than relying on scopeReads.

On this page