IC Improve Code Recipes

Recipe 14.5 · C#

Graceful Shutdown

Problem

A deployment restarts the service in the middle of an import. Half the batch is committed, the other half is lost, and the file is marked as processed. Or the host waits for a job that ignores cancellation, the shutdown timeout passes, and the process is killed in the middle of a database write.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: the process ends wherever the work happens to be
protected override void OnStop()
{
    _worker.Abort();               // gone in modern .NET
    // or: Environment.Exit(0);
}

Thread.Abort throws PlatformNotSupportedException on .NET 5 and later, which is a mercy. Both it and Environment.Exit stop the work at an arbitrary point instead of at a safe one.

The improved recipe

Decide what a safe stopping point is, check the token only there, and give the host enough time to reach it. The worker below claims a batch of import items, stops between items when asked, and returns unprocessed items to the queue.

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Jobs;

public sealed record ImportItem(long Id, string Payload);

public interface IImportQueue
{
    Task<IReadOnlyList<ImportItem>> ClaimBatchAsync(
        int size, CancellationToken ct);

    Task ReleaseAsync(
        IReadOnlyList<ImportItem> items, CancellationToken ct);
}

public interface IImportProcessor
{
    Task ProcessAsync(ImportItem item, CancellationToken ct);
}
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ImproveCode.Jobs;

public sealed class ImportWorker(
    IImportQueue queue,
    IImportProcessor processor,
    ILogger<ImportWorker> logger) : BackgroundService
{
    private static readonly TimeSpan IdleDelay = TimeSpan.FromSeconds(10);
    private static readonly TimeSpan ItemTimeout =
        TimeSpan.FromSeconds(20);

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            IReadOnlyList<ImportItem> batch =
                await queue.ClaimBatchAsync(50, stoppingToken);
            if (batch.Count == 0)
            {
                await Task.Delay(IdleDelay, stoppingToken);
                continue;
            }

            for (int i = 0; i < batch.Count; i++)
            {
                if (stoppingToken.IsCancellationRequested)
                {
                    List<ImportItem> rest = batch.Skip(i).ToList();
                    using var release = new CancellationTokenSource(
                        TimeSpan.FromSeconds(5));
                    await queue.ReleaseAsync(rest, release.Token);
                    logger.LogInformation(
                        "Stopping; released {Count} items", rest.Count);
                    return;
                }

                // The item gets its own deadline, not the stopping
                // token, so a started item is finished, not torn.
                using var itemCts = new CancellationTokenSource(
                    ItemTimeout);
                await processor.ProcessAsync(batch[i], itemCts.Token);
            }
        }
    }
}
C#
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ImproveCode.Jobs;

public static class ShutdownServiceCollectionExtensions
{
    public static IServiceCollection ConfigureGracefulShutdown(
        this IServiceCollection services, TimeSpan shutdownTimeout)
    {
        services.Configure<HostOptions>(options =>
        {
            options.ShutdownTimeout = shutdownTimeout;
            options.BackgroundServiceExceptionBehavior =
                BackgroundServiceExceptionBehavior.StopHost;
            options.ServicesStopConcurrently = true;
        });
        return services;
    }
}

In Program.cs, give the host more time than the longest item: builder.Services.ConfigureGracefulShutdown(TimeSpan.FromSeconds(45));

How it works

The host's shutdown sequence is simple. On a stop request it calls StopAsync on every hosted service, which for a BackgroundService cancels the stoppingToken, then waits for ExecuteAsync to finish or for ShutdownTimeout to pass, whichever comes first. The default timeout is 30 seconds. After that, the host moves on and the process ends, finished or not.

So graceful shutdown is a contract between you and the host. You promise to reach a safe point quickly after cancellation, and the host promises to wait that long. ImportWorker keeps its side by checking the token only between items. The item in progress runs with its own 20-second deadline, so a stop request never tears one item in half. Unstarted items go back to the queue, which in a database usually means clearing a ClaimedBy column, so another instance or the next start picks them up.

ConfigureGracefulShutdown sets the host's side: a timeout longer than the longest item plus the release call. ServicesStopConcurrently (new in .NET 8) stops all hosted services in parallel, so three services with 20 seconds of work each need 20 seconds, not 60. BackgroundServiceExceptionBehavior.StopHost is the default since .NET 6, and setting it explicitly documents that a crashed worker should stop the process rather than leave a zombie.

Variations and pitfalls

  • Respect the outer limits. Windows gives services only a limited time at system shutdown, and Kubernetes kills a pod after its terminationGracePeriodSeconds, 30 seconds by default. Keep ShutdownTimeout below the platform's limit, or raise both together.
  • Make items idempotent. A crash, a power cut or a killed process still stops work mid-item. Design each item so that processing it twice is harmless: upsert instead of insert, and record the item as done in the same transaction as its effects.
  • IHostApplicationLifetime. Inject it to run code on ApplicationStopping, or to stop the application yourself with StopApplication() when a run-once console job finishes.
  • Don't swallow cancellation. A catch (Exception) that wraps the whole loop also catches OperationCanceledException, and the loop keeps running after the host asked it to stop. Rethrow cancellation when the stopping token is cancelled, as Recipe 14.1 does.
  • Test it. Stop the service in the middle of a long batch. The log should show the released item count, and no item should be half-written.