Aviary

Running in production

The operational checklist for taking nestjs-durable from a single dev process to a real deployment — durable store and transport, choosing a topology, lease-based crash recovery, the dead-letter cap, graceful shutdown, replay-safe deploys, producer-only pods, flow control, tenancy isolation, retention, encryption at rest, observability, and schema management.

Everything below works out of the box in a single dev process with zero infrastructure — that's the point of the durability model. This page is the other half: what to change, and what to double-check, before that process becomes a real deployment with multiple replicas, real deploys, and someone else's uptime on the line. Each item says why it matters, shows the config, and links to the page with the full detail.

1. Swap the dev defaults

Two defaults exist purely to make getting-started zero-setup: InMemoryStateStore and EventEmitterTransport. Neither survives a process restart.

  • Store. InMemoryStateStore is exactly what it says — an in-memory Map. A crash or redeploy loses every run. Swap in a real adapter (MikroORM, TypeORM, Prisma, or Drizzle) before anything durability-sensitive ships. See Stores.
  • Transport. EventEmitterTransport dispatches steps in-process — fine for one process, but a @Step handler never runs anywhere else, so there's no cross-process or cross-language worker. Swap in BullMQTransport (Redis) once steps need to run in a separate worker (or a Python worker). See BullMQ / Redis, and Choosing a transport for how BullMQ, SQS, the SQL DbTransport and the event emitter compare.
DurableModule.forRootAsync({
  inject: [MikroORM],
  useFactory: (orm) => ({
    store: new MikroOrmStateStore(orm),
    transport: new BullMQTransport({ connection: { host: 'redis', port: 6379 } }),
  }),
});

2. Pick a topology

Which transport you need depends on where step bodies run, not on how many replicas you have. The durable state (runs, checkpoints, leases, signal waiters, timers, persisted schedules) always lives in the shared store. What a cross-process transport and a control plane add is delivery between processes.

TopologyStoreTransportControl planeWho drives timers, recovery and schedules
(a) One processa real adapterEventEmitterTransportin-process (auto-wired)that process (drive defaults to true)
(b) Several replicas, steps run in the pod that dispatched themone shared storeEventEmitterTransport in each replicanone across pods (see what you lose)every replica left on drive: true
(c) Steps run in a separate worker fleetone shared storeBullMQTransport, SqsTransport or DbTransportBullMQ's built-in one, or an explicit controlPlanethe driving operator pods

(a) Single process

One NestJS app that serves HTTP, runs workflow bodies, and serves its @Step handlers over an in-process EventEmitterTransport. Checkpoints are in your database, so a crash mid-run resumes from the last completed step on the next boot.

Nothing extra has to tick: DurableModule's TimerPoller runs inside the app whenever the instance drives (the default). It runs the pending-run pickup, recoverIncomplete, due timers, execution timeouts, schedules and persisted schedules every timerPollMs (default 1 000 ms). While polls find nothing to do and the instance has a control plane or run queue, the wait backs off to maxIdleIntervalMs (default 5 000 ms), but never past the next due timer or schedule window, and any run event brings it back to timerPollMs. Remember app.enableShutdownHooks() so the drain in Graceful shutdown runs.

(b) Several replicas, steps stay in-process

If every replica runs the same module with the same @Step providers, you do not need a broker to scale horizontally. A ctx.step dispatched over EventEmitterTransport is handled in the pod that dispatched it, and correctness never depended on the transport, because every cross-replica decision goes through the shared store:

  • One executor per run. Every execution (a fresh start, a poll pickup, a signal, a step result, recovery) first takes an atomic lease on the run row (tryLockRun) and renews it every leaseMs / 2. A replica that fails to take the lease does not run the body.
  • Signals. engine.signal(token, payload) takes the waiter row from the store, writes the signal:<token> checkpoint, and resumes the run under a lease on whichever replica received the call. If no run is waiting yet, the payload is buffered in the store and consumed by the next waitForSignal(token). If the run is mid-turn on another replica, the checkpoint is already durable, and the reconcileMs fallback wake is the safety net that re-drives it.
  • Cancellation. A plain cancel(runId) writes cancelled to the run row. A turn still executing on another replica cannot overwrite it: settling a turn never replaces a terminal state reached meanwhile, and a later resume sees the terminal status and stops. cancel(runId, { compensate: true }) persists the non-terminal cancelling status, and recovery re-drives a cancelling run to cancelled, so the undo survives a crash.
  • Timers, recovery, schedules. These are store queries (due timers, orphaned leases, schedule windows) that any driving replica can answer, with the lease again deciding who executes. Pausing a persisted schedule (from the dashboard or engine.schedules.pause) is a store write, so it applies fleet-wide. A static schedules entry is paused in config with paused: true.

EventEmitterTransport doubles as a control plane, but only inside one process. What you give up is everything that is broadcast between processes rather than written to the store:

Without a cross-pod control planeEffect
Lifecycle eventsThe dashboard's live tail and engine.subscribe only see runs executing on the pod that serves them. engine.waitForRun(runId) (and WorkflowService.waitForRun) listens for events plus one initial store read, so it does not hear about a run that settles on another replica and waits until its timeoutMs. MyWorkflow.execute() outside a workflow uses until: 'terminal', which also polls the store every 250 ms, so it still resolves across pods.
Instant cancellationThe cancel is durable either way, but the replica executing the run is not told. Its in-flight turn keeps going until the turn ends and its settle is refused, and engine.onCancel listeners there never fire.
enqueued nudgeA driving pod normally runs a run enqueued elsewhere as soon as the control plane says so. Without it, the run waits for the next timerPollMs tick.

Several driving replicas are safe (every phase leases before it executes), but each one polls the store every tick.

ctx.step over EventEmitterTransport in a fleet

A ctx.step dispatched over EventEmitterTransport lives only in the dispatching pod's memory. If that pod dies mid-step, nothing else holds the job: recovery parks the run suspended on its pending checkpoint, and by design the reconcile re-drive re-suspends a still-pending step rather than re-dispatching it. That is the lost-dispatch case in Retries. Set remoteRedispatchMs (above your longest step, with idempotent steps), use the dashboard's Re-dispatch action, or keep in-process work in ctx.localStep, which simply re-runs on replay.

Also keep every event-emitter replica driving. A drive: false replica registers no @Step handlers, but a resume it triggers itself (an engine.signal it serves, say) still runs the turn there, and a step dispatched from that turn has no local handler: the emitter ignores it and the run waits.

(c) Remote steps across processes

Once step bodies must run somewhere other than the pod that dispatched them (a dedicated worker fleet, a GPU pool, a Python worker), pick a cross-process transport. BullMQTransport implements ControlPlane over Redis pub/sub and the module auto-wires it, so events and cancellation reach every pod. SqsTransport and DbTransport are point-to-point only: pass a separate controlPlane (any ControlPlane, including a BullMQTransport instance used only for that), or accept the losses listed under (b).

// BullMQ: the transport is also the control plane
DurableModule.forRoot({
  store,
  transport: new BullMQTransport({ connection: { host: 'redis', port: 6379 } }),
});

// SQS or SQL: point-to-point transport plus a dedicated broadcast channel
DurableModule.forRoot({ store, transport: sqs, controlPlane: redisControlPlane });

BullMQ is the one to pick for a cross-ecosystem fleet, remote workflows and store-less tenant pods. See Choosing a transport for the full matrix, and Roles & config for thin workers.

Keep workflow bodies off the API pods. By default start() executes a fresh run on the pod that called it. An API pod that should only enqueue sets drive: false, which installs a no-op run dispatcher and leaves the run pending for a driving pod's next poll (or its enqueued nudge). On BullMQ, add consumers: false too, so the pod also stops consuming step results and decisions (see Producer-only processes). Even then, a resume the pod triggers itself (an engine.signal call it handles) executes the body there under the lease.

3. Crash recovery is a lease

Running more than one replica is safe by design, not by convention, but it's worth knowing why before you rely on it:

  • Crash recovery is a lease, not a boot-time sweep. While a run executes, its worker renews a recovery lease every leaseMs / 2. A crashed worker stops renewing, so the lease expires and engine.recoverIncomplete() reclaims the orphaned run — on any instance, not only on the next boot. leaseMs defaults to 30 000 — set it above your longest single resume step, since the lease renews for the run's whole duration, not just its start. Releasing the lease at the end of a turn is best effort: if the store refuses that write (say the connection is stuck in an aborted transaction after the step that failed the run), the engine logs a [nestjs-durable] releasing the lease of run … failed warning and keeps the turn's real outcome. The lease then expires on its own and recovery takes over.
  • recoverIncomplete needs a heartbeat to run periodically, not just at boot. The NestJS TimerPoller calls it every tick (alongside resumeDueTimers/sweepTimeouts) — this is what turns a 30-second lease into a real self-healing loop instead of a recovery that only fires once per deploy. Make sure at least one operator instance drives (runs the module without drive: false) so the poller is actually ticking somewhere. Each pass asks the store only for orphans (listOrphanedRuns: incomplete runs whose lease is free or expired, at most 500 per pass), so a fleet with thousands of healthy running runs costs one indexed query per tick, not a read and a lock attempt per run.
  • Exactly one instance per run, by an atomic lease. StateStore.tryLockRun is how the engine picks a single owner for a running run even with several replicas racing to recover it — there's no split-brain double-resume. Recovery decides on the run as it reads after taking the lease, never on the listing, so a run that suspended or completed in between is left alone.
  • A turn that lost its lease is fenced. If a turn stalls past leaseMs (a blocked event loop, a long GC pause, a store outage that ate its renewals), another instance can take the run over and re-execute it. The stalled instance finds out on its next renewal, which reports the lease gone: from then on that execution is a zombie, and the engine refuses its writes. Its completion, failure, suspension, continue-as-new, saga undo or remote-turn decision is not written. It reports the store's current state instead, and it does not release the lease (that lease belongs to the new owner now). It logs [nestjs-durable] lost the lease of run … while executing it. Steps the zombie already checkpointed stay checkpointed, so the new owner replays them instead of running them again. A renewal that throws (a transient store error) is not treated as a takeover. The fence is per execution: the next execution of that run on the same instance starts clean.
  • A terminal state is final. Settling a turn never overwrites a terminal state reached meanwhile: a cancel or a dead-letter that lands while the body runs survives the turn completing, failing or suspending.
  • A dispatched step is not a crash. A running run with an in-flight remote step (a pending remote checkpoint) has its work on the transport, not in a dead process. Recovery parks it suspended on the reconcile timer instead of counting a recovery attempt, so a healthy run waiting on a slow worker never burns its maxRecoveryAttempts budget.
  • A lost wake still wakes. A run that suspends with no timer of its own (waiting on a signal, a child, or a remote step without timeoutMs) gets a fallback wakeAt reconcileMs later (DurableModule option, default 300 000 = 5 minutes, 0 disables it). The re-drive is an idempotent replay: a dependency still pending re-suspends, a settled one advances.
  • One bad run doesn't stop the sweep. The due-timer and pending-run passes skip a run they cannot resume (a version this pod doesn't have mid-rolling-deploy, say), log [nestjs-durable] could not resume run …; leaving it for another instance, and carry on with the batch. The poller also isolates each phase: a failing recoverIncomplete logs [nestjs-durable] timer poll: recoverIncomplete failed; continuing and the timers, timeouts and schedules of that tick still run, and a failed tick never crashes the pod.
  • Exactly one execution per run inside a process, too. The lease is keyed by instanceId, so it only fences other instances. Within one engine, resumes of a run are serialized: a signal, a late step result, a child wake or an explicit resume() that lands while the run is executing waits for that execution to settle, then re-drives the run once (wakes that pile up meanwhile coalesce into that one re-drive). This is also why instanceId must be unique per process: two processes sharing one share the lease.

By default each replica takes a random instanceId — the identity stamped on recovery leases and worker heartbeats. That's fine, but a stable, human-readable id makes leases and the dashboard's per-worker health legible (you can tell which pod holds a run's lease), so pin it to the orchestrator's pod identity:

DurableModule.forRoot({
  store,
  transport,
  leaseMs: 60_000, // above your longest single resume step
  instanceId: process.env.HOSTNAME, // e.g. the k8s pod name — stable, unique per replica
});

A stable instanceId also shortens recovery after a hard kill. A pod killed without a graceful shutdown (OOM, SIGKILL) leaves its runs running under leases nobody renews. When it comes back under the same instanceId, its first recovery pass reclaims those runs right away instead of waiting up to leaseMs. It only takes back leases that expire before its own boot time plus leaseMs, so they were taken by the previous process, and it skips any run this process is already executing. Other instances still wait for those leases to expire. Every bundled store supports this (through the optional ownedBy argument of StateStore.listOrphanedRuns). A custom store that ignores the argument falls back to waiting for the lease to expire.

This depends on the rule above: a live instanceId must be unique per process. Two processes running under one id at the same time share leases, and a restarted one would take back runs the other is still executing. A pod identity that is reused only after the old pod is gone, like a StatefulSet ordinal or a k8s pod name, is fine. A fixed id shared by every replica is not.

None of this needs configuration beyond picking leaseMs — it's the default behavior of a durable store + DurableModule. Full mechanism: Durability & replay and Reliability.

4. Cap the blast radius: dead-letter poison pills

Self-healing recovery is great until a run is a genuine poison pill — a deserialization bug, a non-deterministic change, an infinite loop — that crashes the process every single time recovery picks it up. Left unbounded, that's a crash loop that takes every other run down with it on every boot.

DurableModule.forRoot({
  store,
  transport,
  maxRecoveryAttempts: 5, // after 5 crash-recoveries, dead-letter the run instead of looping
  deadLetterWorkflow: 'global-dlq', // fallback DLQ handler for workflows without their own
});

maxRecoveryAttempts is unlimited by default — recovery retries forever unless you set it. Once a run exceeds the cap, the engine moves it to the terminal dead status instead of resuming it again: inspectable and retriable from the dashboard, but no longer crash-looping the process. Route dead runs to a handler with engine.onDead, an inline @DeadLetter() method, or the module's deadLetterWorkflow default. See Dead-letter queue.

The budget bounds one crash-loop episode. A retry of a dead or failed run (the dashboard's Retry action, engine.requeue) resets its recoveryAttempts to zero, so the next recovery pass doesn't kill the resurrected run again on the spot. Requeueing a run that is still in flight does not reset it, so the poison-pill bound still holds.

5. Graceful shutdown

On SIGTERM you want the process to stop picking up new runs and let in-flight ones finish — not kill them mid-step and rely on the lease timeout to recover them a leaseMs later.

// main.ts
app.enableShutdownHooks(); // required for Nest's OnApplicationShutdown to fire at all
DurableModule.forRoot({
  store,
  transport,
  shutdownTimeoutMs: 15_000, // wait up to 15s for in-flight runs to settle before exiting
});

Shutdown happens in three steps, in this order (Nest runs every onModuleDestroy before any beforeApplicationShutdown or onApplicationShutdown):

  1. Poller stop (driving operators only). The timer poller stops its interval, tells the engine to stop starting work (beginDrain), and waits for the sweep in flight, up to shutdownTimeoutMs. Nothing it was about to lock or start is started, and no store call from the poll is pending afterwards. A non-driving operator (drive: false, a dashboard) does none of this, so runs started by its finishing requests or beforeApplicationShutdown hooks still execute in process. On a driving operator the engine stops executing newly started runs from this point: they stay pending for another instance's poll or the next boot.
  2. Drain. The module calls engine.drain(shutdownTimeoutMs) — shutdownTimeoutMs defaults to 10 000. Time already spent in step 1 waiting for the timer poll is deducted, so the timer poll's wait and the drain together take at most shutdownTimeoutMs; time that merely passes between them (other hooks, the HTTP server closing) is not charged, and with no poll in flight drain gets the full timeout. The retention sweep's own wait (also bounded by shutdownTimeoutMs) runs concurrently in step 1 and is not deducted, so a slow prune can add up to one more shutdownTimeoutMs before the drain. A drain() you call yourself while the poller is still waiting starts with the full budget and is shortened as soon as the poller reports its wait.
  3. Transport close, bounded separately by the transport's closeTimeoutMs.

drain turns recovery and the pending-run poll into no-ops, so no new run starts, then waits for every currently in-flight execution to settle — up to the timeout — before returning. Transports are closed after the drain, deliberately, so an in-flight run can still dispatch to and await a remote step while it drains. Only after drain resolves (or times out) does the process actually exit.

What this means for a run that's still executing when the timeout is hit: drain just stops waiting — it doesn't cancel anything. The run keeps running until the process is actually killed; if that happens mid-step, the step's result is simply never checkpointed, its recovery lease expires on schedule, and another instance's recoverIncomplete() picks the run back up and replays it from its last completed checkpoint — the same crash-recovery path from #3, just triggered by a deploy instead of an unplanned crash. Set shutdownTimeoutMs above your typical in-flight run duration to make that the rare case rather than the common one.

When the budget runs out, drain releases the recovery leases of the runs still executing, so another instance's next recoverIncomplete() picks them up at once instead of waiting up to leaseMs for the lease to lapse. It logs [nestjs-durable] drain timed out with N run(s) still executing; released their leases … with the run ids. Each of those turns is fenced before its lease is released. Whatever it computes after that is never written over the new owner's work, and a step it still has in flight may run again on the new owner, exactly as after a crash. The release is owner-scoped (StateStore.releaseRunLock(runId, owner)): a lease another instance already took over is left alone. A store adapter that ignores the owner argument releases unconditionally, which is only less precise in that race. The drain runs on every operator, including a drive: false API pod, so runs that pod resumed itself (a signal it handled, say) are waited for as well.

6. Deploys: replay-safety discipline

A workflow body is replayed positionally — the same rule from Durability & replay applies with extra force once real traffic is in flight when you deploy. Three layers catch a breaking change at a different point:

  • Lint at author time. @dudousxd/nestjs-durable-eslint-plugin flags Date.now(), Math.random(), new Date(), crypto.randomUUID() and performance.now() inside a @Workflow run — the most common way a workflow body accidentally goes non-deterministic — before it's ever committed. Wire the rule (or Biome's GritQL plugin) into CI so a slipped call fails the build, not a production replay. See Linting for non-determinism.

  • Regression-test replay before you ship. assertReplayable(register, history) (from @dudousxd/nestjs-durable-testing) replays a captured real run's history against your current workflow code and throws NonDeterminismError if they diverge — catch a shape-breaking change in CI against a committed fixture, instead of an in-flight run in production. There is no export command: a RunHistory is just the run row plus its checkpoints, so capture one from the production store with a small script and commit the JSON. See Replay a captured run in CI.

    // scripts/capture-run.ts: run once against production, commit the output as a fixture
    const run = await store.getRun(runId);
    const checkpoints = await store.listCheckpoints(runId);
    writeFileSync(`test/fixtures/${runId}.json`, JSON.stringify({ run, checkpoints }, null, 2));

    Payloads are captured as stored: wrap the store in the same CodecStateStore (see Encrypting payloads at rest) to read them decoded, and scrub anything sensitive before committing.

  • Version bumps for breaking shape changes. A workflow's @Workflow({ version }) pins every run that starts under it; a run always replays against the version it started on. When a change reorders, inserts, or removes steps, register the new version alongside the old one and keep both until every run that started on the old version has reached a terminal state. For a surgical change, guard the new code with ctx.patched(id) instead of a second body. A pod asked to resume a run whose version it no longer registers throws workflow <name>@<version> is not registered — keep the prior version deployed so in-flight runs can drain (skew protection), and the timer and pending sweeps skip that run, leaving it for a pod that still has the version. See Versioning & determinism and Patching in place.

Deploy workers and the operator/API together when a workflow or its steps changed. Once steps run in a separate process — a BullMQ worker, or a Python worker — that worker's code must agree with the operator's on step names and workflow shape for the run it's replaying. A worker left running an old build after a step was renamed (without a matching @Workflow version bump) can pick up a run and surface a NonDeterminismError, or just hang — the same failure mode documented as a pitfall of a stale local worker in Tenancy. The lint rule and assertReplayable catch the code-level mistake; keeping workers and operator in lockstep on deploy is what keeps a correct version bump from still tripping over a stale process that hasn't picked it up yet.

Singleton workflows tolerate a rolling upgrade. Replicas older than 0.73 admit singleton runs by a scan and write no admission marker. Newer replicas also count an old replica's untagged holder as holding its slot, so they don't start a second run for the key beside it. Old and new replicas can serve singleton workflows side by side while you roll out. While old replicas are still running, the fleet is only as strict as their scan, so finish the rollout. See Store support and upgrades.

7. Producer-only processes

Broker queues are point-to-point: every process that consumes competes for each job. A process that boots DurableModule without being a worker (an API pod, a Nest REPL, a CLI command built with NestFactory.createApplicationContext, a migration or seed script) should say so, or it claims step jobs and results it then dies holding, or runs turns meant for the fleet.

Two options, and a non-worker usually wants both:

  • drive: false stops the instance from driving: no timer poller (so no pending pickup, recovery, timers, timeouts, schedules or retention), no @Step handler registration, no boot-time recovery, and a no-op run dispatcher, so start() only persists the run as pending.
  • consumers: false parks the transport's point-to-point consumers. On BullMQTransport it calls deferConsumers() before the engine subscribes, so step tasks, results, decisions, step events, start-run and run-request jobs stay on the queues for the fleet, and no co-located or thin worker consumer starts. Pub/sub (heartbeats, control, run replies, tenant events) is broadcast and keeps flowing.
// API pods, REPL, scripts: enqueue and read, never consume or drive
DurableModule.forRoot({
  store,
  transport,
  drive: process.env.APP_TYPE !== 'API',
  consumers: process.env.APP_TYPE !== 'API',
});

Ship one config to every pod and flip both with an env var. Only BullMQTransport can defer its consumers. SqsTransport, DbTransport and the in-process transports keep consuming, and consumers: false logs [nestjs-durable] consumers: false — <Transport> cannot defer its consumers and will keep consuming in this process. Call transport.startConsumers() later if the process turns out to be a worker after all. The durable CLI never boots the module (it loads only a store), so it needs neither option. See Producer-only processes and the producer-only row of Choosing a transport.

8. Concurrency and backpressure

Two independent knobs, easy to conflate:

  • Worker/transport concurrency — how many dispatched tasks this process runs at once. On BullMQTransport, concurrency defaults to 1 (one task at a time); pass a fixed number, or 'adaptive' to let an AdaptiveController self-tune the limit from a latency/backpressure gradient and a RAM ceiling instead of you guessing it. See BullMQ / Redis.
  • Admission (durable queues) — a cap or rate limit that ctx.step calls opt into via engine.registerQueue / the module's queues option, independent of how many workers you run. A blocked call re-suspends and the timer poller retries admission later, so the limit survives a crash. See Flow control.
const transport = new BullMQTransport({
  connection: { host: 'redis', port: 6379 },
  concurrency: { mode: 'adaptive', min: 2, max: 32, ramCeilingPct: 85 },
});

DurableModule.forRoot({
  store,
  transport,
  queues: [{ name: 'emails', concurrency: 10, rateLimit: { limit: 1000, periodMs: 3_600_000 } }],
});

By default, admission accounting is per engine instance — a concurrency: 5 queue admits up to 5 per replica, not 5 fleet-wide. For a true cross-instance cap, pass a RedisAdmissionBackend (from @dudousxd/nestjs-durable-admission-redis) as the module's admission option so every replica shares the same Redis-backed accounting. See Local vs. global admission.

For a worker role (a store-less thin worker, or a co-located store + connection process), the concurrency field is the worker consumer's own per-queue limit — it can also be 'adaptive' (see Node worker → Concurrency):

DurableModule.forRoot({
  topology: 'tenant',
  partition: 'acme-corp',
  connection: process.env.REDIS_URL,
  concurrency: { mode: 'adaptive', min: 2, max: 32, ramCeilingPct: 85 },
  concurrencyByHandler: {
    'reports.generate': 2, // a heavy step: keep it low regardless of the global limit
  },
});

concurrencyByHandler (a Record<string, ConcurrencyOption>) gives one queue its own BullMQ concurrency; every other queue keeps concurrency. The key is the exact name string you gave @Workflow({ name }) or @Step(name), namespace and dots included: a workflow declared as @Workflow({ name: 'agent.opencode.run' }) is keyed 'agent.opencode.run', not 'opencode.run' and not its sanitized queue token. It works the same on a co-located worker (store + connection) and a thin worker (connection only). An overridden queue runs on its own controller (an adaptive override tunes that queue alone), and its heartbeat reports that controller's limit and in-flight count. A name this process does not register is ignored, with one warning per name per process.

This is the knob for one interactive workflow among many background ones: with ~20 queues per process and a small database pool, keep concurrency: 1 and raise only the workflow a person waits on.

DurableModule.forRoot({
  store,
  connection: process.env.REDIS_URL,
  concurrency: 1,
  concurrencyByHandler: { 'agent.opencode.run': 4 }, // the exact @Workflow({ name })
});

Tuning for wide fans

A fan of tens of thousands of items stresses different parts of the system than a stream of small runs. These knobs matter, roughly in order:

  1. Fan out steps, not children, when an item is one step. ctx.all(this.lines.process, lines) costs a checkpoint and a dispatch per item; ctx.all(LineWorkflow, lines) costs a whole run per item (row, turn, lease, parent signal). See The same step over many inputs.
  2. Cap the fan with concurrency on the ctx.all call, so the queue and the store do not hold the whole fan at once. Each settled wave costs the parent one turn.
  3. Raise the workers' concurrency (or make it adaptive) so the steps actually run in parallel. Fleet parallelism is concurrency × replicas.
  4. Results need no tuning. Each instance consuming results works on many of them at once (512 on BullMQ, up to 80 on SQS, up to 512 on DbTransport) and settles one run's results in batches: the results that arrive while one batch is being written go into the next, up to 256. A batch is one settleCheckpointsIfPending call (one commit), which writes only what a result changes, never the step's input, and it resumes the run at most once. A step fan's barrier COUNT is read only by a batch with none of the fan's results queued behind it, so under a backlog it is read about once per instance, not once per batch. A step fan's results then cost about one checkpoint read and 1/256 of a commit each. A result is acknowledged only after its batch commits, and a batch the store rejects is retried row by row, so one bad row fails only its own result. See Result concurrency.
const transport = new BullMQTransport({
  connection: { host: 'redis', port: 6379 },
  concurrency: { mode: 'adaptive', max: 64 }, // tasks this pod runs at once
});

Due timers come in batches. Every driving instance runs resumeDueTimers on each timer-poll tick. When thousands of runs come due together (recovery after an outage, a fan's children waking at once), each pass loads at most timerBatchSize of them, most overdue first, and walks them in a shuffled order so instances spread over the batch instead of contending for the same leases. The default is 500. Set it on the module (or on a WorkflowEngine you build yourself). A value that is not a finite number of at least 1 falls back to 500.

DurableModule.forRoot({ store, transport, timerBatchSize: 1000 });

Runs spread over every driving instance. On a transport with a run queue (BullMQ, SQS and the SQL transport), every driving instance consumes that queue, and the runs any instance starts or wakes go through it: a ctx.all / ctx.allSettled fan's children, ctx.child, start, event and schedule triggers, signalWithStart and entity runners, continue-as-new, requeue/retryWithInput, recovery of a crashed run, and the wakes of a suspended run (a signal, a child's completion reaching its parent, a due timer, a freed singleton or queue slot, a lease that came free). Whichever instance has a free slot takes the next run, so a 40,000-child fan executes across the deployment instead of on the instance running the parent. A fan's children reach the broker in bulk writes of up to 500, not one round trip each. Nothing to configure: the Nest module wires the consumer on every driving operator (not on drive: false or a thin worker), and workflow code is unchanged.

The queue holds one entry per waiting run (SQS, which cannot deduplicate, may deliver one twice), and an instance skips an entry whose run another instance already took or that is no longer due. A run whose queueing fails stays pending, and the next poll queues it again, or runs it itself while the broker is down. At shutdown an instance stops taking runs and waits for the ones it holds within shutdownTimeoutMs; what is left in the queue goes to the other instances.

A start re-sent for the same pending state is queued once; a run that went pending again, or a wake, landing while an instance handles the run's previous entry gets another turn after it. A due timer is claimed for one lease period while its wake waits, so the poll does not queue it again; a wake the transport refused resumes the run where it was raised instead of waiting for its timer.

With a run queue, engine.signal (and signalWithStart, an entity operation) resolves once the wake is queued, with the run's status at that moment; use waitForRun for the outcome. Step results and workflow decisions still resume their run where they land: they come off the broker's shared results queues, so they already land on an arbitrary instance.

Each instance stays bounded. One budget of 256 covers everything an instance takes on itself: the runs it takes off the queue, a fan's child starts, and on a transport without a run queue (the event-emitter transport, or a custom one) the runs it starts and those other instances announce as enqueued, which it skips after one read if someone else already took them. 256 is the total, not a per-kind limit. The rest wait, as queue entries or as run ids in memory, while the runs stay pending in the store for any instance's poll.

One instance also never runs two turns of the same run side by side. Wakes that arrive while a turn of the run is executing on it (the last children of a fan settling together, a result and a timer) share one more turn after it, instead of each running its own replay of the fan with every checkpoint loaded.

Lost wakes heal on their own. A crash, an OOM or a scale-down can land between two writes the engine makes in sequence. Each gap has a recovery path that needs nobody:

  • A child persists its end (completed, failed, cancelled or dead) and then tells its parent: ctx.all fails on a child that did not complete, ctx.allSettled reports it as a rejected entry (code cancelled for a cancelled child), and a failFast fan keeps reporting the failure that failed it, not a sibling it cancelled. The notification retries a store error a few times and a graceful shutdown waits for it. If the parent still never hears (the instance went down in between), its next turn reads the children it waits on in batches of 500 and settles every finished one exactly as the notification would have; a child whose read fails is left to the turn after. That turn comes no later than the parent's reconcileMs wake (default 5 minutes), which bounds how long a lost completion can delay its parent, on a deployment where some instance is polling. A notification arriving after that turn leaves nothing behind.
  • A step result is written and then resumes its run. A redelivered result whose step already settled still resumes the run if it is suspended (subject to a step fan's barrier), so the transport's retry of a result whose resume failed now finishes the job. A result whose resume found the run leased by another instance looks again once that lease is free, so a holder that went down mid-turn costs one lease period, not the run's timer.
  • A wake that lands while the run's turn is still executing on another instance (a signal, a child that finished before its parent's turn ended) cannot take the run's lease. It is kept durably for that turn instead, and the run goes again as soon as the turn ends, wherever the wake was received.
  • With remoteRedispatchMs set, a run waiting on a dispatched step parks no later than reconcileMs, not on the redispatch deadline itself, so a lost wake costs minutes, not the hour a long redispatch window allows.

The console summarizes wide fans. The dashboard's run detail folds any fan wider than 50 into one summary row and pages its members on demand, so opening a 40,000-member fan no longer ships every checkpoint to the browser. On a store with checkpointStats and queryCheckpoints (every bundled store) the server does not read the whole run either. It aggregates the checkpoints with one GROUP BY and loads only the rows it shows. For a 40,000-member step fan that is 21 rows per poll instead of 40,001, and a page of 100 members reads 100. An unchanged run answers the next poll with a 304 after reading only the run row and the aggregate. A custom store without the two methods falls back to the full read. See Wide fans.

Remote-worker liveness

When steps or workflows run in a separate (or polyglot) worker, the engine can't tell a slow worker from a dead one by default — it just waits. Set remoteAdvanceSilenceMs on the operator so a remote workflow advance that goes silent longer than the deadline is treated as lost and re-driven by recoverIncomplete; each worker heartbeat rearms the deadline, so an alive-but-slow worker is never re-driven:

DurableModule.forRoot({
  store,
  transport, // BullMQ — remote/polyglot workers
  remoteAdvanceSilenceMs: 30_000, // no decision/heartbeat for 30s ⇒ presume the turn lost, recover it
});

This is the workflow-turn counterpart to a dispatched step's timeoutMs. Leave it unset and a remote advance waits unbounded (correct, but a genuinely dead worker's run stays running until its lease expires). See Cross-ecosystem interop and the Node worker for the worker side.

9. Isolation between environments

If a dev cluster, a staging environment, and developers' local instances ever point at the same store/Redis, an un-namespaced instance is not an isolated observer — it's on the exact same queues and polling the exact same rows as everyone else, and it will steal or drive someone else's runs. namespace (DurableModule.forRoot({ namespace })) partitions both the store's poll paths and the transport's queue/stream/key names, so non-interchangeable pools can safely share one backing database and Redis:

DurableModule.forRoot({
  store,
  transport,
  namespace: process.env.DURABLE_TENANT, // e.g. 'staging', or a developer's own name
});

Omitting namespace makes the instance an operator that drives/recovers/resumes runs of every namespace — that's the shared cluster's control plane, not something to set on a random local process. See Tenancy for the full operator/tenant model and its pitfalls.

10. Retention

Without a policy, completed/failed/cancelled runs accumulate in durable_workflow_runs (and its child tables) forever, and the timer poller's per-tick status scans get linearly slower as that table grows. Set a retention policy on a driving instance to hard-prune terminal history on an interval:

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

Every bundled store adapter implements the bulk prune (a custom store without it no-ops with a warning). Policies can be scoped to a namespace, tags, workflows or search attributes, and engine.purgeNamespace(ns) / engine.purgeRuns(scope) delete a tenant's runs on demand. See Retention for the full policy shape, the sweep interval/batch-size defaults, and how "keep" bounds combine.

Fleet-wide sweeps on one pod

Three sweeps act on the whole fleet's data rather than claiming a run: retention pruning, the stalled-run pager, and the cleanup of buffered child completions no parent will consume. By default every driving pod runs them, which repeats the work, and makes the pager page once per pod.

Import LocksModule from @nestjs/locks with a shared lock store, and durable's sweepers run on one pod:

@Module({
  imports: [
    DurableModule.forRoot({ store, transport, retention, onStalled }),
    LocksModule.forRoot(), // plus your shared LockStore provider (Redis, Postgres): see the official docs
  ],
})
export class AppModule {}

There is nothing to configure on durable's side. At init it looks for Locks and logs which mode is on. Each sweep takes its own lease, durable:retention, durable:stalled-pager or durable:buffered-signals (with :<namespace> appended on a namespaced engine), and keeps it: the official lock renews itself every ttl / 3. The other pods skip that sweep until the holder stops renewing (a crash, or shutdown, where Locks hands the lease back), and the next tick elsewhere takes over. Without LocksModule, or with @nestjs/locks not installed, nothing changes.

Work that claims runs (pending runs, crash recovery, timers, timeouts, schedules, lifecycle events) stays on every pod: each run is already arbitrated by a lease or a compare-and-set.

11. Encrypting payloads at rest

Run and step inputs and outputs are stored as JSON. To keep them out of the database in the clear, wrap the store in CodecStateStore (from @dudousxd/nestjs-durable-core) with your own synchronous PayloadCodec:

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 });

Know what it covers. It encodes run input/output, checkpoint input/output, a persisted schedule's input, and buffered signal and event payloads. It leaves searchable metadata alone (ids, status, workflow, tags, search attributes, timestamps). By default it also leaves the structured error and a step's recorded events alone, so error messages and step logs are stored as written. Pass { coverage: 'extended' } as the third argument to encode step events, step error and run error too, but only on a fresh table or with a codec whose decode passes through values it didn't encode (older rows hold those fields as plaintext). It wraps the store only: tasks and results on the transport (Redis, SQS, the SQL task tables) still carry the plain payload, so protect the broker separately. See Encrypting payloads.

12. Observability

Three views of the same engine lifecycle events, for different jobs:

  • The dashboard (@dudousxd/nestjs-durable-dashboard) is the operating surface — run list, the step graph, retry/cancel/continue actions. Anyone who reaches it can read every run's payloads and retry or cancel it, so set authorize (forRoot({ authorize: { policy: ConsolePolicy, ability: 'view' } }), a function, a class, or authorizeByToken(...)). With NODE_ENV=production, a console with no authorize answers 403 to every request, and a warning is logged at boot. See Protecting the console.
  • OpenTelemetry (@dudousxd/nestjs-durable-otel) turns runs into traces — one root span per run, one child span per step — for the tracing stack you already run. attachDurableOtel(engine) is aimed at debugging production latency and correlation, not at operating a run. Note that the root span ends on suspend and does not reopen on resume, so a workflow that sleeps or waits on a signal shows post-resume steps as detached spans — use the Telescope watcher instead if you need one trace per run across suspends. See OpenTelemetry. The same package also exports attachDurableMetrics(engine) — a dependency-free counter/percentile collector (run/step counts by outcome, p50/p95/max duration) meant to back a /metrics route or a scheduled exporter.
  • Telescope (@dudousxd/nestjs-durable-telescope), if you already run @dudousxd/nestjs-telescope, surfaces durable runs/steps alongside your app's requests and jobs, and its durableTelescopeExtension() adds a health dashboard (success rate, current-state gauges, top failing workflows) driven partly from recent history and partly from live store reads, so the current-state gauges aren't bounded by Telescope's prune window. See Telescope.

Watch for stranded runs. suspended is not an error, so a lost dispatch alerts nobody. There is no stalled-run hook to page on. What exists:

  • The dashboard flags a remote step still pending after 10 minutes as "awaiting worker result — dispatched Nm ago (possibly lost)", and offers a Re-dispatch action (engine.redispatchPending(runId) from code). See Recovering a lost remote step dispatch.
  • Its waiting states show no-worker for a run whose next step has a backlog and zero live workers (BullMQ only, which reports worker health). See Waiting states.
  • remoteRedispatchMs turns the lost dispatch into a self-heal instead of an alert, and a per-step timeoutMs bounds a step that should never take long.
  • engine.onDead fires for every run that crosses maxRecoveryAttempts. Wire it to your pager.

If you need an alert on runs stuck for too long, run a scheduled query against the store yourself (listRuns filtered by status, then compare updatedAt).

When something does go wrong, start from the symptom in Troubleshooting: stuck in suspended, stuck in pending, a run went dead, and steps seem to run twice.

13. Schema management

By default the module calls store.ensureSchema() on boot for the MikroORM/TypeORM adapters — zero setup in dev. For MikroORM specifically, this runs ensureMikroOrmDurableSchema, which is fingerprint-gated: a marker table (durable_schema_meta) records a SHA-256 hash of the durable entity metadata last applied, and a steady-state boot does two cheap round-trips (a CREATE TABLE IF NOT EXISTS plus one PK read) to confirm nothing changed, skipping the expensive whole-database information_schema introspection entirely. Only a fresh database, an actual entity change, or a hand-bumped internal revision constant triggers the full heal — and that heal runs under a best-effort cross-pod advisory lock (MySQL GET_LOCK, Postgres pg_advisory_lock) so concurrent pods don't race the same DDL.

If your environment restricts DDL to migrations (no runtime CREATE TABLE/ALTER TABLE at all), turn auto-schema off and own it explicitly:

DurableModule.forRoot({ store, transport, autoSchema: false });
// in a migration
import { ensureMikroOrmDurableSchema } from '@dudousxd/nestjs-durable-store-mikro-orm';

export class AddDurableTables extends Migration {
  async up() {
    await ensureMikroOrmDurableSchema(this.getEntityManager().getOrm());
  }
}

autoSchema defaults to true. The same additive, non-destructive update runs either way — the auto-boot path and the migration helper call the exact same function, so turning it off changes when it runs, not what it does. See MikroORM store for the full mechanism, including the MySQL/MariaDB collation auto-convergence it also performs during a full heal.

The heal does not announce a successful repair, so there is no "schema was behind" warning to watch for. With autoSchema: false, rerun your migration after every library upgrade. What the MikroORM heal does log, and is worth alerting on in boot logs, are the steps it skipped:

  • could not acquire the durable-schema advisory lock (proceeding without it): concurrent pods may race the same DDL.
  • skipped a non-structural durable-schema statement that failed; the column is left as-is: a type alignment hit data it can't cast. The store still works, but the column hasn't converged.
  • could not align collation for <table>: MySQL/MariaDB collation left as-is, which can surface later as "Illegal mix of collations".

14. Guard the run: input validation & a lifetime cap

Two @Workflow options catch a whole class of production incidents at the boundary rather than deep in a replay — a malformed start payload, and a run that never ends.

Validate start input. A run created with garbage input fails on its first step (or worse, halfway through), long after the caller has moved on. input declares the run's input schema, and the payload is checked against it before the run is created, so a bad request is rejected at start. It takes the same two forms @Step({ input }) does: a Standard Schema (zod 3.24+, valibot, arktype, …) or a class-validator DTO class — the two validation styles NestJS itself supports (StandardSchemaValidationPipe and ValidationPipe).

import { z } from 'zod';

const CheckoutInput = z.object({
  orderId: z.string(),
  amountCents: z.number().int().min(1),
  placedAt: z.coerce.date(),
});

@Workflow({ name: 'checkout', version: '1', input: CheckoutInput })
export class CheckoutWorkflow {
  async run(ctx: WorkflowCtx, input: z.infer<typeof CheckoutInput>) {
    input.placedAt.getTime(); // a real Date, on the first execution and on every replay
  }
}
import { Type } from 'class-transformer';
import { IsDate, IsInt, IsString, Min } from 'class-validator';

class CheckoutInput {
  @IsString() orderId!: string;
  @IsInt() @Min(1) amountCents!: number;
  @Type(() => Date) @IsDate() placedAt!: Date;
}

@Workflow({ name: 'checkout', version: '1', input: CheckoutInput })
export class CheckoutWorkflow {
  async run(ctx: WorkflowCtx, input: CheckoutInput) {
    /* input is a CheckoutInput instance here */
  }
}

A DTO class needs class-validator/class-transformer installed.

The run stores what was sent; the body sees what was parsed. The run's stored input is the payload exactly as the caller sent it. run(ctx, input) receives the schema's parsed value — coerced and transformed — and that value is re-parsed from the stored input before every turn, replays included. A value the stored JSON can't carry (a Date, a DTO instance with methods) therefore reaches the body the same way on every turn. Two rules follow:

  • The schema must be deterministic. No default(() => Date.now()), no random ids: a replay must parse the same value the first execution did.
  • Changing the schema is a breaking change to the workflow — bump version, like any other change to the body (section 6). An in-flight run whose stored input no longer parses fails with code: 'invalid_input'.

Validate the output. output takes the same forms. The value run() returns is parsed before the run completes, and the parsed value is stored as the run's output; a mismatch fails the run with code: 'invalid_output'. Both come from a SchemaValidationError, a FatalError (never retried) whose issues and details.issues list { message, path } for every issue, so an alert or an onError route can match them.

For a rule a schema can't express (a cross-field invariant, an async lookup) add validateInput — a plain (input) => void | Promise<void> that throws to reject. It runs at start after input parses, and receives the parsed value, so it can rely on the types the schema produced:

@Workflow({
  name: 'transfer',
  input: TransferInput,
  validateInput: (input) => {
    const { from, to } = input as { from: string; to: string };
    if (from === to) throw new Error('cannot transfer to the same account');
  },
})
export class TransferWorkflow { /* … */ }

One limit: validation at start needs the @Workflow class in the process that calls start. A control plane that only routes runs to a worker by name can't check the input there, so a bad payload surfaces when the worker runs the body — as a failed run with code: 'invalid_input', not as an error from start.

Cap the lifetime. A workflow that waits on a signal or a child that never arrives will sit suspended forever, holding whatever it holds. executionTimeout bounds a run's total wall-clock life; the timer poller cancels an overrunning run (status cancelled, reason execution_timeout):

@Workflow({ name: 'approval', executionTimeout: '72h' }) // auto-cancel if not settled within 3 days
export class ApprovalWorkflow { /* … */ }

What counts. The clock starts at the run's createdAt, so time spent waiting in the queue counts. Every run that hasn't finished is covered — pending (no worker has picked it up), blocked (no live worker has the capabilities it requires), running and suspended — because a run that never starts is as stuck as one that hangs halfway. Two consequences worth knowing:

  • A run in cancelling is left alone: its saga undo is running, and it ends cancelled on its own.
  • A delayed start (startAt) waits suspended, so its wait counts too. A startAt further out than the timeout is cancelled before it ever runs.

The timeout comes from the newest registered version of the workflow and applies to that workflow's runs of every version, so adding, raising or removing it on a new version also changes it for in-flight runs of older ones. The sweep only covers runs in the engine's own namespace.

A timeout is reported like any cancel: the run is cancelled, its error.code is execution_timeout, and the engine emits run.failed — the event every cancellation emits. Alert on the code, not on the event type.

A timed-out run takes its children with it, the same way an explicit cancel does — the whole subtree, depth-first, skipping any child that already finished. Otherwise a child outlives the parent that spawned it with nothing left pointing at it, and the only way to find it is to read the runs table by hand.

The cap is enforced by engine.sweepTimeouts, which the NestJS TimerPoller calls every tick — so a driving operator instance must be running (not drive: false) for it to fire, exactly like durable timers and retention. See Scheduling for the poller, and Event-driven workflows for validateInput on an event-triggered start.

15. Performance

Dispatched steps don't replay: the sticky continuation

A dispatched ctx.step suspends the run until the step's result lands. Without anything else, the next turn would replay the workflow body from the top over the run's whole history, so a step would cost more the longer the run gets. Instead, the instance that ran the turn keeps the parked body in memory: the step call doesn't unwind, it waits. The turn still settles the run suspended and releases its lease exactly as before. When the result's turn runs on the same instance, it re-reads only the steps the body is parked on and lets the body continue from there. Per-step cost stays flat however long the run is, and the body runs once.

It is an optimization only. The engine falls back to a normal replay whenever it can't be sure the parked body is the run's latest state:

  • the result's turn runs on another instance (or after a restart), which replays as usual;
  • another turn settled the run since the body parked (the run row's updatedAt stamp differs), or the run was cancelled or retried;
  • the body was evicted (see the knobs below), or sat idle past stickyIdleMs;
  • the turn also suspended some other way (a sleep, a signal, a child, a step fan): only bodies parked purely on dispatched ctx.step calls are kept;
  • the body called a ctx primitive while detached, between turns, e.g. after awaiting a raw timer or fetch outside the ctx. The call is refused before it does anything, and the run replays;
  • an execution wrapper (Telescope registers one) is registered: a resumed body runs in the async scope of the turn that started it, and a wrapper expects one scope per turn.

Non-determinism is still caught: a parked call re-checks its checkpoint, and every position past the park point is read from the store exactly as a replay reads it.

Option (DurableModule / WorkflowEngine)DefaultWhat it does
stickyRuns1000Parked bodies kept per instance; least recently used out first. 0 turns the cache off.
stickyIdleMs300_000How long a parked body may wait for its next turn before it's dropped.

A parked body costs about 26 KB of heap (measured with a small body; its closures, the ctx and its pending promises), so the default holds ~26 MB at most. Runs past the limit just replay; raise it on an instance that keeps more runs in flight at once, lower it where memory is tight.

Several engine instances: results go back to the parked body

With several engine instances consuming one results queue, a step's result would land on the instance holding its parked body only part of the time, and the others would replay. So a dispatched ctx.step asks for its result back: the task carries the dispatching instance's id (replyTo), and on a transport that routes replies (BullMQ) the worker sends the result to that instance's own queue (<prefix>-results-to-<instance>). Step fans (ctx.all) keep the shared queue, so a wide fan still spreads over every engine.

A result is never lost to a missing instance. Each engine keeps an alive key in Redis; while it is missing (a crash, a scale-down, a shutdown, which deletes it first), workers send results to the shared queue, and every engine and worker moves what is left on a dead instance's queue there, stalled jobs included. That result then replays on whichever engine takes it. Engines and workers from before this change ignore replyTo, so a rolling deploy mixes freely.

OptionWhereDefaultWhat it does
routeRepliesDurableModule / WorkflowEnginetrueAsk for routed results (only while the sticky cache is on).
replyRoutingBullMQTransporttrueConsume and send routed results; false keeps everything on the shared queue.
replyAliveTtlMsBullMQTransport15_000How long an engine's alive key outlives its last refresh.
replySweepMsBullMQTransport5_000How often dead instances' queues are looked for.
replyDrainIdleMsBullMQTransport90_000How long an emptied dead queue is still watched before it's forgotten.

Fewer round trips

The bundled SQL stores implement optional StateStore methods that save round trips on the hot path: settling a batch of step results and reading the settled rows back in one statement (settleResultsIfPending), taking a run's lease and reading it at once (tryLockRunAndGet), writing a first dispatch's pending row without a read first (insertCheckpointIfAbsent), and claiming pending runs in batches with FOR UPDATE SKIP LOCKED (claimPendingRuns). Several driving replicas without a run queue split the backlog instead of racing for the same rows, and each runs its batch concurrently. The Drizzle (Postgres), TypeORM, MikroORM and Prisma stores implement them on Postgres and MySQL (on MySQL, which has no RETURNING, the ones that still save a statement there); on SQLite they are left out. A custom store that omits them keeps working; the engine falls back to the read-then-write calls. A store for a database without RETURNING can build settleResultsIfPending for batches on its own batched calls with settleResultsWithPlainCalls from the core package.

The sticky continuation recognizes the run row by the exact updatedAt its suspend wrote, so a store must keep that column to the millisecond. Every bundled store does on Postgres and MySQL (the TypeORM and MikroORM auto-schemas raise older second-precision MySQL columns at boot); one that rounds it just replays every turn.

On node-postgres, the Drizzle store sends these statements as constant SQL text instead of rebuilding them with drizzle's query builder every time (other drivers keep the builder), as named prepared statements, so Postgres parses each one once per connection; that halves its CPU per workflow. Prepared statements need a direct connection, or a pooler that supports protocol-level prepared statements. Behind PgBouncer in transaction mode before 1.21, turn them off with new DrizzlePgStateStore(db, { preparedStatements: false }).

On this page