IC Improve Code Recipes

Recipe 1.7 · Python

Async Data Access All the Way Down

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

Data access is I/O, and a thread that waits for SQL Server is a thread that cannot serve another request. Most enterprise code I have inherited ignores this: async/await appears in only about 0.3% of the hand-written C# files in my archive (1,265 files, 11 of 35 engagements). Async fixes that, but only when it is async from the controller to the reader. Half-async code, with .Result or .Wait() somewhere in the middle, deadlocks in classic ASP.NET and starves the thread pool in ASP.NET Core. Another common problem is loading an entire result set into a list just to write it to a file.

The way it's often written

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

Requirements: Python 3.12+. Install: pip install fastapi

Python Sync-over-async read and an in-memory CSV export (p035_r1_7_sync_over_async_export_before.py)
"""Sync-over-async read and an in-memory CSV export

Source: ImproveCode, Chapter 1, Recipe 1.7 "Async Data Access All the Way Down"
Section: The way it's often written
Book page: 35  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Task.Result -> asyncio.run_coroutine_threadsafe(...).result() on the running loop (blocks it, the
Python form of the deadlock); MVC File() -> FastAPI Response with the whole CSV in memory.
"""

import asyncio
from datetime import datetime
from typing import Any

from fastapi import Response


async def get_audit_async(from_: datetime) -> list[Any]:
    raise NotImplementedError


# Not to copy: sync over async, and everything in memory.
def get_audit(from_: datetime) -> list[Any]:
    loop = asyncio.get_event_loop()
    return asyncio.run_coroutine_threadsafe(
        get_audit_async(from_), loop).result()  # deadlock risk


def export(from_: datetime) -> Response:
    all_ = get_audit(from_)  # 2 million rows
    csv = "\n".join(a.to_csv() for a in all_)
    return Response(content=csv.encode("utf-8"), media_type="text/csv")

The improved recipe

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

Python Stream audit rows asynchronously and write them as CSV (p035_r1_7_stream_audit_rows_to_csv.py)
"""Stream audit rows asynchronously and write them as CSV

Source: ImproveCode, Chapter 1, Recipe 1.7 "Async Data Access All the Way Down"
Section: The improved recipe
Book page: 35-36  -- original C# listing
Converted from C# to Python.
IAsyncEnumerable -> async generator over an aioodbc cursor (fetchone per row, no buffering);
TextWriter -> an async write callable (e.g. a response stream); "O" format -> datetime.isoformat().
"""

import asyncio
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass
from datetime import datetime

from p020_r1_2_typed_sql_parameters_lookup import DbConnectionFactory, TypedParams


@dataclass(frozen=True)
class AuditEntry:
    audit_id: int
    changed_utc: datetime
    description: str


class AuditExport:
    SQL = """
        SELECT AuditId, ChangedUtc, Description
        FROM dbo.AuditLog
        WHERE ChangedUtc >= ?
        ORDER BY AuditId;
        """
    COMMAND_TIMEOUT = 120

    def __init__(self, db: DbConnectionFactory) -> None:
        self._db = db

    async def stream(self, from_utc: datetime) -> AsyncIterator[AuditEntry]:
        async with await self._db.open() as connection:
            async with connection.cursor() as command:
                p = TypedParams().add_datetime2("@FromUtc", from_utc)
                await p.apply(command)
                async with asyncio.timeout(self.COMMAND_TIMEOUT):
                    await command.execute(self.SQL, *p.values)

                while (row := await command.fetchone()) is not None:
                    yield AuditEntry(int(row[0]), row[1], str(row[2]))

    async def write_csv(self, from_utc: datetime,
                        output: Callable[[str], Awaitable[None]]) -> None:
        await output("AuditId,ChangedUtc,Description\n")
        async for e in self.stream(from_utc):
            description = '"' + e.description.replace('"', '""') + '"'
            await output(",".join((
                str(e.audit_id),
                e.changed_utc.isoformat(),
                description)) + "\n")

How it works

StreamAsync is an async iterator. It opens the connection, runs the query, and yields one AuditEntry per row as the reader advances. Only one row is in memory at a time. The connection stays open while the caller enumerates and closes when the await foreach loop finishes, breaks or throws, because the iterator's await using declarations run on disposal.

[EnumeratorCancellation] connects the token passed to StreamAsync with any token passed through WithCancellation, so a cancelled HTTP request stops the query. CommandBehavior.SequentialAccess tells the reader not to buffer the whole row, which matters for wide rows and large text columns; it requires that you read columns in order, as the mapping does.

WriteCsvAsync shows the consuming side. In ASP.NET Core you can pass a StreamWriter over Response.Body and the file streams to the browser as it is read from the database. Chapter 11 has a complete CSV writer; the quoting here is the minimum needed to be correct.

Variations and pitfalls

  • Never block on async. No .Result, .Wait() or .GetAwaiter().GetResult() in request code. If a synchronous caller cannot be changed, keep a synchronous method that calls the synchronous ADO.NET API rather than wrapping the async one.
  • Pass the token everywhere. Every OpenAsync, ExecuteReaderAsync and ReadAsync takes a CancellationToken. Cancellation sends an attention signal to SQL Server, which stops the query on the server, not just on the client.
  • ConfigureAwait(false). In ASP.NET Core and console apps there is no synchronization context, so it changes nothing. In a library that may be called from .NET Framework ASP.NET or WinForms, add .ConfigureAwait(false) to each await.
  • Large MAX columns. Reading big VARBINARY(MAX) or NVARCHAR(MAX) values with ReadAsync and GetString has historically been slow in SqlClient. Use SequentialAccess with GetStream or GetTextReader and copy the value in chunks.
  • Do not stream across a slow consumer for hours. The connection, and any shared locks under the default isolation level, stay open while the caller enumerates. For long exports, page through the data by key (Chapter 2) instead.