Today I'm excited to announce @nestjs/workflows, a new package for durable workflows in Nest. It lets you write a process that takes days, such as charging a card, waiting for a delivery, and asking for a review a week later, as a single async method. Every step is journaled in your own database, so the workflow survives deploys and crashes, never repeats work it has already done, and undoes it when something goes wrong. And there's no workflow server to run.
In case you're not familiar with NestJS, it is a TypeScript Node.js framework that helps you build enterprise-grade efficient and scalable Node.js applications.
Let's dive right in! 🐈
Why durable workflows?
Let's take the order fulfilment process of an online store selling cat food:
- Charge the customer's card.
- Reserve the items in the warehouse.
- Wait up to 3 days for the carrier to tell us the parcel was delivered.
- If it never arrives, or the carrier returns it, refund the customer and release the stock. Otherwise, wait 7 days and ask for a review.
On a whiteboard, that's four boxes and a couple of arrows. In production, it's a different story. The process has to survive deploys and crashes, charge the card exactly once, undo its work when it fails, and let customer support check where every single order stands.
The usual answer is a mix of queues, cron jobs, status columns, and "if status is X and updated_at is older than 3 days" queries. It works, until nobody can tell how a given order ended up in the state it's in, because the logic of a single process is spread across a dozen handlers. The other answer is a dedicated workflow engine, which is another cluster to run, monitor, and upgrade.
@nestjs/workflows sits in between. It's a library, it keeps its state in your database, and the workflow itself is just TypeScript that reads top to bottom, exactly like the list above.
Workflows, queues, or sagas?
Before we go further, it's worth saying when you don't need a workflow.
- A queue (e.g., BullMQ) is great for independent background jobs: resize an image, send an email, generate a report. One job, one handler, done.
- A saga built from events and handlers fits when several services coordinate loosely and nobody owns the whole process.
- A workflow shines when one process has several steps that depend on each other, needs to wait (for a person, a webhook, or simply time), and has to be undone when it fails halfway. And when someone will ask "where is order #1234 right now?"
They also work well together. As you'll see later, a workflow can hand heavy lifting off to a queue and wait for the result.
Getting started
First, install the package:
$ npm i --save @nestjs/workflowsThen register the module, along with a store. PostgreSQL and MySQL are supported out of the box, with Drizzle, TypeORM, Prisma, or a plain driver:
@Module({ imports: [ DrizzleModule.forRootAsync({ /* ... */ }), WorkflowsModule.forRoot({ worker: { concurrency: 10, leaseDuration: '30s', shutdownTimeout: '10s' }, }), ], providers: [ { provide: PostgresWorkflowStore, inject: [getDrizzleToken(), WorkflowStorage], useFactory: (db: Database, workflowStorage: WorkflowStorage) => new PostgresWorkflowStore({ executor: fromDrizzle(db) }, workflowStorage), }, OrderFulfilmentWorkflow, ],})export class AppModule {}The store keeps everything in a dedicated nest_workflows schema. In development, it migrates itself at startup. In production, you apply migrations before deploying, with your own tool or with npx @nestjs/workflows migrate (and npx @nestjs/workflows status makes a nice CI check).
Every instance of your application is also a worker that picks up workflows from the database, so to scale, you simply run more instances. Workers hold leases on the instances they're running, so when a process crashes, another one takes over as soon as the lease expires. And on a graceful shutdown (app.enableShutdownHooks()), the worker hands its instances back right away.
‼️ Without a store, workflows live in memory, which is fine for tests, but they're lost on restart and can't join your transactions. That's why the application refuses to start with NODE_ENV=production and no store, unless you explicitly opt in with allowInMemoryStorage: true. ‼️
Write the workflow
Here's the first part of our order fulfilment:
@Workflow('order-fulfilment')export class OrderFulfilmentWorkflow implements WorkflowRunner<Order, FulfilmentResult> { constructor( private readonly payments: PaymentsService, private readonly warehouse: WarehouseService, ) {} async run(order: Order, ctx: WorkflowContext) { const charge = await ctx.step( 'charge-payment', ({ idempotencyKey }) => this.payments.charge(order, idempotencyKey), { retry: { attempts: 5, backoff: { delay: '2s' } }, compensate: (charge, { idempotencyKey }) => this.payments.refund(charge.chargeId, idempotencyKey), }, ); ctx.setStatus('paid'); await ctx.step('reserve-stock', () => this.warehouse.reserve(order), { compensate: () => this.warehouse.release(order), }); ctx.setStatus('awaiting-delivery'); // ... }}The key idea: every side effect runs in a step, and every step's result is journaled. When the process crashes, or a new version gets deployed, the workflow reruns run() from the top, but the steps that already completed don't run again. They return their recorded results instead. So the card is charged once, no matter how many times the method itself runs.
A few details worth knowing:
- Idempotency keys. Each step gets an
idempotencyKey(<instance id>:<step name>) that stays the same across retries and processes. Pass it to your payment provider, and even a step that crashed halfway through, after charging but before recording the result, won't charge twice. - Retries. Steps retry with exponential backoff by default (3 attempts). If retrying won't help, say the card was declined, throw
NonRetryableStepErrorand the step fails immediately. While waiting for the next attempt, the instance is parked and doesn't hold a worker. - Compensations.
compensateis the undo. If the workflow fails or gets cancelled, compensations run in reverse order: release the stock, then refund the charge. They're journaled, retried, and get their own idempotency keys, too. - JSON in, JSON out. Step results are stored as JSON and come back as JSON, even on the first run (a
Datebecomes a string). The types reflect that, so TypeScript won't let you forget.
Steps can also run in parallel. Reserving each item separately, each with its own undo, is just Promise.all():
await Promise.all( order.items.map((item, i) => ctx.step(`reserve-item-${i}`, () => this.warehouse.reserveItem(item), { compensate: () => this.warehouse.releaseItem(item), }), ),);Start it with the order
You start a workflow in the same transaction that saves the order:
const order = await this.db.transaction(async (tx) => { const order = await this.saveOrder(tx, dto); await this.workflowClient.start(OrderFulfilmentWorkflow, order, { id: fulfilmentId(order.id), transaction: tx, }); return order;});Either both the order and its workflow exist, or neither does. No orders stuck without a fulfilment, no fulfilments for an order that rolled back. And since id is derived from the order (order-<id>), starting the same workflow twice is harmless.
That same id makes the process observable. Here's an endpoint that tells customer support exactly where an order stands:
@Get(':id/fulfilment')async fulfilment(@Param('id') id: string) { const instance = await this.workflowClient.getStatus(fulfilmentId(id), { journal: true }); return { status: instance.status, stage: instance.customStatus, waitingFor: instance.waitingFor, wakeAt: instance.wakeAt, steps: instance.journal, };}status is the engine's view (running, suspended, compensating, completed, failed, ...), while stage is yours, whatever you passed to ctx.setStatus(). Together with the journal, support can answer "it was charged, the stock is reserved, and we're waiting for the carrier until Thursday" without ever opening the database.
Wait for signals and timers
Step 3 is where things get interesting. We need to wait for the carrier's shipment.delivered webhook, for up to 3 days, but the parcel might also get returned. First, declare the signals:
export const shipmentDelivered = new WorkflowSignal<CarrierEvent>('shipment.delivered');export const shipmentReturned = new WorkflowSignal<CarrierEvent>('shipment.returned');Then wait for whichever comes first:
const outcome = await ctx.waitForAny('await-delivery', { delivered: ctx.signalWait(shipmentDelivered, { key: order.id }), returned: ctx.signalWait(shipmentReturned, { key: order.id }), timedOut: ctx.timer('3d'),});if (outcome.key === 'returned') { ctx.fail('The parcel was returned');}if (outcome.key === 'timedOut') { ctx.fail('The parcel was not delivered within 3 days');}const delivery = outcome.value;While it's waiting, the workflow isn't running anywhere. It's parked in the database, holding no memory and no worker slot, whether it waits 3 seconds or 3 days. And ctx.fail() doesn't just mark it as failed: it runs the compensations, so the customer gets refunded and the stock is released.
When the webhook arrives, your controller sends the signal, again in the same transaction as the order update:
await this.db.transaction(async (tx) => { await this.markDelivered(tx, event); await this.workflowClient.signal(shipmentDelivered, event, { key: event.reference, id: event.trackingNumber, transaction: tx, });});Signals are durable. One sent before the workflow even reached the wait is kept until it does. And with an id, a signal that gets sent twice (say, because the carrier retried its webhook) is only stored once.
If you only need a single signal, ctx.waitForSignal('await-delivery', shipmentDelivered, { key: order.id, timeout: '3d' }) resolves with the payload, or with null when the timeout passes.
Sleep for a week, then ask for a review
Once the parcel is delivered, there's nothing left to undo. We wouldn't want a later failure (say, the review email bouncing) to refund a delivered order, so we mark the point of no return:
ctx.commit('delivered');ctx.setStatus('delivered');await ctx.sleep('before-review-request', '7d');await ctx.step('send-review-request', () => this.mail.sendReviewRequest(order));return { chargeId: charge.chargeId, trackingNumber: delivery.trackingNumber };ctx.commit() discards the compensations registered so far, and ctx.sleep() is a durable timer. Deploy ten times this week, and the review request still goes out exactly once, 7 days after delivery.
And as a safety net, you can put a deadline on the whole run. With @Workflow('order-fulfilment', { timeout: '30d' }), an instance that's still around after 30 days is stopped, compensated, and failed with WorkflowTimeoutError.
Cancel and operate
When a customer calls to cancel, support hits a route like this:
@Post(':id/cancel')@HttpCode(202)async cancel(@Param('id') id: string, @Body('reason') reason: string) { const order = await this.ordersService.findOne(id); if (order.status === 'delivered') { throw new ConflictException('A delivered order cannot be cancelled'); } const { accepted } = await this.workflowClient.cancel(fulfilmentId(id), reason); if (accepted) { await this.ordersService.markCancelled(id); } return { accepted };}A parked workflow wakes up immediately, a running one stops at its next ctx call, and either way it runs its compensations (release the stock, refund the card) and ends as cancelled. If it has already passed its point of no return, the cancel isn't accepted.
For day-to-day operations, there's:
retry(id)for an instance that failed (for example, after you fixed the bug that made it fail),terminate(id, reason)to stop one without running compensations,delete(id)to remove one, andpurge({ olderThan: '30d' })to clean up finished instances.
The purge pairs nicely with @nestjs/locks, so it runs once, no matter how many instances you have:
@Cron('30 3 * * *')@OnOneInstance({ key: 'workflows:purge' })async purge() { await this.workflowClient.purge({ olderThan: '30d' });}Two statuses deserve an alert: compensation_failed (the workflow failed, and so did the undo, so a human has to look at it), and failures caused by WorkflowNonDeterminismError, which we'll get to in a moment.
Control throughput
Steps call real systems, and real systems have limits. You can cap how many instances run at once, per key, and how often they start:
@Workflow('order-fulfilment', { concurrency: { limit: 1, key: (order: Order) => order.userId }, rateLimit: { max: 10, duration: '1s' },})Here, each customer has at most one fulfilment running at a time, and we start at most 10 per second, to stay within the payment provider's rate limit. Concurrency slots are only held while an instance is actually executing, not while it sleeps or waits for a signal, so a thousand orders waiting for delivery don't block anything.
Priorities decide who goes first. Pass priority: order.shipping === 'express' ? 1 : 2 when starting, and express orders are always picked up before standard ones (lower runs first).
Child workflows
As the process grows, you'll want to split it up. Shipping, for instance, can be its own workflow, with its own steps and compensations:
@Workflow('shipment')export class ShipmentWorkflow implements WorkflowRunner<Order, CarrierEvent> { async run(order: Order, ctx: WorkflowContext) { await ctx.step('book-pickup', ({ idempotencyKey }) => this.carrier.bookPickup(order, idempotencyKey), { compensate: (pickup) => this.carrier.cancelPickup(pickup.id), }); // ...wait for delivery, as before }}and the parent simply awaits it:
const delivery = await ctx.executeChild(ShipmentWorkflow, order);The child gets its own id, journal, and status page. When it fails, the parent receives a ChildWorkflowFailedError and can compensate, and when the parent is cancelled, so is the child (configurable with parentClose).
Long-running steps
Most steps take milliseconds. Some don't. Rendering all invoices at the end of the month can take half an hour, and you don't want a crash at minute 29 to start from scratch. That's what heartbeats are for:
await ctx.step( 'render-invoices', async ({ progress, heartbeat, signal }) => { let cursor = progress?.cursor; for await (const page of this.invoices.pages({ month, after: cursor, signal })) { await this.renderer.renderPage(page); cursor = page.lastId; await heartbeat({ cursor }); } }, { heartbeatTimeout: '2m' },);Each heartbeat() saves a checkpoint, and if the attempt dies, the next one gets it back as progress and resumes from there. If no heartbeat arrives for 2 minutes, the attempt is considered stuck and retried. And signal aborts when the process shuts down or loses its lease, so the step stops cleanly.
If the heavy lifting already lives in a queue, the workflow can hand it off instead: enqueue the job in a step (using the idempotency key as the job id), then wait for a signal that the job's processor sends when it's done.
Schedules
Recurring work can be declared right on the workflow. Here's the monthly invoice run, at 2 a.m. New York time on the first of every month:
@Workflow('invoice-batch', { schedules: [ { id: 'monthly-invoices', cron: '0 2 1 * *', tz: 'America/New_York', missed: 'once', input: ({ at }) => ({ month: lastMonth(at) }), }, ],})missed: 'once' means that if every instance was down at 2 a.m., the run still happens once when they come back. (The default is to skip missed runs, and there's also overlap to decide what happens when the previous run is still going.)
Schedules can be created at runtime, too. A "remind me to reorder cat litter every 4 weeks on Saturday morning" feature is one call, in the customer's own time zone:
await this.workflowClient.schedules.upsert(`reorder-reminder-${user.id}`, { workflow: ReorderReminderWorkflow, rrule: 'FREQ=WEEKLY;INTERVAL=4;BYDAY=SA;BYHOUR=9;BYMINUTE=0', tz: user.timeZone, input: { userId: user.id },});When the caller needs the result
Not everything has to be fire-and-forget. When an HTTP request needs the result, use startAndWait(), and fall back gracefully when it takes too long:
try { return await this.workflowClient.startAndWait( InvoiceBatchWorkflow, { month }, { id: `invoices-${month}` }, { timeout: '30s' }, );} catch (error) { if (error instanceof WorkflowResultTimeoutError) { res.status(202); return { rendering: true }; } throw error;}The workflow keeps running after the timeout. Only the waiting stops.
Deploy changes safely
Since workflows replay their journal, there are a few rules for the code inside run(). They're short, and they're all about one thing: the method must make the same decisions every time it replays.
- All I/O goes into steps.
- Use
ctx.now(),ctx.random(), andctx.uuid()instead ofDate.now(),Math.random(), orrandomUUID(). - Step and wait names must be unique within a run.
- Don't use
Promise.race()orPromise.any(). Usectx.waitForAny()instead. - Don't keep per-run state on
this.
The same goes for deploys. Renaming, removing, or reordering steps would make the journal and the code disagree. Instead of silently doing the wrong thing, the engine detects that before the next step runs and fails the instance with WorkflowNonDeterminismError (without charging anyone twice). To make such a change, you register a new version:
@Workflow('order-fulfilment', { version: 2 })export class OrderFulfilmentWorkflowV2 implements WorkflowRunner<Order, FulfilmentResult> { // charge-payment, then a new send-order-confirmation step, then the rest}New orders start on version 2, while running ones finish on version 1. Once list() shows no unfinished version 1 instances, you delete the old class. Adding steps after the last one any running instance has reached, or tweaking retries and timeouts, doesn't need a new version at all.
More use cases
Order fulfilment is just one example. Here's where else durable workflows fit naturally:
- Subscriptions. Ship a box, sleep 30 days, repeat. For endless processes, continue as a new instance every year (
subscription-<id>-<year>), so journals stay short. - Onboarding. Send a welcome email, wait for the user to verify their address (a signal) or 3 days (a timer), nudge them, and escalate to a human if they never finish.
- Approvals. A refund above a threshold waits for a manager's signal, with a deadline, and runs the refund only once it's approved.
- Billing runs. Monthly invoicing as a scheduled workflow, with a heartbeating step that survives crashes halfway through.
- Event-driven processes. With the CQRS integration,
@StartOn(OrderPlacedEvent)and@SignalOn(OrderDeliveredEvent)connect workflows to events published in your transactions, and steps can execute commands through theCommandBus.
And if your workflows store personal data, an AesGcmPayloadCodec encrypts everything they journal, with key rotation, while ids, statuses, and times stay readable for operations.
Testing
Testing a process that waits for 3 days shouldn't take 3 days. Pass a manual clock to the module, disable the worker, and drive time yourself:
it('refunds and releases the stock when the parcel never arrives', async () => { const order = await placeOrder(); clock.advance('3d'); await drain(); const instance = await workflowClient.getStatus(fulfilmentId(order.id), { journal: true }); expect(instance.status).toBe('failed'); // compensations ran in reverse order: reserve-stock, then charge-payment});You can also test crash recovery for real: hang a step, close the app, boot a second one, advance the clock past the lease, and check that it resumes with the same idempotency key, and the customer was charged exactly once. And if you write your own store, the workflowStoreContract suite from @nestjs/workflows/testing verifies it behaves correctly under concurrency.
Try it today!
$ npm i --save @nestjs/workflowsThe new Durable workflows chapter in the official documentation covers everything above in depth, including TypeORM and MySQL setups, the CQRS integration, encryption, every status and error, and a production checklist. Give it a try, and please open an issue if anything gets in your way!
Happy coding! 🐈
Learn NestJS - Official NestJS Courses 📚
Level-up your NestJS and Node.js ecosystem skills in these incremental workshop-style courses, from the NestJS Creator himself, and help support the NestJS framework! 🐈🚀 The NestJS Fundamentals Course is now LIVE and 25% off for a limited time!
🎉 NEW - NestJS Course Extensions now live!
- NestJS Advanced Concepts Course now LIVE!
- NestJS Advanced Bundle (Advanced Architecture and Advanced Concepts) now 22% OFF!
- NestJS Microservices now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
- NestJS GraphQL Course (code-first & schema-first approaches) are now LIVE!
- NestJS Authentication / Authorization Course now LIVE!
