nestjs / event-emitter

Event Emitter module for Nest framework (node.js) 🦋
https://nestjs.com
MIT License
193 stars 37 forks source link

Mitigating Event Loss Risk During NestJS Application Initialization #1063

Open mdwekat opened 8 months ago

mdwekat commented 8 months ago

Is there an existing issue that is already proposing this?

Is your feature request related to a problem? Please describe it

Problem Description:

In NestJS applications using the @OnEvent decorator, there's a risk of losing events emitted before the full completion of the application's bootstrap process. Specifically:

This early emission problem threatens the reliability of applications relying on events for tasks like state initialization, startup procedures, or module communication. Ensuring all events are captured is crucial for maintaining consistent application behavior and avoiding missed operations or errors.

App Start
├─ Module Initialization
│  └─ 🚨 Potential Early Event Emission (Risk)
│  
├─ Application Bootstrap
│  ├─ 🚨 Another Potential Early Event Emission (Risk)
│  └─ EventSubscribersLoader (onApplicationBootstrap)
│     └─ Event Listeners Setup (👂 Listening Starts)

Describe the solution you'd like

The solution involves several potential strategies:

  1. Deferred Event Emission: Implement a mechanism to defer the emission of events until it's guaranteed that all listeners are set up. This could involve queuing events emitted early and then releasing them once the application is fully bootstrapped.
  2. Lifecycle Hooks Enhancement: Enhance the order and timing of lifecycle hooks or the event listener setup process to ensure listeners are ready before any module emits an event.
  3. Documentation and Guidelines: Provide clear guidelines and best practices in the documentation to prevent early emission, possibly by outlining safe lifecycle phases for emitting events.

Teachability, documentation, adoption, migration strategy

What is the motivation / use case for changing the behavior?

The motivation is to ensure reliable and consistent event handling in NestJS applications. Events are crucial for asynchronous tasks and inter-service communication. By ensuring that no events are lost due to timing issues related to application initialization, we improve the robustness, predictability, and reliability of applications. This change will benefit all NestJS users who rely on event-driven architecture, especially those building complex or modular applications where timing and order of initialization are critical.

sashahohloma commented 8 months ago

I ran into the same problem when using lifecycle hooks

kamilmysliwiec commented 7 months ago

Deferred Event Emission: Implement a mechanism to defer the emission of events until it's guaranteed that all listeners are set up. This could involve queuing events emitted early and then releasing them once the application is fully bootstrapped.

Would you like to create a PR for this issue?