Adding an event
Use the outbox when another module must react after the business row commits, including across a process restart.
-
Call
outboxWriter.enqueue(tx, { tenantId, eventType, aggregateId, payload })inside the businessprisma.$transaction, with thattx. -
Add a consumer method on a provider in a module that
WorkerModuleimports:@OutboxHandler('order.created', 'fulfillment.order-created.v1', { lockOrder: true })async handleOrderCreated(event: OutboxEventEnvelope<OrderCreatedEvent>,transaction: Prisma.TransactionClient): Promise<void> {// write through `transaction`} -
Name the consumer
<area>.<purpose>.v1. The name keys itsProcessedEventrows, so it is permanent: renaming it replays the event history to it. Bump the version only when you mean to. -
Write through the
transactionargument. Those writes commit with the consumer's idempotency record, so a retry cannot apply them twice. PasslockOrder: truewhen the consumer mutates the order named in the payload.If the consumer calls an external system or a service that runs its own queries, declare
{ transactional: false }and take only(event). It is then called with no transaction open and recorded afterwards, so it must be safe to repeat. Do not keep the transaction parameter and ignore it: holding the dispatcher's transaction while querying on other connections starves the pool under load. The decorator throws when the parameters do not match the mode. -
Let errors propagate. Do not catch to log: the dispatcher retries the event and reports the failure. Catch only a failure you can handle, and throw
ExpectedErrorfor one that is not a bug. -
Run
yarn di:check. It fails if the consumer's class is not a provider of the worker, or if two consumers share a name.
A local event (EventEmitter2.emit with an @OnLocalEvent listener) is appropriate only for a best-effort side effect, such as cache warming or embeddings, in the same process, where losing it on a crash is acceptable. @OnLocalEvent reports a failure and never retries. return.status.changed shows the failure mode of emitting with nothing listening.
Document the new eventType on Events in the same change.