Skip to main content

Adding an event

Use the outbox when another module must react after the business row commits, including across a process restart.

  1. Call outboxWriter.enqueue(tx, { tenantId, eventType, aggregateId, payload }) inside the business prisma.$transaction, with that tx.

  2. Add a consumer method on a provider in a module that WorkerModule imports:

    @OutboxHandler('order.created', 'fulfillment.order-created.v1', { lockOrder: true })
    async handleOrderCreated(
    event: OutboxEventEnvelope<OrderCreatedEvent>,
    transaction: Prisma.TransactionClient
    ): Promise<void> {
    // write through `transaction`
    }
  3. Name the consumer <area>.<purpose>.v1. The name keys its ProcessedEvent rows, so it is permanent: renaming it replays the event history to it. Bump the version only when you mean to.

  4. Write through the transaction argument. Those writes commit with the consumer's idempotency record, so a retry cannot apply them twice. Pass lockOrder: true when 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.

  5. 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 ExpectedError for one that is not a bug.

  6. 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.