Recipe 9.4 · Python
Queueing and Retrying
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
Sending mail inline in a web request couples the user's experience to the mail relay. When the relay is slow, the page is slow. When the relay is down, the user gets an error for an action that actually succeeded, such as placing an order. And a transient failure, like a relay that says "try again later," is treated the same as a permanent one, like a mailbox that does not exist.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
When the send fails, the order is saved but the user is told it was not, and often places it again.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Sending mail inline so an SMTP failure looks like a failed order
Source: ImproveCode, Chapter 9, Recipe 9.4 "Queueing and Retrying"
Section: The way it's often written
Book page: 196 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Helpers are passed in as callables; traceback.format_exc() stands in for ex.ToString().
"""
import traceback
from collections.abc import Callable
from typing import Any
def place_order(order: Any, body: str, lbl_message: Any,
save_order: Callable[[Any], None],
send_email: Callable[[str, str, str], None],
log_write: Callable[[str], None]) -> None:
try:
save_order(order)
send_email(order.email, "Order received", body)
except Exception:
lbl_message.text = "Your order could not be placed."
log_write(traceback.format_exc())
The improved recipe
The request puts the message on an in-process queue and returns. A hosted background service reads the queue, sends with retries and exponential backoff for transient failures, and logs permanent failures without retrying them. The queue uses System.Threading.Channels (covered in depth in Chapter 14).
NuGet packages: MailKit, Microsoft.Extensions.Hosting.Abstractions.
A usage snippet for registration and for the request path:
Requirements: Python 3.12+. Install: pip install aiosmtplib · Needs at run time: an SMTP server. The module loads without them; calling the code does not work without them.
"""Bounded e-mail queue and background dispatcher with transient retry
Source: ImproveCode, Chapter 9, Recipe 9.4 "Queueing and Retrying"
Section: The improved recipe
Book page: 196-198 -- original C# listing
Converted from C# to Python.
asyncio.Queue(maxsize=1000) replaces the bounded Channel; the BackgroundService
becomes an asyncio task; aiosmtplib exceptions replace MailKit's.
"""
import asyncio
import logging
import random
from email.message import EmailMessage
import aiosmtplib
from p185_r9_1_async_smtp_email_sender import EmailSender
class EmailQueue:
def __init__(self) -> None:
self._queue: asyncio.Queue[EmailMessage] = asyncio.Queue(maxsize=1000)
async def enqueue_async(self, message: EmailMessage) -> None:
if message is None:
raise TypeError("message must not be None.")
await self._queue.put(message) # waits when full
@property
def reader(self) -> "asyncio.Queue[EmailMessage]":
return self._queue
class EmailDispatcher:
MAX_ATTEMPTS = 5
def __init__(self, queue: EmailQueue, sender: EmailSender,
logger: logging.Logger | None = None) -> None:
self._queue = queue
self._sender = sender
self._logger = logger or logging.getLogger(__name__)
self._task: asyncio.Task[None] | None = None
def start(self) -> None:
self._task = asyncio.create_task(self.execute_async())
async def stop(self) -> None:
if self._task is not None:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
async def execute_async(self) -> None:
while True:
message = await self._queue.reader.get()
try:
await self._send_with_retry_async(message)
finally:
self._queue.reader.task_done()
async def _send_with_retry_async(self, message: EmailMessage) -> None:
attempt = 1
while True:
try:
await self._sender.send_async(message)
return
except asyncio.CancelledError:
raise
except Exception as ex:
if self.is_transient(ex) and attempt < self.MAX_ATTEMPTS:
delay = 2 ** attempt + random.random()
self._logger.warning(
"Send of %s failed (attempt %d); retrying in %.1fs",
message["Message-ID"], attempt, delay, exc_info=ex)
await asyncio.sleep(delay)
attempt += 1
continue
self._logger.error(
"Giving up on %s to %s after %d attempt(s)",
message["Message-ID"], message["To"], attempt, exc_info=ex)
return
@staticmethod
def is_transient(ex: BaseException) -> bool:
match ex:
case aiosmtplib.SMTPResponseException(code=code):
return 400 <= code < 500
case aiosmtplib.SMTPServerDisconnected():
return True
case aiosmtplib.SMTPConnectError() | aiosmtplib.SMTPTimeoutError():
return True
case TimeoutError() | ConnectionError() | OSError():
return True
case _:
return False
Requirements: Python 3.12+. Install: pip install fastapi
"""Registering the queue and dispatcher, then enqueueing a confirmation
Source: ImproveCode, Chapter 9, Recipe 9.4 "Queueing and Retrying"
Section: The improved recipe
Book page: 198 -- original C# listing
Converted from C# to Python.
AddSingleton/AddHostedService become a FastAPI lifespan that starts the dispatcher
task; Results.Created becomes a 201 JSONResponse with a Location header.
"""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from email.message import EmailMessage
from typing import Any
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from p187_r9_1_register_and_send_statement import get_email_sender
from p196_r9_4_email_queue_retry_dispatcher import EmailDispatcher, EmailQueue
email_queue = EmailQueue()
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
dispatcher = EmailDispatcher(email_queue, get_email_sender())
dispatcher.start()
yield
await dispatcher.stop()
app = FastAPI(lifespan=lifespan)
# In the order endpoint, after the order is committed:
async def after_commit(order: Any, confirmation: EmailMessage) -> JSONResponse:
await email_queue.enqueue_async(confirmation)
return JSONResponse(status_code=201, content=order,
headers={"Location": f"/orders/{order['id']}"})
How it works
The bounded channel holds up to 1,000 messages. When it is full, EnqueueAsync waits instead of dropping mail or growing memory without limit; under normal load it completes immediately. SingleReader = true lets the channel use a faster implementation because only the dispatcher reads.
EmailDispatcher runs for the life of the application. ReadAllAsync waits without spinning when the queue is empty and ends cleanly when the host shuts down and cancels the token.
IsTransient is where the judgment lives. SMTP reply codes in the 400s mean "temporary, try again" (mailbox busy, greylisting, rate limit). Codes in the 500s mean "permanent" (no such user, message rejected), and retrying them only gets your server flagged. Network-level failures, a dropped connection and timeouts are treated as transient. Everything else goes to the final catch, which logs the failure with the message ID and recipients and moves on, so one bad message cannot block the queue.
Backoff doubles from 2 seconds to 16 seconds over five attempts, with up to a second of random jitter so that a burst of failures does not retry in lockstep. Chapter 5 shows the same policy with Polly if you already use it.
Variations and pitfalls
- In-memory means losable. If the process restarts, queued messages are gone. For mail that must not be lost, such as legal notices or password resets, write it to an outbox table in the same transaction as the business change and have the dispatcher poll the table. That is the transactional outbox pattern, and it is a small table:
CREATE TABLE dbo.EmailOutbox
(
EmailOutboxId BIGINT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_EmailOutbox PRIMARY KEY,
MessageMime VARBINARY(MAX) NOT NULL,
CreatedUtc DATETIME2(3) NOT NULL
CONSTRAINT DF_EmailOutbox_Created DEFAULT SYSUTCDATETIME(),
Attempts INT NOT NULL CONSTRAINT DF_EmailOutbox_Att DEFAULT 0,
NextAttemptUtc DATETIME2(3) NULL,
SentUtc DATETIME2(3) NULL,
LastError NVARCHAR(2000) NULL
);
- Serialize the whole MIME message.
message.WriteTo(stream)gives you the exact bytes to store inMessageMime, andMimeMessage.Load(stream)reads them back. Attachments and headers survive the round trip. - Batch sends. For a newsletter-sized batch, keep one MailKit client connected and send many messages through it. Reconnect every few hundred messages; many relays limit messages per session.
- Rate limits. Hosted mail services limit messages per second. Add a
Task.Delayor aSystem.Threading.RateLimitinglimiter in the dispatcher loop rather than finding out from 421 replies. - Graceful shutdown. Messages still in the channel at shutdown are lost unless you drain it. Chapter 14 shows how to give a hosted service time to finish.