this.eventEmitter.emit("order.created", new OrderCreatedEvent(order));
@OnEvent("order.created")
handleOrderCreated(event: OrderCreatedEvent) {
// send confirmation, update stats...
}
@nestjs/event-emitter sends events inside one running app. Microservice events go to other services through a broker, and a BullMQ queue stores jobs so they are not lost.
How it works. It wraps the EventEmitter2 library.
- Call
EventEmitterModule.forRoot(). - Inject
EventEmitter2and callemit("order.created", payload). - Any provider method decorated with
@OnEvent("order.created")runs.
This decouples modules inside one app. For example, the orders module doesn't need to import the mail or analytics modules.
Limits. Events live only in memory. They don't cross process boundaries. If the process crashes or a listener throws, there is no retry and nothing is saved.
The other options:
- Microservice events, with
emit()and@EventPattern(), go through a broker to other services. - A BullMQ queue stores jobs in Redis and retries them.
In short: use the event emitter for cheap internal decoupling. Use a queue when the work must not be lost.
- It sends in-process events with
EventEmitter2and@OnEvent. - It decouples modules inside one app.
- Events are not saved or retried, and stay in a single process.
- Microservice events go to other services through a broker.
- Queues save jobs and retry them.
Read more
- Events (https://docs.nestjs.com/techniques/events)docs.nestjs.com
- Queues (https://docs.nestjs.com/techniques/queues)docs.nestjs.com