IC Improve Code Recipes

Recipe 14.5 · Python

Graceful Shutdown

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

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.

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.

Requirements: Python 3.12+. Install: pip install pywin32 · Needs at run time: Windows (admin rights to install the service). The module loads without them; calling the code does not work without them.

Python Stop a service by aborting its worker thread or exiting the process (p316_r14_5_abort_worker_on_stop_before.py)
"""Stop a service by aborting its worker thread or exiting the process

Source: ImproveCode, Chapter 14, Recipe 14.5 "Graceful Shutdown"
Section: The way it's often written
Book page: 316  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Thread.Abort -> injecting SystemExit into the thread via ctypes PyThreadState_SetAsyncExc
(Python's closest equivalent); Environment.Exit(0) -> os._exit(0); OnStop -> pywin32 SvcStop.
"""

from __future__ import annotations

import ctypes
import threading

import win32serviceutil


class SyncService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SyncService"
    _svc_display_name_ = "Sync Service"

    _worker: threading.Thread

    # Not to copy: the process ends wherever the work happens to be
    def SvcStop(self) -> None:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(  # the "Thread.Abort"
            ctypes.c_ulong(self._worker.ident or 0), ctypes.py_object(SystemExit))
        # or: os._exit(0)

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.

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

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Import item record and the queue/processor contracts (p316_r14_5_import_queue_contracts.py)
"""Import item record and the queue/processor contracts

Source: ImproveCode, Chapter 14, Recipe 14.5 "Graceful Shutdown"
Section: The improved recipe
Book page: 316-317  -- original C# listing
Converted from C# to Python.
Record -> frozen dataclass; interfaces -> typing.Protocol. The CancellationToken
parameters are dropped: callers bound each call with asyncio.timeout, and cancellation
reaches the implementation as asyncio.CancelledError.
"""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from typing import Protocol


@dataclass(frozen=True)
class ImportItem:
    id: int
    payload: str


class IImportQueue(Protocol):
    async def claim_batch(self, size: int) -> Sequence[ImportItem]: ...

    async def release(self, items: Sequence[ImportItem]) -> None: ...


class IImportProcessor(Protocol):
    async def process(self, item: ImportItem) -> None: ...

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Import worker that finishes the current item and releases the rest on stop (p317_r14_5_import_worker_graceful_stop.py)
"""Import worker that finishes the current item and releases the rest on stop

Source: ImproveCode, Chapter 14, Recipe 14.5 "Graceful Shutdown"
Section: The improved recipe
Book page: 317-318  -- original C# listing
Converted from C# to Python.
BackgroundService -> the asyncio stand-in from the 14.1 module (stopping Event);
CancellationTokenSource(timeout) -> asyncio.timeout, so a started item gets its own
deadline instead of being torn by the stop signal.
"""

from __future__ import annotations

import asyncio
import logging
from datetime import timedelta

from p302_r14_1_timed_job_background_service import BackgroundService, wait_or_stopped
from p316_r14_5_import_queue_contracts import IImportProcessor, IImportQueue


class ImportWorker(BackgroundService):
    _IDLE_DELAY = timedelta(seconds=10)
    _ITEM_TIMEOUT = timedelta(seconds=20)

    def __init__(
            self,
            queue: IImportQueue,
            processor: IImportProcessor,
            logger: logging.Logger | None = None) -> None:
        super().__init__()
        self._queue = queue
        self._processor = processor
        self._logger = logger or logging.getLogger(f"{__name__}.ImportWorker")

    async def execute(self, stopping: asyncio.Event) -> None:
        while not stopping.is_set():
            batch = await self._queue.claim_batch(50)
            if len(batch) == 0:
                if await wait_or_stopped(stopping, self._IDLE_DELAY.total_seconds()):
                    return
                continue

            for i, item in enumerate(batch):
                if stopping.is_set():
                    rest = list(batch[i:])
                    async with asyncio.timeout(5):
                        await self._queue.release(rest)
                    self._logger.info("Stopping; released %d items", len(rest))
                    return

                # The item gets its own deadline, not the stopping
                # signal, so a started item is finished, not torn.
                async with asyncio.timeout(self._ITEM_TIMEOUT.total_seconds()):
                    await self._processor.process(item)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Configure host shutdown timeout and failure behaviour (p318_r14_5_configure_graceful_shutdown.py)
"""Configure host shutdown timeout and failure behaviour

Source: ImproveCode, Chapter 14, Recipe 14.5 "Graceful Shutdown"
Section: The improved recipe
Book page: 318  -- original C# listing
Converted from C# to Python.
services.Configure<HostOptions> -> setting fields on the HostOptions of the asyncio Host
stand-in from the 14.1 module (StopHost -> stop_host_on_exception=True).
"""

from __future__ import annotations

from datetime import timedelta

from p302_r14_1_timed_job_background_service import HostOptions


def configure_graceful_shutdown(
        options: HostOptions, shutdown_timeout: timedelta) -> HostOptions:
    options.shutdown_timeout = shutdown_timeout
    options.stop_host_on_exception = True  # BackgroundServiceExceptionBehavior.StopHost
    options.services_stop_concurrently = True
    return options

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.