Application
Events
Let one part of the application announce something, and others react.
Imagine placing an order. After it is saved you must charge the card, send a confirmation email, reserve stock and write an audit line. If OrderService calls all four, it knows about everything and every new reaction means editing it. With events, OrderService only announces "an order was created"; each interested part listens by itself. Adding a reaction means adding a listener, not changing the order code.
event-emitter is @nestjs/event-emitter. Import the module once:
Kest.run<AppModule> { import(EventEmitterModule.forRoot()) }Listen and emit
data class OrderCreated(val orderId: String, val total: Long)
@Injectable
class Billing {
@OnEvent("order.created") fun charge(e: OrderCreated) { ... }
}
@Injectable
class Audit {
@OnEvent("order.*", priority = 10) fun log(e: Any) { ... } // wildcards; a higher priority runs first
}
@Injectable
class Orders(private val events: EventEmitter, private val repo: OrderRepository) {
fun place(o: Order) {
repo.save(o)
events.emit("order.created", OrderCreated(o.id, o.total)) // runs every matching listener, returns whether any listened
}
}An event has a name (order.created, dotted) and an optional payload (any object). A listener method takes the payload as its parameter. "order.*" matches order.created, order.paid... .
How listeners run
Synchronous (emit) | listeners run in the emitting thread, one after another, by priority. emit returns when all are done. If one throws, the exception is logged (and sent to error monitoring) and the others still run; the emitter does not see the failure |
Asynchronous (emitAsync, or @OnEvent(..., async = true)) | listeners run on virtual threads; emitAsync returns a future of their results |
Use synchronous when a listener's work must finish before the emitter continues (it takes part in the same request); use asynchronous for slow, independent work (sending an email).
Events are not a message queue
Events live inside one process and are not saved. If the process dies after emit but before a listener finished, the reaction is lost. For work that must not be lost (charging, shipping), use:
- the transactional outbox, which stores the event with your data, or
- a queue job.
Use events for in-process decoupling and for reactions that are fine to lose (cache invalidation, metrics, logging).
Good practice
- Name events in the past tense (
order.created): they say what happened. - Make the payload a small immutable data class with ids, not a live entity.
- Keep listeners independent: one should not rely on another having run, except via
prioritywhen you must. - Do not emit from inside a listener of the same event (it can loop).