Recipe 14.4 · Python
In-Process Queues With System.Threading.Channels
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 web request needs to start work that takes longer than the user should wait: sending a receipt e-mail, generating a PDF, calling a slow partner. You want to return immediately and do the work in the background, with a limit on how much can pile up and a fixed number of workers.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Task.Run from a request has no limit: a burst of orders starts a burst of concurrent sends. If
_email is scoped to the request, it may be disposed before the task runs. Exceptions are lost.
And at shutdown, the host doesn't know the tasks exist, so it stops without waiting for them.
Requirements: Python 3.12+. Install: pip install fastapi pydantic
"""Checkout that fires and forgets the receipt email
Source: ImproveCode, Chapter 14, Recipe 14.4 "In-Process Queues With System.Threading.Channels"
Section: The way it's often written
Book page: 312 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
MVC action -> FastAPI route; Task.Run fire-and-forget -> an unobserved daemon thread;
RedirectToAction -> RedirectResponse.
"""
from __future__ import annotations
import threading
from typing import Protocol
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
class Order(BaseModel):
id: int
class OrderRepository(Protocol):
def save(self, order: Order) -> None: ...
class ReceiptEmailer(Protocol):
def send_receipt(self, order_id: int) -> None: ...
_orders: OrderRepository
_email: ReceiptEmailer
app = FastAPI()
# Not to copy: unbounded, unobserved, dies with the request scope
@app.post("/checkout")
def checkout(order: Order) -> RedirectResponse:
_orders.save(order)
threading.Thread( # fire and forget
target=_email.send_receipt, args=(order.id,), daemon=True).start()
return RedirectResponse("/thanks", status_code=303)
The improved recipe
A bounded Channel<T> is the queue, a hosted service runs a fixed number of consumers, and each
item is handled in its own scope.
Usage in an ASP.NET Core app, with a small message record and a handler that sends the e-mail (Chapter 9 covers the sending):
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Bounded in-process background queue with completion
Source: ImproveCode, Chapter 14, Recipe 14.4 "In-Process Queues With System.Threading.Channels"
Section: The improved recipe
Book page: 312-313 -- original C# listing
Converted from C# to Python.
Channel.CreateBounded(FullMode.Wait) -> asyncio.Queue(maxsize) plus a completion Event,
so readers drain the remaining items and then stop (ReadAllAsync semantics);
IQueueHandler<T> -> typing.Protocol.
"""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
from typing import Protocol
class ChannelClosedError(Exception):
pass
class IQueueHandler[T](Protocol):
async def handle(self, item: T, stopping: asyncio.Event) -> None: ...
class BackgroundQueue[T]:
def __init__(self, capacity: int) -> None:
self._queue: asyncio.Queue[T] = asyncio.Queue(maxsize=capacity)
self._completed = asyncio.Event()
@property
def count(self) -> int:
return self._queue.qsize()
async def enqueue(self, item: T) -> None:
"""Waits while the queue is full."""
if self._completed.is_set():
raise ChannelClosedError("The queue has been completed.")
await self._queue.put(item)
def try_enqueue(self, item: T) -> bool:
"""Returns False at once if the queue is full."""
if self._completed.is_set():
return False
try:
self._queue.put_nowait(item)
return True
except asyncio.QueueFull:
return False
def complete(self) -> None:
self._completed.set()
async def read_all(self) -> AsyncIterator[T]:
"""Yields items until the queue is completed and empty."""
while True:
if not self._queue.empty():
yield self._queue.get_nowait()
continue
if self._completed.is_set():
return
get = asyncio.ensure_future(self._queue.get())
done_wait = asyncio.ensure_future(self._completed.wait())
await asyncio.wait({get, done_wait}, return_when=asyncio.FIRST_COMPLETED)
done_wait.cancel()
if get.done():
yield get.result()
else:
get.cancel()
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Register a background queue, its handler and its workers
Source: ImproveCode, Chapter 14, Recipe 14.4 "In-Process Queues With System.Threading.Channels"
Section: The improved recipe
Book page: 313 -- original C# listing
Converted from C# to Python.
AddSingleton/AddScoped/AddHostedService -> creating the singleton queue, appending a
QueueWorkerService to the host's service list and returning the queue to the caller.
"""
from __future__ import annotations
import logging
from collections.abc import Callable
from p302_r14_1_timed_job_background_service import BackgroundService
from p312_r14_4_bounded_background_queue import BackgroundQueue, IQueueHandler
from p313_r14_4_queue_worker_service_drain import QueueWorkerService
def add_background_queue[T](
services: list[BackgroundService],
handler_factory: Callable[[], IQueueHandler[T]],
capacity: int = 1000,
workers: int = 1) -> BackgroundQueue[T]:
queue = BackgroundQueue[T](capacity)
services.append(QueueWorkerService(
queue,
handler_factory,
logging.getLogger(f"{__name__}.QueueWorkerService"),
workers))
return queue
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Queue worker service that drains the queue on shutdown
Source: ImproveCode, Chapter 14, Recipe 14.4 "In-Process Queues With System.Threading.Channels"
Section: The improved recipe
Book page: 313-314 -- original C# listing
Converted from C# to Python.
BackgroundService -> the asyncio stand-in from the 14.1 module; Task.WhenAll of N workers
-> asyncio.gather; the StopAsync override completes the queue and waits up to the
shutdown timeout before signalling stopping; scoped handler -> a factory called per item.
"""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Callable
from p302_r14_1_timed_job_background_service import BackgroundService
from p312_r14_4_bounded_background_queue import BackgroundQueue, IQueueHandler
class QueueWorkerService[T](BackgroundService):
def __init__(
self,
queue: BackgroundQueue[T],
handler_factory: Callable[[], IQueueHandler[T]],
logger: logging.Logger,
worker_count: int) -> None:
super().__init__()
self._queue = queue
self._handler_factory = handler_factory
self._logger = logger
self._worker_count = worker_count
async def execute(self, stopping: asyncio.Event) -> None:
await asyncio.gather(
*(self._work(stopping) for _ in range(self._worker_count)))
async def stop(self, timeout: float) -> None:
# Stop accepting work, then let the workers drain the queue
# until the host's shutdown timeout runs out.
self._queue.complete()
if self.execute_task is not None:
await asyncio.wait({self.execute_task}, timeout=timeout)
# Like base.StopAsync after the timeout: signal stopping, do not wait.
self._stopping.set()
async def _work(self, stopping: asyncio.Event) -> None:
async for item in self._queue.read_all():
if stopping.is_set():
self._logger.warning(
"Shutdown timeout: %d queued items abandoned",
self._queue.count + 1)
return
try:
await self._handler_factory().handle(item, stopping)
except Exception:
self._logger.exception("Failed to handle %r", item)
Requirements: Python 3.12+. Install: pip install fastapi
"""Endpoint that enqueues a receipt and returns 202 Accepted
Source: ImproveCode, Chapter 14, Recipe 14.4 "In-Process Queues With System.Threading.Channels"
Section: The improved recipe
Book page: 314-315 -- original C# listing
Converted from C# to Python.
Minimal API MapPost -> FastAPI route; the hosted workers start and stop in the app
lifespan. SendReceipt and its handler are minimal stand-ins for types used by the snippet.
"""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from fastapi import FastAPI, Response
from p302_r14_1_timed_job_background_service import BackgroundService, Host
from p313_r14_4_add_background_queue_registration import add_background_queue
@dataclass(frozen=True)
class SendReceipt:
order_id: int
class SendReceiptHandler:
async def handle(self, item: SendReceipt, stopping: asyncio.Event) -> None:
... # send the receipt email
services: list[BackgroundService] = []
receipt_queue = add_background_queue(
services, SendReceiptHandler, capacity=500, workers=4)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
host = Host(services)
await host.start()
try:
yield
finally:
await host.stop()
app = FastAPI(lifespan=lifespan)
@app.post("/orders/{id}/receipt")
async def queue_receipt(id: int) -> Response:
await receipt_queue.enqueue(SendReceipt(id))
return Response(status_code=202)
How it works
A channel is a thread-safe producer-consumer queue built for async code. WriteAsync adds an
item, and ReadAllAsync yields items as they arrive, waiting without blocking a thread when the
queue is empty. Many producers and many consumers can use it at once.
The capacity is the important design choice. With BoundedChannelFullMode.Wait, a full queue
makes EnqueueAsync wait until a worker frees a slot. That is backpressure: under a burst, callers
slow down instead of the process filling memory with a million pending items. When a caller
should never wait, such as a request handler with a strict latency budget, use TryEnqueue and
return 503 Service Unavailable when it returns false.
QueueWorkerService starts workerCount loops that read from the same channel, so at most that
many items are handled at once. Each item gets its own scope, which gives the handler fresh scoped
services, unlike the request-scoped services that Task.Run captured.
Shutdown is ordered. StopAsync completes the writer first, so no new items are accepted. The
workers keep reading until the queue is empty, at which point ReadAllAsync ends and so does
ExecuteAsync. Only if the host's shutdown timeout runs out first is the stoppingToken
cancelled, the in-flight handlers told to stop, and the remainder logged as abandoned.
I tested the queue with a capacity of 10, four workers and 1,000 items from two producers: all
1,000 were handled exactly once, and items still queued when the host was stopped were drained
before StopAsync returned.
Variations and pitfalls
- The queue lives in memory. If the process crashes or the server reboots, queued items are gone. For anything that must not be lost, such as payments or regulatory filings, write the work to a database table or a durable broker first, and use the channel only to wake a worker. Or use Hangfire (Recipe 14.6).
- One queue per message type.
BackgroundQueue<SendReceipt>andBackgroundQueue<BuildPdf>are separate singletons with separate capacities and worker counts. Slow PDFs then cannot starve e-mail. - Retries. A handler that fails is logged and dropped. Add a retry with backoff inside the handler (Chapter 5), or re-enqueue with an attempt counter on the message record.
- Unbounded channels.
Channel.CreateUnbounded<T>()is fine when the producer is naturally limited, such as a file watcher. For anything driven by user traffic, always set a bound.