Today I'm excited to announce @nestjs/outbox, a new package that implements the transactional outbox pattern for Nest. You write your business data and the messages that describe it in the same database transaction, and a relay delivers those messages afterwards, with retries, ordering per key, a dead-letter queue, and an inbox on the consumer side, so nothing gets lost and nothing gets processed twice.
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 an outbox?
Picture a typical online store. A customer places an order, you save it in the database, and then you publish an OrderPlaced event so other parts of the system can send a confirmation email, reserve stock, and update analytics.
The problem is that there's no transaction spanning both your database and whatever you publish to. So whichever order you pick, something can go wrong:
- Save, then publish. The process crashes in between, and the event is lost. No confirmation email, no stock reservation, and the analytics dashboard undercounts.
- Publish, then save. The insert fails, and the customer gets thanked for an order that doesn't exist.
- Retry on error. The publish times out after it actually succeeded, you send it again, and the customer gets two confirmation emails.
This is known as the dual write problem, and ClientProxy.emit(), EventEmitter2, and the CQRS EventBus all have it, because they publish from memory.
The fix is the transactional outbox. Instead of publishing directly, you insert the message into an outbox table in the same transaction as the order itself. Either both are saved or neither is. A relay then picks up committed messages and publishes them, and consumers keep an inbox of the messages they've already processed. @nestjs/outbox gives you all three pieces.
Getting started
First, install the package:
$ npm i --save @nestjs/outboxMessages live in your own database, so you register a store along with the module. The package ships with stores for PostgreSQL and MySQL, and works with Drizzle, TypeORM, Prisma, Kysely, or a plain pg / mysql2 client:
@Module({ imports: [ DrizzleModule.forRootAsync({ /* ... */ }), OutboxModule.forRootAsync({ useFactory: () => ({ relay: { enabled: process.env.OUTBOX_RELAY !== 'off' }, retry: { attempts: 10, backoff: { delay: '1s', maxDelay: '1m' } }, }), }), ], providers: [ { provide: PostgresOutboxStore, inject: [getDrizzleToken(), OutboxStorage], useFactory: (db: Database, storage: OutboxStorage) => new PostgresOutboxStore({ executor: fromDrizzle(db) }, storage), }, ],})export class AppModule {}The store creates its tables in a dedicated nest_outbox schema. In development, migrations run automatically at startup. In production, you apply them before deploying, either through your own migration tool or with npx @nestjs/outbox migrate (and npx @nestjs/outbox status makes a nice CI check).
‼️ Without a store, the outbox lives in memory, which is fine for tests but defeats the whole point in production. That's why the application refuses to start with NODE_ENV=production and no store registered, unless you explicitly opt in with allowInMemoryStorage: true. ‼️
One transaction, one source of truth
Here's what placing an order looks like:
async placeOrder(userId: string, dto: PlaceOrderDto): Promise<Order> { const order = await this.db.transaction(async (tx) => { const [order] = await tx.insert(orders).values({ userId, ...dto }).returning(); await this.outbox.add(tx, [ { topic: 'order.placed', payload: order }, { topic: 'analytics.order.placed', key: order.id, payload: order }, ]); return order; }); this.outbox.notify(); return order;}add() takes the transaction handle as its first argument, and it's not optional. Pass it the root database handle by mistake and it throws OutboxTransactionRequiredError, because writing outside the transaction would bring the dual write problem right back. If the transaction rolls back, the messages roll back with it.
notify() wakes the relay right after the commit, so delivery is instant. If you forget it (or the process dies right after committing), the relay simply picks the message up on its next poll.
Handling messages in-process
Consumers inside the same application are just methods decorated with @OnOutboxMessage():
@Injectable()export class OrderEmailsHandler { constructor(private readonly mailer: MailerService) {} @OnOutboxMessage('order.placed', { consumer: 'order-confirmation-email' }) async sendConfirmation(order: Order) { await this.mailer.sendOrderConfirmation(order); }}The consumer name is the key of that handler's inbox. Once it has successfully processed a message, it won't process it again, even if the message gets delivered twice. Several handlers can subscribe to the same topic, and if one of them fails, the message is retried, but the handlers that already succeeded are skipped.
When a handler writes to the same database, you can do even better and record the inbox entry in the handler's own transaction:
@OnOutboxMessage('order.placed', { consumer: 'stock-reservation' })async reserveStock(order: Order, ctx: OutboxHandlerContext) { await this.db.transaction((tx) => ctx.processInTransaction(tx, async () => { // Reserve the items, or throw NonRetryableMessageError // when there isn't enough stock }), );}Now the stock reservation and the "already processed" record either both commit or neither does. That's exactly-once processing for writes to the same database, which is about as good as distributed systems get. 🙃
Publishing to other services
Messages don't have to stay in-process. Each message goes to one transport, and a route function picks which one:
route: (message) => (message.topic.startsWith('analytics.') ? 'analytics' : 'local'),The built-in ClientProxyTransport publishes through any Nest microservices client, so the analytics service in the example above receives analytics.order.placed as a regular @EventPattern(). On the receiving side, the consumer uses the same inbox (OutboxInbox) to skip duplicates, ideally in the same transaction as its own writes.
‼️ The outbox guarantees the message leaves your process. With transports such as TCP, Redis or core NATS, a consumer that crashes after receiving a message, but before processing it, can still lose it. For events that must never be lost, use a broker with acknowledgements, such as Kafka, RabbitMQ with publisher confirms, or NATS JetStream. ‼️
Ordering, retries, and dead letters
Messages that share a key are published one at a time, in commit order. That's why the analytics message above uses key: order.id: an order.cancelled event can never overtake the order.placed event of the same order. Messages without a key (or with different keys) go out in parallel.
When publishing fails, the relay retries with exponential backoff and jitter. After the last attempt, the message moves to a dead-letter table with the error from every attempt. If a handler knows retrying won't help (say, there's not enough stock), it throws NonRetryableMessageError, and the message is dead-lettered right away.
From there, you can requeue a dead letter (it keeps its original id and gets a fresh retry budget, and consumers that already handled it skip it thanks to their inbox) or purge it. Both accept filters, such as a topic or a date, so cleaning up after an incident doesn't have to be done one message at a time.
Running several instances
The relay is safe to run on every instance. Messages are claimed with leases and SKIP LOCKED, and writes are protected by fencing tokens, so a relay that paused for too long can't overwrite the work of another one. If you prefer to keep your API pods lean, set OUTBOX_RELAY=off there and run the relay in dedicated worker processes.
On SIGTERM, the relay stops claiming new messages, waits for in-flight publishes, and releases its leases, so another instance picks up immediately. Just remember to call app.enableShutdownHooks().
Observability
The relay reports lagMs (how long the oldest pending message has been waiting) and the number of dead letters through relay.stats(), and every published, retry-scheduled, dead-lettered, and lease-lost event is published on OutboxEvents.events$ and on diagnostics channels such as nestjs:outbox:dead-lettered. Those two numbers, lag and dead letters, are the ones worth alerting on. With NestJS Observe, you can report them as custom metrics and see them right next to your traces.
Testing
Disable the relay in tests and drive it by hand with relay.runOnce(), so every test decides exactly when messages get delivered. Paired with PGlite (PostgreSQL running in-process) and your real migrations, you can test the whole flow, including what happens when a transaction rolls back after add().
And if you write your own store, the outboxStoreContract and outboxInboxStoreContract suites from @nestjs/outbox/testing verify it behaves correctly, including under concurrency.
Try it today!
$ npm i --save @nestjs/outboxThe outbox is also the foundation for other packages, such as @nestjs/mail and @nestjs/webhooks, so you'll see it again. The new Transactional outbox chapter in the official documentation covers everything above in depth, including TypeORM, Prisma, and MySQL setups, the full delivery guarantees, 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!
