Advertisement

Background Tasks & Hosted Services interview questions and answers

15 Background Tasks & Hosted Services interview questions for ASP.NET Core roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you implement retry logic with exponential backoff for a background service that calls a potentially-flaky external API?

Combine a retry policy (hand-rolled, or via a library like Polly) wrapping each unit of work with exponentially increasing delays between attempts, distinguishing between transient failures (worth retrying, like network timeouts) and permanent failures (should be logged and skipped, not retried indefinitely) to avoid an infinite retry loop on genuinely unrecoverable errors.
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));

protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    while (!stoppingToken.IsCancellationRequested) {
        await retryPolicy.ExecuteAsync(() => CallExternalApiAsync());
        await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
    }
}
Real-world example
A background service integrating with a flaky third-party payment provider uses Polly's exponential backoff to gracefully absorb transient network issues, only escalating to an alert after three consecutive failed attempts.
Likely follow-ups
  • How do you distinguish transient from permanent failures programmatically?
  • What is a dead-letter mechanism and how does it complement retry logic?
Diagnostics & Performance gRPC Services
Q12 Intermediate Save

How does IHostApplicationLifetime let a BackgroundService react to application startup and shutdown events?

IHostApplicationLifetime exposes ApplicationStarted, ApplicationStopping, and ApplicationStopped CancellationTokens/events you can register callbacks against, letting a service run logic precisely when the application has fully started (useful for deferring work until all other services are ready) or precisely when shutdown begins (for final cleanup logic distinct from the service's own StopAsync).
public class MyService(IHostApplicationLifetime lifetime) : BackgroundService {
    protected override Task ExecuteAsync(CancellationToken stoppingToken) {
        lifetime.ApplicationStarted.Register(() => _logger.LogInformation("App fully started"));
        lifetime.ApplicationStopping.Register(() => _logger.LogInformation("App stopping..."));
        return Task.CompletedTask;
    }
}
Real-world example
A service registration hook waits for ApplicationStarted before announcing itself to a service discovery system, ensuring it only advertises availability once the entire application (including all other hosted services) has successfully completed startup.
Likely follow-ups
  • How does ApplicationStopping differ from the CancellationToken passed to ExecuteAsync?
  • What happens if a callback registered on ApplicationStopping throws an exception?
Hosting Models: Kestrel IIS & Reverse Proxies Health Checks
Q13 Advanced Save

How would you implement a background task queue accepting ad-hoc work items dynamically at runtime, rather than a fixed polling loop?

A common pattern defines an IBackgroundTaskQueue interface backed by a Channel<Func<CancellationToken, Task>>, with a QueueBackgroundWorkItem method that any part of the application (like a controller action) can call to enqueue arbitrary async work, while a single BackgroundService continuously dequeues and executes items from the channel -- decoupling 'something needs background processing' (raised anywhere in the app) from 'how background processing actually happens' (centralized in one consumer).
public interface IBackgroundTaskQueue {
    void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem);
    Task<Func<CancellationToken, Task>> DequeueAsync(CancellationToken ct);
}

// Controller usage:
_taskQueue.QueueBackgroundWorkItem(async ct => await SendWelcomeEmailAsync(userId, ct));
Real-world example
A user-registration endpoint enqueues a 'send welcome email' work item onto the background task queue and returns immediately to the client, with a single dedicated BackgroundService processing that (and any other queued) work item asynchronously afterward.
Likely follow-ups
  • How does this pattern handle a work item that throws an exception?
  • What are the durability trade-offs of an in-memory Channel-based queue versus a persistent message broker?
Concurrency (asyncio/threading/multiprocessing) Error Handling
Q14 Intermediate Save

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

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.
Likely follow-ups
  • When is 'fail fast' the wrong choice for a background service?
  • How does the default BackgroundServiceExceptionBehavior.Ignore differ from StopHost?
Hosting Models: Kestrel IIS & Reverse Proxies Diagnostics & Performance
Q15 Advanced Save

How do you test a BackgroundService's business logic without waiting for its actual polling interval, keeping tests fast?

Extract the actual work logic (the part done inside each loop iteration) into a separate, directly-testable method or injected service, and unit test that in isolation with normal fast unit tests -- reserve testing the BackgroundService class itself (its loop, cancellation handling, scope creation) for a smaller number of targeted integration-style tests that might use a very short injected interval or directly invoke ExecuteAsync with a pre-cancelled token to test just one iteration without an actual wait.
// Testable: extracted work logic
public interface IOrderProcessingWork {
    Task ProcessPendingOrdersAsync(CancellationToken ct);
}

[Fact]
public async Task ProcessPendingOrders_MarksOrdersAsShipped() {
    var work = new OrderProcessingWork(mockRepo.Object);
    await work.ProcessPendingOrdersAsync(CancellationToken.None);
    mockRepo.Verify(r => r.MarkAsShipped(It.IsAny<int>()), Times.Once);
}
Real-world example
A team refactors a monolithic BackgroundService (with all logic embedded directly in ExecuteAsync) into a thin loop delegating to an injected, independently-testable work service, cutting their test suite's runtime from minutes (waiting on real Task.Delay intervals) to milliseconds.
Likely follow-ups
  • How would you test the actual BackgroundService's cancellation and scope-creation behavior specifically?
  • What's the risk of testing only the extracted logic and never the loop itself?
Testing ASP.NET Core Applications Dependency Injection

Showing 11–15 of 15