Background services are commonly used in ASP.NET Core applications to execute tasks that should run independently of incoming HTTP requests.

Examples include sending scheduled notifications, processing queued messages, synchronizing data, generating reports, cleaning up expired records, and executing recurring database operations.

ASP.NET Core provides the BackgroundService base class, which makes it relatively straightforward to implement these long-running operations.

However, there is one problem developers sometimes encounter in production: a single exception can stop the entire background service and, depending on the hosting configuration, even stop the application.

Imagine a background service that runs every five minutes to process pending notifications.

The first execution completes successfully. During the second execution, the database becomes temporarily unavailable. The service throws an exception, and the execution loop terminates.

The application might still be running in some configurations, but the background service is no longer processing notifications.

This creates a situation where the application appears healthy, while an important background operation has silently stopped.

The problem becomes more serious when the background service is responsible for business-critical operations such as payment processing, scheduled reminders, inventory synchronization, or message processing.

A common mistake is to catch every exception and ignore it. Although this might prevent the service from stopping, it can hide genuine problems and leave failed jobs unprocessed.

The better approach is to handle failures at the appropriate level, log meaningful information, retry operations when appropriate, and allow the background service to continue processing subsequent jobs.

In this article, we'll understand how BackgroundService handles exceptions, why an unhandled exception can stop the host, and how to build more resilient background workers using practical C# examples.

We'll also explore retry strategies, cancellation handling, dependency injection scopes, logging, and production considerations.

Understanding How BackgroundService Works

Before looking at exception handling, let's understand how BackgroundService works in ASP.NET Core.

BackgroundService is an abstract class that implements IHostedService. It provides a convenient way to implement long-running background operations.

A typical background service overrides the ExecuteAsync() method:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        ILogger<NotificationBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Background service is running.");

            await Task.Delay(
                TimeSpan.FromMinutes(5),
                stoppingToken);
        }
    }
}

The ExecuteAsync() method represents the lifetime of the background service.

As long as the returned task is running, the hosted service remains active.

In this example, the service executes a loop, writes a log message, waits for five minutes, and then repeats the operation.

The stoppingToken is provided by the hosting infrastructure. It is triggered when the application begins shutting down.

The service should observe this token and stop its work gracefully.

Register the background service in Program.cs:

C#
builder.Services.AddHostedService<NotificationBackgroundService>();

ASP.NET Core starts the service when the application starts and manages its lifecycle during application shutdown.

This is the basic structure of a BackgroundService.

The important part is understanding what happens when an exception escapes from ExecuteAsync().

What Happens When an Exception Occurs in BackgroundService?

Consider the following implementation:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        ILogger<NotificationBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Processing scheduled notifications.");

            await ProcessNotificationsAsync();

            await Task.Delay(
                TimeSpan.FromMinutes(5),
                stoppingToken);
        }
    }

    private Task ProcessNotificationsAsync()
    {
        throw new InvalidOperationException(
            "Unable to process notifications.");

    }
}

The ProcessNotificationsAsync() method throws an exception.

Because there is no exception handling around the operation, the exception propagates out of ExecuteAsync().

The execution loop terminates immediately.

Starting with .NET 6, the default behavior of the Generic Host is to log an unhandled BackgroundService exception and stop the host.

This behavior is controlled by HostOptions.BackgroundServiceExceptionBehavior.

The default setting is:

C#
BackgroundServiceExceptionBehavior.StopHost

This means an unhandled exception from a BackgroundService can cause the entire ASP.NET Core application to stop.

The behavior was changed in .NET 6 because earlier versions could leave the application running even though the background service had stopped working.

That created a difficult situation: the application appeared to be running, but the background operation was no longer executing.

The newer default behavior makes such failures more visible.

However, stopping the entire application might not be the desired behavior for every background job.

For example, if a notification fails because of a temporary database timeout, there may be no reason to stop the web application.

In this situation, the service should handle the job failure and continue processing.

Catch Exceptions Inside the Background Execution Loop

The first step toward making a BackgroundService more resilient is handling exceptions around individual operations.

Instead of allowing an exception to escape from ExecuteAsync(), catch it inside the execution loop.

Consider the following implementation:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        ILogger<NotificationBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                _logger.LogInformation(
                    "Processing scheduled notifications.");

                await ProcessNotificationsAsync(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "An error occurred while processing notifications.");
            }

            await Task.Delay(
                TimeSpan.FromMinutes(5),
                stoppingToken);
        }
    }

    private Task ProcessNotificationsAsync(
        CancellationToken cancellationToken)
    {
        // Notification processing logic.

        return Task.CompletedTask;
    }
}

Now the behavior is different.

If ProcessNotificationsAsync() throws an exception, the catch block logs the error.

The exception does not escape from the execution loop, so the background service can continue.

After the delay, the next iteration starts.

The execution flow looks like this:

Code
Background Service Starts
          |
          v
    Start Processing
          |
          v
    Did Job Succeed?
       /       \
     Yes        No
      |          |
      v          v
 Continue     Log Error
      |          |
      +-----+----+
            |
            v
       Wait Interval
            |
            v
      Process Again

This is a simple but useful pattern for recurring background operations.

However, there is one important detail.

The exception handling should be placed around the individual operation, not used to hide every possible failure in the application.

For example, a database timeout during one job might be recoverable. A programming error caused by an invalid application state may require immediate attention.

Both should be logged, but they may need different recovery strategies.

Understand the Difference Between Job Failure and Service Failure

One of the most important design decisions is understanding what has actually failed.

A BackgroundService might execute hundreds or thousands of jobs during its lifetime.

If one job fails, it does not necessarily mean the entire background service should stop.

For example, imagine a worker responsible for sending notifications to users.

It processes three notifications:

  • Notification A is sent successfully.

  • Notification B fails because the email provider is temporarily unavailable.

  • Notification C is still waiting to be processed.

Should the entire worker stop because Notification B failed?

Usually, no.

The worker should record the failure, apply an appropriate retry strategy, and continue processing other notifications.

This means exception handling should happen at the job level whenever possible.

Consider this implementation:

C#
private async Task ProcessNotificationsAsync(
    IEnumerable<Notification> notifications,
    CancellationToken cancellationToken)
{
    foreach (var notification in notifications)
    {
        try
        {
            await SendNotificationAsync(
                notification,
                cancellationToken);
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                ex,
                "Failed to send notification {NotificationId}",
                notification.Id);
        }
    }
}

Here, a failure while sending one notification does not prevent the worker from attempting the next notification.

This is useful when jobs are independent of each other.

However, there are situations where processing must stop.

For example, if a financial transaction requires several dependent operations, continuing after an intermediate operation fails might leave the system in an inconsistent state.

The recovery strategy should depend on the business operation.

A useful rule is:

  • If an individual job fails independently, handle the failure at the job level.

  • If a complete batch must succeed or fail together, handle the batch as a unit.

  • If the worker itself cannot continue safely, allow the service to fail and rely on an appropriate recovery mechanism.

Do not treat every exception as a reason to continue.

Use PeriodicTimer for Recurring Background Operations

Many background services execute operations at regular intervals.

A common implementation uses Task.Delay() inside a while loop.

This works, but .NET also provides PeriodicTimer, which offers a convenient way to execute recurring operations.

Consider the following implementation:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        ILogger<NotificationBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(
            TimeSpan.FromMinutes(5));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                _logger.LogInformation(
                    "Starting notification processing.");

                await ProcessNotificationsAsync(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Notification processing failed.");
            }
        }
    }

    private Task ProcessNotificationsAsync(
        CancellationToken cancellationToken)
    {
        // Process pending notifications.

        return Task.CompletedTask;
    }
}

PeriodicTimer provides a tick at the configured interval.

The worker waits for the next tick, executes the operation, and waits for another tick.

If the operation fails, the exception is logged, and the loop continues waiting for subsequent ticks.

There is an important difference between this approach and a fixed delay after each execution.

With PeriodicTimer, ticks follow the timer's schedule. If an operation takes longer than the interval, missed ticks are not queued up as separate executions. The timer allows only one consumer to wait for ticks at a time.

This is useful for recurring operations where overlapping executions are not required.

If the requirement is to wait five minutes after a job completes before starting the next one, Task.Delay() after processing may be a better fit.

Choose the approach based on the required scheduling behavior.

Create a Dependency Injection Scope for Each Background Job

There is another issue developers often encounter when implementing BackgroundService.

Hosted services are registered as long-lived services.

By default, AddHostedService() registers the hosted service as a singleton.

This means you should not directly inject scoped dependencies, such as a DbContext, into the BackgroundService constructor.

Consider the following implementation:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly AppDbContext _dbContext;

    public NotificationBackgroundService(
        AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        // Background processing.
    }
}

Because AppDbContext is normally registered as scoped, injecting it directly into a singleton hosted service creates a lifetime mismatch.

It can also lead to problems with long-lived DbContext instances, including accumulated tracked entities and unexpected state.

The recommended approach is to inject IServiceScopeFactory and create a new scope for each execution.

For example:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        IServiceScopeFactory scopeFactory,
        ILogger<NotificationBackgroundService> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(
            TimeSpan.FromMinutes(5));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                await ProcessNotificationsAsync(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Notification processing failed.");
            }
        }
    }

    private async Task ProcessNotificationsAsync(
        CancellationToken cancellationToken)
    {
        await using var scope = _scopeFactory.CreateAsyncScope();

        var notificationService = scope.ServiceProvider
            .GetRequiredService<INotificationService>();

        await notificationService.ProcessPendingAsync(
            cancellationToken);
    }
}

Register the application services:

C#
builder.Services.AddScoped<INotificationService, NotificationService>();

builder.Services.AddHostedService<NotificationBackgroundService>();

Now each processing execution receives a new dependency injection scope.

The scoped services and DbContext instances are disposed when the scope is disposed.

This approach is particularly useful when background services interact with databases through Entity Framework Core.

It also keeps the background worker responsible for scheduling and lifecycle management while the actual business logic remains inside application services.

Add Retry Logic for Temporary Failures

Logging an exception and continuing with the next scheduled execution is useful, but it does not solve every problem.

Some failures are temporary.

For example:

  • Database connections may temporarily become unavailable.

  • An external API may return HTTP 503.

  • A network request may time out.

  • A message broker may temporarily reject a connection.

In these situations, retrying the operation may allow it to complete successfully without waiting for the next scheduled execution.

However, retries should be implemented carefully.

Retrying immediately without any delay can make the problem worse.

For example, if a database is already overloaded, repeatedly sending the same request can increase its load.

A better approach is to use exponential backoff.

With exponential backoff, the delay increases after each failed attempt.

For example:

Attempt

Retry Delay

1

1 second

2

2 seconds

3

4 seconds

4

8 seconds

5

Stop retrying

The exact retry policy depends on the operation and the type of failure.

Let's implement a simple retry method.

C#
private async Task ExecuteWithRetryAsync(
    Func<CancellationToken, Task> operation,
    CancellationToken cancellationToken)
{
    const int maxAttempts = 5;

    var delay = TimeSpan.FromSeconds(1);

    for (var attempt = 1; attempt <= maxAttempts; attempt++)
    {
        cancellationToken.ThrowIfCancellationRequested();

        try
        {
            await operation(cancellationToken);

            return;
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex) when (attempt < maxAttempts)
        {
            _logger.LogWarning(
                ex,
                "Operation failed on attempt {Attempt}. Retrying in {Delay}.",
                attempt,
                delay);

            await Task.Delay(delay, cancellationToken);

            delay = TimeSpan.FromSeconds(
                Math.Min(delay.TotalSeconds * 2, 30));
        }
    }
}

You can use it when processing notifications:

C#
await ExecuteWithRetryAsync(
    ProcessNotificationsAsync,
    stoppingToken);

In a real implementation, make sure the final failed attempt is also logged with enough context. The example above allows the final exception to propagate to the caller, where the outer background loop can log it.

Also, avoid retrying every exception.

For example, an invalid request, missing required data, or business validation failure is unlikely to succeed simply by trying again.

Retry policies should distinguish between transient failures and permanent failures.

For production applications, consider using the Polly resilience libraries or the resilience capabilities available through Microsoft.Extensions.Http.Resilience for HTTP operations.

These libraries provide additional capabilities such as retry policies, timeouts, circuit breakers, and jitter.

Make Background Jobs Idempotent Before Retrying

There is an important problem that developers sometimes overlook when implementing retries.

What happens if a job partially succeeds before an exception occurs?

Consider a payment processing operation.

The application sends a payment request to an external payment provider. The provider processes the payment successfully, but the response times out before the application receives it.

The application sees an exception and assumes the payment failed.

It retries the operation.

Now the same payment might be processed twice.

This is why idempotency is important.

An idempotent operation produces the same intended result when executed multiple times with the same identifier or request.

For example, instead of creating a new payment every time a request is retried, use a unique transaction identifier or idempotency key.

A simplified payment request might look like this:

C#
public class PaymentRequest
{
    public Guid IdempotencyKey { get; set; }

    public int OrderId { get; set; }

    public decimal Amount { get; set; }
}

The application can use the same idempotency key for every retry of the same logical payment operation.

The payment provider or application database can then detect whether the operation has already been processed.

The same principle applies to background jobs.

For example, if a notification is successfully sent but the worker fails before marking it as completed, the next execution may send the same notification again.

A robust implementation should use a unique job identifier and a persistent processing status.

Possible states include:

  • Pending

  • Processing

  • Completed

  • Failed

  • RetryScheduled

The application should update these states carefully so that retries do not create duplicate business operations.

For database-backed jobs, consider using transactions and concurrency controls when claiming work.

For operations involving external systems, use idempotency keys or equivalent deduplication mechanisms whenever possible.

Handle Cancellation Without Treating It as a Job Failure

Cancellation is another important part of background service development.

The hosting infrastructure provides a CancellationToken to ExecuteAsync().

This token is triggered when the application begins shutting down.

Your background service should pass this token to operations that support cancellation.

For example:

C#
protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        await ProcessNotificationsAsync(stoppingToken);

        await Task.Delay(
            TimeSpan.FromMinutes(5),
            stoppingToken);
    }
}

When the application begins shutting down, Task.Delay() observes the cancellation request and throws OperationCanceledException.

This is expected behavior.

It does not necessarily indicate that the background job failed.

For this reason, cancellation should be handled separately from ordinary exceptions.

Consider:

C#
try
{
    await ProcessNotificationsAsync(stoppingToken);
}
catch (OperationCanceledException)
    when (stoppingToken.IsCancellationRequested)
{
    _logger.LogInformation(
        "Background service is stopping.");
}
catch (Exception ex)
{
    _logger.LogError(
        ex,
        "Background processing failed.");
}

The distinction is important.

If the application is shutting down, the worker should stop gracefully rather than treating cancellation as an application failure.

Also remember that cancellation is cooperative.

Passing a token to a method does not guarantee that the method will stop immediately. The underlying operation must observe the token.

For example, database operations, HTTP requests, delays, and other asynchronous operations should receive the cancellation token whenever supported.

Use a Durable Queue for Important Background Jobs

A simple BackgroundService with a timer works well for recurring operations.

However, consider a different requirement.

An application receives thousands of jobs that must be processed reliably.

If the application restarts, pending jobs should not be lost.

A simple in-memory collection is not sufficient for this requirement.

For example:

C#
private readonly Queue<Notification> _notifications = new();

This queue exists only in application memory.

If the process crashes or the application restarts, the pending jobs disappear.

For important background operations, use a durable job store or message broker.

Examples include:

  • RabbitMQ

  • Apache Kafka

  • Azure Service Bus

  • Database-backed job queues

  • Hangfire

A durable queue stores pending work outside the lifetime of the application process.

The worker retrieves jobs, processes them, and acknowledges successful completion.

If processing fails, the job can be retried according to the queue's delivery and retry policies.

A typical message-processing workflow looks like this:

Code
       Message Published
              |
              v
        Durable Queue
              |
              v
        Background Worker
              |
              v
        Process Message
              |
         +----+----+
         |         |
       Success    Failure
         |         |
         v         v
      Acknowledge  Retry
         |         |
         v         v
      Completed   Dead Letter

A dead-letter queue is useful for messages that repeatedly fail and need investigation.

This prevents one problematic message from blocking the entire queue indefinitely.

However, durable messaging does not automatically guarantee exactly-once processing.

Most message-processing systems provide delivery guarantees that require consumers to handle duplicate deliveries safely.

Design consumers to be idempotent and acknowledge messages only after the required processing has completed.

A Complete Example of a Resilient BackgroundService

Let's bring these concepts together.

Suppose an application processes pending notifications every five minutes.

The background worker should:

  • Execute at regular intervals.

  • Create a new dependency injection scope for each execution.

  • Handle processing failures without stopping the worker.

  • Respect application cancellation.

  • Log errors with useful information.

First, define the application service:

C#
public interface INotificationService
{
    Task ProcessPendingAsync(
        CancellationToken cancellationToken);
}

Implement it:

C#
public class NotificationService : INotificationService
{
    private readonly AppDbContext _dbContext;
    private readonly ILogger<NotificationService> _logger;

    public NotificationService(
        AppDbContext dbContext,
        ILogger<NotificationService> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    public async Task ProcessPendingAsync(
        CancellationToken cancellationToken)
    {
        var notifications = await _dbContext.Notifications
            .Where(n => !n.IsProcessed)
            .OrderBy(n => n.CreatedAt)
            .Take(100)
            .ToListAsync(cancellationToken);

        foreach (var notification in notifications)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await SendNotificationAsync(
                    notification,
                    cancellationToken);

                notification.IsProcessed = true;
            }
            catch (OperationCanceledException)
                when (cancellationToken.IsCancellationRequested)
            {
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Failed to process notification {NotificationId}",
                    notification.Id);
            }
        }

        await _dbContext.SaveChangesAsync(cancellationToken);
    }

    private Task SendNotificationAsync(
        Notification notification,
        CancellationToken cancellationToken)
    {
        // Integrate with the notification provider.

        return Task.CompletedTask;
    }
}

Now implement the BackgroundService:

C#
public class NotificationBackgroundService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<NotificationBackgroundService> _logger;

    public NotificationBackgroundService(
        IServiceScopeFactory scopeFactory,
        ILogger<NotificationBackgroundService> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(
            TimeSpan.FromMinutes(5));

        _logger.LogInformation(
            "Notification background service started.");

        try
        {
            while (await timer.WaitForNextTickAsync(stoppingToken))
            {
                try
                {
                    await ProcessNotificationsAsync(stoppingToken);
                }
                catch (OperationCanceledException)
                    when (stoppingToken.IsCancellationRequested)
                {
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(
                        ex,
                        "Notification processing cycle failed.");
                }
            }
        }
        catch (OperationCanceledException)
            when (stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Notification background service is stopping.");
        }
    }

    private async Task ProcessNotificationsAsync(
        CancellationToken cancellationToken)
    {
        await using var scope = _scopeFactory.CreateAsyncScope();

        var notificationService = scope.ServiceProvider
            .GetRequiredService<INotificationService>();

        await notificationService.ProcessPendingAsync(
            cancellationToken);
    }
}

Register the services in Program.cs:

C#
builder.Services.AddScoped<
    INotificationService,
    NotificationService>();

builder.Services.AddHostedService<
    NotificationBackgroundService>();

This implementation separates the responsibilities clearly.

NotificationBackgroundService manages scheduling, cancellation, and the overall execution loop.

NotificationService handles the actual notification processing and database operations.

A new dependency injection scope is created for each processing cycle, so the application does not keep one DbContext instance alive for the entire lifetime of the worker.

Individual notification failures are logged without preventing the remaining notifications from being attempted.

If the complete processing cycle encounters an unexpected exception, the outer background loop catches it and continues with the next timer tick.

This is a reasonable starting point for recurring background operations.

There are still production considerations to address.

For example, if multiple application instances run simultaneously, they may retrieve and process the same pending notifications. You need a concurrency-safe job claiming mechanism, such as database locking, atomic status updates, or a durable queue.

Also, in this example, failed notifications remain unprocessed and may be attempted again during the next cycle. A production system should maintain retry counts, last-attempt timestamps, failure details, and a maximum retry policy.

The example demonstrates the worker lifecycle and exception-handling structure rather than a complete distributed job-processing system.

Should You Use BackgroundServiceExceptionBehavior.Ignore?

ASP.NET Core provides another option through HostOptions.BackgroundServiceExceptionBehavior.

Developers sometimes consider using Ignore to prevent an unhandled background service exception from stopping the host.

For example:

C#
builder.Services.Configure<HostOptions>(options =>
{
    options.BackgroundServiceExceptionBehavior =
        BackgroundServiceExceptionBehavior.Ignore;
});

This changes the host's response to unhandled BackgroundService exceptions.

However, there is an important detail.

Ignore does not restart the failed BackgroundService.

It tells the host to log the exception and otherwise ignore it. The failed ExecuteAsync() task has still completed, so the background service is no longer running its processing loop.

This means the application can remain available while the background service has stopped working.

For most recurring background operations, this is not what you want.

It is generally better to catch recoverable exceptions inside the execution loop so that the worker can continue deliberately.

Use Ignore only when its behavior is specifically appropriate for the application and you have a separate strategy for detecting and recovering from a stopped worker.

Do not use it as a replacement for exception handling.

Monitoring Background Services in Production

Keeping a BackgroundService running after a failure is only one part of building a reliable background processing system.

You also need to know whether the worker is actually doing its job.

An application can remain healthy from an HTTP perspective while its background processing is delayed or failing repeatedly.

This is why monitoring is important.

Consider tracking the following information:

Metric

Why It Matters

Last successful execution

Shows when the worker last completed successfully

Processing duration

Identifies slow background operations

Failed job count

Shows how frequently jobs fail

Retry count

Helps identify repeated failures

Pending job count

Shows whether work is accumulating

Oldest pending job age

Identifies processing delays

Worker heartbeat

Confirms that the worker is still active

For example, a background worker might log:

C#
_logger.LogInformation(
    "Processed {ProcessedCount} notifications in {Duration} ms.",
    processedCount,
    stopwatch.ElapsedMilliseconds);

When an error occurs:

C#
_logger.LogError(
    exception,
    "Notification processing failed for batch {BatchId}.",
    batchId);

Use structured logging so that important fields can be searched and analyzed through your logging platform.

For more critical workloads, expose metrics through a monitoring system and configure alerts for conditions such as:

  • No successful processing within the expected interval.

  • A continuously increasing pending job count.

  • Repeated failures.

  • Jobs exceeding their maximum retry count.

  • An inactive worker heartbeat.

Logging tells you what happened. Monitoring helps you identify when the system is no longer operating as expected.

Common Mistakes Developers Should Avoid

There are a few mistakes that can make background processing unreliable even when exception handling is present.

Catching Every Exception and Ignoring It

Consider:

C#
try
{
    await ProcessJobAsync();
}
catch
{
}

This prevents exceptions from escaping, but it also hides the reason for failure.

Always log meaningful error information and decide what should happen to the failed job.

Assuming Ignore Restarts the BackgroundService

BackgroundServiceExceptionBehavior.Ignore does not restart the worker.

The host continues running, but the failed service does not automatically begin executing again.

Handle recoverable exceptions inside the execution loop or use an external worker recovery strategy.

Retrying Every Exception

Not every failure is temporary.

Retrying an invalid request or a business validation failure repeatedly wastes resources.

Classify failures and retry only those that can reasonably succeed later.

Retrying Without Idempotency

A partially completed operation may be executed more than once.

Use unique job identifiers, idempotency keys, and appropriate transaction or deduplication strategies.

Injecting Scoped Dependencies Directly Into BackgroundService

Background services are generally singletons.

Use IServiceScopeFactory to create scopes for operations that require scoped dependencies such as DbContext.

Ignoring Cancellation Tokens

If a worker ignores the stopping token, application shutdown may take longer or terminate before processing is completed.

Pass cancellation tokens to asynchronous operations and handle expected cancellation separately from processing failures.

Using In-Memory Queues for Critical Jobs

In-memory queues can lose pending work when the application restarts or crashes.

Use durable storage or a message broker when jobs must survive application failures.

Allowing Multiple Workers to Process the Same Job

Running multiple application instances can introduce duplicate processing.

Use concurrency-safe job claiming, message acknowledgment, or database locking strategies to coordinate workers.

Conclusion

BackgroundService is a useful feature in ASP.NET Core for implementing recurring and long-running operations. However, a reliable background worker needs more than a while loop and a call to Task.Delay().

An unhandled exception from ExecuteAsync() can stop the background service and, by default, cause the Generic Host to stop as well.

If individual jobs are expected to fail independently, handle exceptions inside the processing loop rather than allowing one failed operation to terminate the worker.

Use appropriate retry policies for temporary failures, make operations idempotent, create dependency injection scopes for scoped services, and respect cancellation tokens during application shutdown.

For important background workloads, also consider durable queues, concurrency control, monitoring, and failure recovery.

The main design principle is to separate the lifetime of the background worker from the success or failure of an individual job.

A failed job should not automatically stop the entire worker. At the same time, keeping a worker alive should never mean silently ignoring errors.

A reliable background processing system should know when to retry, when to skip, when to record a permanent failure, and when the entire service genuinely needs to stop.