This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-async-generator-dependency-teardown-invariant

FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail

Enforces deterministic resource deallocation and transaction termination in FastAPI async generator dependencies during unexpected client disconnects and ASGI task cancellations. Mandates comprehensive try-finally blocks or asynchronous context managers around all yield statements to eliminate connection pool starvation and orphaned transactions.

Prohibited Anti-Pattern: Naked Dependency Yields Inducing Connection Pool Exhaustion on Abrupt Client Disconnection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail - Enforces deterministic resource deallocation and transaction termination in FastAPI async generator dependencies during unexpected client disconnects and ASGI task cancellations. Mandates comprehensive try-finally blocks or asynchronous context managers around all yield statements to eliminate connection pool starvation and orphaned transactions.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-async-generator-dependency-teardown-invariant"
---

# FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Naked Dependency Yields Inducing Connection Pool Exhaustion on Abrupt Client Disconnection

## System Constraints
You are a Principal Backend Architect enforcing deterministic resource deallocation invariants in FastAPI applications. You must ensure that all ASGI dependencies utilizing generators wrap yields in defensive try-finally constructs or asynchronous context managers. Because client disconnects raise asyncio.CancelledError (which inherits from BaseException), post-yield code without explicit finally guards will never execute, leaking database connections, Redis handles, and file descriptors into process pools.

## Strict Guidelines
- Engineers MUST ALWAYS wrap the `yield` statement of an async generator dependency in an explicit `try...finally` block or an `async with` context manager.
- Engineers MUST NOT place critical finalizers, pool releases, or cleanup logic directly below a naked `yield` statement without a guaranteed `finally` execution path.
- Code SHOULD catch `BaseException` rather than `Exception` when rollback handling must execute before re-raising upon `asyncio.CancelledError`.
- Services MUST ensure that all transactional handles explicitly execute rollback or cleanup when a request is cancelled prematurely by an ASGI client disconnect.
- Components NEVER assume route execution completed successfully if post-yield execution resumes; commit operations MUST be bounded within the try block preceding yield completion or within route handlers.

## Bad vs Good Implementations
### Async Generator Dependency with Client Disconnect Resource Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts the connection mid-flight, Starlette/FastAPI propagates an asyncio.CancelledError into the dependency generator. Naked post-yield statements are skipped, preventing session closure and starving the database connection pool under sustained load.
```python
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import async_session_factory

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    session: AsyncSession = async_session_factory()
    # DEFECT: If client disconnects or ASGI cancels the task during request execution,
    # code resumes or terminates via asyncio.CancelledError.
    # The following post-yield statements never execute, leaking the connection back to the pool.
    yield session
    await session.commit()
    await session.close()
```

#### Production Standard (Correct)
> **Standard**: Wrapping the yield within an async context manager and guarding with a try...except BaseException...finally block ensures that session rollback and connection deallocation are strictly deterministic, regardless of unexpected ASGI client terminations.
```python
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import async_session_factory

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_factory() as session:
        try:
            yield session
            await session.commit()
        except BaseException:
            # BaseException catches asyncio.CancelledError on client disconnect
            await session.rollback()
            raise
        finally:
            # async with context manager guarantees close() execution
            # even when CancelledError or unhandled exceptions occur
            await session.close()
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail

FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic resource deallocation and transaction termination in FastAPI async generator dependencies during unexpected client disconnects and ASGI task cancellations. Mandates comprehensive try-finally blocks or asynchronous context managers around all yield statements to eliminate connection pool starvation and orphaned transactions. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Naked Dependency Yields Inducing Connection Pool Exhaustion on Abrupt Client Disconnection Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftNaked Dependency Yields Inducing Connection Pool Exhaustion on Abrupt Client DisconnectionCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS wrap the `yield` statement of an async generator dependency in an explicit `try...finally` block or an `async with` context manager.

Engineers MUST ALWAYS wrap the `yield` statement of an async generator dependency in an explicit `try...finally` block or an `async with` context manager.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT place critical finalizers, pool releases, or cleanup logic directly below a naked `yield` statement without a guaranteed `finally` execution path.

Engineers MUST NOT place critical finalizers, pool releases, or cleanup logic directly below a naked `yield` statement without a guaranteed `finally` execution path.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD catch `BaseException` rather than `Exception` when rollback handling must execute before re-raising upon `asyncio.CancelledError`.

Code SHOULD catch `BaseException` rather than `Exception` when rollback handling must execute before re-raising upon `asyncio.CancelledError`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that all transactional handles explicitly execute rollback or cleanup when a request is cancelled prematurely by an ASGI client disconnect.

Services MUST ensure that all transactional handles explicitly execute rollback or cleanup when a request is cancelled prematurely by an ASGI client disconnect.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER assume route execution completed successfully if post-yield execution resumes

Components NEVER assume route execution completed successfully if post-yield execution resumes; commit operations MUST be bounded within the try block preceding yield completion or within route handlers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is FastAPI Async Generator Dependency Deterministic Teardown and Connection Release Guardrail critical for AI coding assistants?

Enforces deterministic resource deallocation and transaction termination in FastAPI async generator dependencies during unexpected client disconnects and ASGI task cancellations. Mandates comprehensive try-finally blocks or asynchronous context managers around all yield statements to eliminate connection pool starvation and orphaned transactions. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Naked Dependency Yields Inducing Connection Pool Exhaustion on Abrupt Client Disconnection) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

FastAPI