← Back to Pull requests

feat: add an opt-in saga error strategy that resubscribes with backoff #2390

Closed
unknown closed this pull request without merging on Oct 20, 2026 07:13 UTC
View on GitHub
unknown unknown commented on Oct 18, 2026 20:11 UTC
Author

PR Checklist


Please check if your PR fulfills the following requirements:

  • The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md

  • Tests for the changes have been added (for bug fixes / features)

  • Docs have been added / updated (for bug fixes / features)
  • PR Type


    What kind of change does this PR introduce?

  • Bugfix

  • Feature

  • Code style update (formatting, local variables)

  • Refactoring (no functional changes, no api changes)

  • Build related changes

  • CI related changes

  • Other... Please describe:
  • What is the current behavior?

    Issue Number: follow-up to #1838 and #1861

    Since #1861, an error thrown inside a saga's stream is published to UnhandledExceptionBus and no longer crashes the app, but the saga then stops: the outer catchError in registerSaga returns of(), so every later event is ignored for the rest of the process.

    What is the new behavior?

    A new CqrsModuleOptions.sagaErrorStrategy option, 'complete' | 'resubscribe', defaults to 'complete', which is the current behavior: the error is published and logged, then the saga stops. With 'resubscribe', the saga uses retry({ delay }): each error is published to UnhandledExceptionBus and logged, then the stream is subscribed again after a delay that starts at 100 ms and doubles with each error up to 30 s. The delay starts again from 100 ms when no error has happened for 60 s, but it is not reset after successful events, so a shareReplay stream that replays its failing event cannot loop fast, and the saga never stops for good. The three durations are private constants. rethrowUnhandled still rethrows before any of this, with either strategy.

    The rxjs peer range moves from ^7.2.0 to ^7.3.0, because retry({ delay }) arrived in RxJS 7.3.0 (July 2021). On 7.2.0 retry ignores the config object: in a scratch install, all 8 'resubscribe' cases fail there and pass on 7.3.0. I kept retry rather than rebuilding it with catchError((error, caught) => timer(d).pipe(mergeMap(() => caught))), which runs on 7.2 but nests one subscriber chain per error: in a probe with a 0 ms delay, the heap grew from 5.6 MB to 21.7 MB over 10,000 errors and the next valid event was no longer delivered, while retry stayed at 5.8 MB and delivered it.

    Since the first review: the option is opt-in, the burst counter (errorsInBurst, Date.now()) and the hard stop are gone, the unit tests moved to src/event-bus.spec.ts, and the option's JSDoc says that resubscribing runs operators such as startWith again, that events published during the delay are missed, and that events in flight inside the saga are dropped with either strategy, so catching per event in the inner mergeMap is still the reliable pattern.

    Since the second review: the saga keeps its own attempt count and the time of its last error (performance.now()) instead of using rxjs's retryCount, and an error that comes 60 s or more after the previous one starts again from 100 ms. Before this, the delay only grew over the life of the process: after 10 bad events one day apart and an 11th, none of 20 valid events sent 1 s apart starting 5 s later produced a command.

    Tests: src/event-bus.spec.ts (12 cases, vitest fake timers) covers the default (the saga ignores a later event, and a startWith command runs once), and for 'resubscribe': 12 bad events 60 s apart and then a valid one (12 errors published and logged, 1 command), the delays between resubscriptions (100, 200, 400 ... 25,600, then 30,000 ms), 5 bad events 10 s apart (delays 100 to 1,600 ms), errors 59,999 ms and then 60,000 ms apart (delays 100, 200, then 100 ms again), 10 bad events a day apart then an 11th and 20 valid events (20 commands; 0 on 98b3d22), no reset after a successful event, the shareReplay replay (4 errors in 1 s), a rejected promise in combineLatest (a 50 ms timer still fires after 1 error), and a startWith command that runs 3 times after two errors. On master the 9 'resubscribe' cases fail and the 2 default cases and the rethrow case pass. The e2e case in unhandled-exceptions.spec.ts builds a module with CqrsModule.forRoot({ sagaErrorStrategy: 'resubscribe' }) and makes the saga throw three times, with 1 s between rounds and a 20 s timeout; on master it times out. Each of these changes makes at least one test fail: defaulting to resubscribe, a delay that does not grow, resetting the count on a successful event, no reset after the quiet period, the quiet-period comparison reversed, <= instead of < at 60 s, a quiet period of 59,999, 60,001, 30,001 or 600,000 ms, no publish, a zero delay, a 60 s cap, and ignoring the option (e2e).

    With rethrowUnhandled: true the error is still rethrown before anything is published, in both strategies, and the saga is not resubscribed; a unit test covers it.

    Does this PR introduce a breaking change?


  • Yes

  • No
  • The default behavior is unchanged. A project pinned to RxJS 7.2.x would get a peer dependency conflict from the new ^7.3.0 range.

    Other information

    Measured with a script that builds EventBus directly (master / default / 'resubscribe'):

  • shareReplay that emits a command and then throws on a bad event, over 200 ms: errors 1 / 1 / 2, commands run again 0 / 0 / 1.

  • merge(events$, timer(50).pipe(map(() => { throw ... }))): errors in 1 s 1 / 1 / 4.

  • combineLatest([events$, from(rejectedPromise)]): errors in 500 ms 1 / 1 / 3, and a 10 ms interval ticked 42 / 43 / 42 times.
  • I left the docs checkbox open: the note lives in the option's JSDoc, since this repo has no docs folder. I can open a PR on docs.nestjs.com once the option name is settled.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: kamilmysliwiec Review duration: 2102m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #2390"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository