Skip to content

Python async generators: close before the pool

Carry ownership through an early return, nested wrapper and failure matrix, with a negative trace fixture.

Dopstack Engineering

· 8 min read

Original conceptual illustration: Descending nested arches for pool, stream and yield, with reverse-order exit arrows; forest green and cream.

Quick answer

Breaking out of `async for` does not give the consumer an explicit cleanup boundary for an async generator it leaves suspended. When the consumer owns that generator, wrap it in `contextlib.aclosing()` and leave the wrapper before closing resources the generator needs. This makes early-exit cleanup part of the surrounding coroutine's work rather than a later finalization event.

Breaking out of async for does not give the consumer an explicit cleanup boundary for an async generator it leaves suspended. When the consumer owns that generator, wrap it in contextlib.aclosing() and leave the wrapper before closing resources the generator needs. This makes early-exit cleanup part of the surrounding coroutine's work rather than a later finalization event. [1][2][3]

Why is the pool closing before the cursor?#

Scenario: a fictional Python service streams candidate documents from a database cursor. Its caller needs only the first acceptable document. The generator contains a finally block that closes the cursor, but the caller breaks early and then shuts down the connection pool. Later, cleanup attempts to use the closed pool. The finally block had the release code. The caller still needed to decide when that code must finish.

An async generator suspends at yield. Its local state can remain alive while the consumer examines the yielded value. If iteration ends normally, execution continues through the generator's remaining body. If the consumer leaves the loop early, the generator may remain suspended. Python's asynchronous cleanup machinery can finalize it later, but that timing is not the lexical scope the application intended. [2][6]

A short script can hide the ordering bug. asyncio.run() handles asynchronous-generator finalization during shutdown. A long-lived service needs the cursor released when the request finishes, not when the event loop eventually exits. A shutdown safety net cannot serve as the resource-lifetime contract for each request. [4]

The examples below use Python 3.10 or later because that is when standard-library aclosing was added. They use an in-memory stand-in for the cursor, so they do not depend on a particular database driver. Replace the stand-in only after confirming the driver's documented ownership and close behavior. [1]

Build a small trace that makes ownership visible#

Start with a generator that records when it opens, yields and finishes closing. Keeping an explicit reference to the generator avoids making the demonstration depend on reference-counting timing. A real cursor would acquire its connection where this example records open and release it where it records closed.

python
import asyncio
from contextlib import aclosing

async def candidates(events):
    events.append("open")
    try:
        for value in ("first", "second"):
            events.append("yield:" + value)
            yield value
    finally:
        events.append("closing")
        await asyncio.sleep(0)
        events.append("closed")

First inspect the unowned form. Keep stream alive, consume one value and break. Immediately after the loop, closed should not yet be in the event list. Explicitly close the generator afterward so the test itself does not leave an unfinished resource behind.

python
async def inspect_early_break():
    events = []
    stream = candidates(events)
    async for value in stream:
        assert value == "first"
        break
    assert "closed" not in events
    await stream.aclose()
    assert events[-2:] == ["closing", "closed"]
    return events

This is a deterministic ownership check, not a memory-leak benchmark. The explicit reference and immediate assertion show the gap between loop exit and generator closure. They do not predict when every Python implementation will collect an abandoned object. That uncertainty is exactly why collection should not define the release boundary.

Now wrap the same generator in aclosing. Its asynchronous exit awaits the generator's aclose() operation. The assertion after the wrapper can require cleanup to have finished, even though the loop stopped after the first value. [1]

python
async def choose_first():
    events = []
    async with aclosing(candidates(events)) as stream:
        async for value in stream:
            assert value == "first"
            break
    assert events == [
        "open", "yield:first", "closing", "closed"
    ]
    return events

asyncio.run(choose_first())

Notice where the assertion sits: after async with, not merely after async for. That is the boundary the caller can rely on. The loop's job is to obtain values; the wrapper's job is to finish a resource that this caller owns.

Which resource must close first?#

Bring the fictional pool back into the picture. The generator's cleanup needs a live connection, so the pool must outlive that cleanup. Put generator ownership inside pool ownership. The nesting expresses a dependency: close the stream, then close the pool.

python
async def find_document(pool_factory, stream_documents):
    async with pool_factory() as pool:
        async with aclosing(stream_documents(pool)) as documents:
            async for document in documents:
                if document["acceptable"]:
                    return document
    return None

This is an interface sketch. pool_factory must return an asynchronous context manager, and stream_documents must return an object with the aclose protocol expected by aclosing. Neither contract follows merely from using a variable named pool or documents. Read the actual driver's API before adapting it.

A return inside the inner scope still exits both context managers. The useful order is stream cleanup before pool cleanup. Verify it with an event log from a test double, then with the actual driver in a disposable integration test. If the pool's shutdown callback appears first, fix ownership nesting rather than suppressing the cursor's closing exception.

There is another valid design: let the caller acquire a cursor with the driver's context manager and pass that cursor to a generator that only transforms rows. Then the caller owns cursor closure directly, while the transforming generator owns no database resource. That can be easier to audit, especially when several transformations wrap the same source.

What happens through wrappers and helper generators?#

Suppose filtered_documents() creates an inner stream and yields only selected rows. Closing the outer generator does not create a universal rule that every object it once iterated is closed. Give each owned inner stream its own explicit scope. Ownership must remain visible at every wrapper that acquires a resource.

python
async def filtered_documents(source, predicate):
    async with aclosing(source()) as documents:
        async for document in documents:
            if predicate(document):
                yield document

Here source() creates a fresh stream owned by this wrapper. The outer consumer must still close filtered_documents() if it leaves early. The two scopes serve different owners: the outer scope finalizes the filtering generator, which then exits its inner scope and closes the source. Test the resulting close order rather than assuming that syntactic nesting makes every arbitrary iterator resource-aware.

Do not apply this pattern blindly to a borrowed stream. If another component intends to continue consuming it, closing it in a helper can break that component. Define whether the helper takes ownership, borrows for one operation, or returns ownership to the caller. In public APIs, make the distinction visible through context-manager usage and documentation.

Also distinguish asynchronous iterators from asynchronous generators. An object can support async for without exposing aclose. aclosing is not a general adapter that invents a shutdown protocol. If a client library documents close, disconnect or an enclosing context manager instead, use that documented interface. [1][2]

How should exceptions and cancellation behave?#

Test a consumer exception as well as break. Raise a sentinel error after the first yielded value, catch it outside the aclosing scope and assert that the close event was recorded. This proves cleanup occurs while unwinding the consumer's scope, without turning a processing error into a successful result.

Cancellation deserves a separate test because cleanup itself can await. Python recommends try/finally for coroutine cleanup and generally re-raising CancelledError after cleanup when it is caught. It derives directly from BaseException. Do not add a broad handler that records cancellation and continues processing the next document as though the request were still active. [5]

A closing scope is not a guarantee against process termination, a second cancellation arriving during cleanup, or a driver that never finishes closing. If your service requires a cleanup deadline, choose what happens when that deadline expires. Record the remaining resource and rely on a documented connection-abort or pool-recovery mechanism where available. Avoid promising that an arbitrary timeout can safely finish an unknown driver's transaction.

Do not casually launch aclose() as an untracked background task. That recreates the lifetime gap: the caller can close the pool while the new task is still using it. If cleanup must run in a separate task under a framework's rules, retain and await that task before dependent resources leave scope, and test the framework's cancellation behavior.

Generator cleanup may fail. A driver can raise while releasing a cursor, or application code in finally can contain its own bug. Preserve both the processing context and closing failure in diagnostics. Silencing all closing errors makes the happy path look clean while hiding an exhausted pool or incomplete rollback.

What does a useful test matrix look like?#

Use a trace with stable event names rather than elapsed-time assertions. Require stream_closed before pool_closed; require it once for normal exhaustion, early break, return and a consumer exception. Add cancellation delivered while the consumer is waiting, and a closing routine that deliberately raises.

PathRequired observationFailure interpretation
ExhaustionGenerator reaches its finalizerBasic cleanup body is reachable
Early break or returnClose completes before dependent context exitsConsumer owns an explicit close scope
Consumer errorCleanup occurs and the error still propagatesException handling preserves failure
Nested wrapperInner resource closes before outer dependenciesOwnership was carried through wrappers
CancellationCleanup follows the chosen policy; cancellation remains visibleFramework and driver behavior need separate verification
Proposed resource-order tests. These are acceptance criteria for your implementation, not measured guarantees about every database driver.

Keep one negative fixture without aclosing and retain its generator reference. It should fail the immediate-close assertion. A test suite that only exercises the repaired form can miss a later refactor that moves the assertion beyond event-loop shutdown and accidentally lets deferred finalization pass.

Keep the test double focused on event order. An integration test then checks the real cursor, connection and pool counters. Record the exact Python and driver versions and the cancellation conditions actually exercised. Passing an in-memory trace does not prove that an HTTP disconnect or database timeout follows the same path.

When is a context manager a clearer API?#

If the stream's main purpose is to hold an expensive resource across consumption, consider exposing an asynchronous context manager that yields the stream. The call site then has an obvious acquire-use-release structure. Users do not need to infer that early iteration creates a second obligation.

This choice costs a little ceremony. It also limits convenient expressions such as an unscoped async for over a function call. For a pure transformation with no owned resource, that ceremony may add little value. For a cursor, subscription or streamed response, explicit ownership usually repays the extra indentation during error handling and shutdown review.

Example verification: the article functions ran on Python 3.12.14. Eight event-order cases covered the retained-reference negative fixture, early break, exhaustion, consumer error, return before pool closure, nested wrappers, a single cancellation while the consumer waited, and a closing error. No real database driver, disconnect handler, repeated cancellation or process kill was tested.

Frequently asked questions#

Does finally run when an async generator is closed?
Explicit aclose injects GeneratorExit at the suspended yield point so cleanup can execute. The call returns an awaitable that must be awaited. A finally block by itself does not define when the consumer will close a suspended generator. [2][6]
Is standard-library aclosing available in Python 3.9?
No. It was added in Python 3.10. On an older supported codebase, use a documented compatibility implementation or explicit try/finally with await stream.aclose(), and test the same ownership behavior. [1]
Does asyncio.run already clean up async generators?
It includes asynchronous-generator finalization in its runner lifecycle. That is useful at shutdown, but it does not provide a per-request resource boundary inside a running service. [4]
Should every async iterator be wrapped in aclosing?
Only if it exposes the expected aclose protocol and this scope owns its closure. Some iterators are borrowed, and some libraries require a different documented context manager. State the ownership contract before adding automatic closure. [1][2]

Technologies

  • Python

Sources

  1. [1]
    contextlib, Python

    Read 2026-11-06T08:03:32.039589+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: aclosing provides deterministic cleanup on early exit.

  2. [2]
    Expressions: async generators, Python

    Read 2026-11-06T08:03:32.235218+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: aclose injects GeneratorExit.

  3. [3]
    Developing with asyncio, Python

    Read 2026-11-06T08:03:32.274704+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: Python recommends explicit generator closure.

  4. [4]
    Runners, Python

    Read 2026-11-06T08:03:32.286003+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: Runner lifecycle includes generator finalization.

  5. [5]
    Coroutines and Tasks, Python

    Read 2026-11-06T08:03:32.342179+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: Cancellation is a BaseException subclass.

  6. [6]
    PEP 525, Python

    Read 2026-11-06T08:03:32.371470+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: The async generator protocol includes aclose.

Written by

Dopstack Engineering

Engineering team

The engineering team at Dopstack. Illustrative scenarios are composites written to explain a pattern, not accounts of client work.

All articles Website

Get new articles by email

Engineering notes on AI, cloud and SaaS. Occasional, never sold or shared.

Send me new Dopstack Insights articles by email. I can unsubscribe at any time. We’ll email you once to confirm. Privacy

Continue reading