Back to results for “Startup”
.NET › Background Services

How should a BackgroundService handle a fatal startup dependency failure, such as being unable to connect to a required message queue at launch?

Intermediate

Answer

If a background service absolutely cannot function without a dependency being available, StartAsync (or the very first check inside ExecuteAsync) should throw, which by default (in .NET 6+, with the appropriate BackgroundServiceExceptionBehavior configured) can bring down the entire host -- appropriate 'fail fast' behavior for critical dependencies, versus implementing a retry-with-backoff connection loop inside ExecuteAsync if brief startup unavailability should be tolerated instead of crashing the whole app.
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    // Fail-fast option: let it throw and crash the host
    await _queueClient.ConnectAsync(stoppingToken);  // throws if unreachable

    // OR resilient option: retry with backoff instead of crashing
    await RetryConnectWithBackoffAsync(stoppingToken);
}
Real-world example A payment-processing worker service is configured to fail fast and crash immediately if it can't reach its message broker at startup, deliberately triggering a container restart and alert rather than silently running in a degraded, non-functional state.

Common follow-ups: How does BackgroundServiceExceptionBehavior.StopHost differ from the default Ignore behavior?;When is 'fail fast' the wrong choice for a background service?