ASP.NET Core › Background Tasks & Hosted Services

How would you configure a BackgroundService to fail fast and crash the host if a critical startup dependency (like a message broker) is unreachable?

Intermediate

Answer

If a background service absolutely cannot function without a dependency being available, throwing during StartAsync or the very first check in ExecuteAsync (combined with the appropriate BackgroundServiceExceptionBehavior.StopHost configuration) brings down the entire host immediately -- an intentional 'fail fast' pattern appropriate for genuinely critical dependencies, versus implementing a retry-with-backoff connection loop if brief startup unavailability should be tolerated instead of crashing.
builder.Services.Configure<HostOptions>(options => {
    options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost;
});

protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    await _queueClient.ConnectAsync(stoppingToken);  // throws if unreachable -- crashes the host
}
Real-world example A payment-processing worker 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 non-functional, degraded state.

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