CodePark/ questions / Microservices, queues & events
START PRACTICINGPRACTICE
Backend question · NestJS › Microservices, queues & events

What is @nestjs/event-emitter for, and how is it different from microservice events or a BullMQ queue?

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 EventEmitter2 and call emit("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 EventEmitter2 and @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.