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-guardrail

FastAPI Async Generator Dependency Teardown & Resource Leak Guardrail

Mandates strict try...finally boundaries and exception-safe teardown protocols across all FastAPI yield-based dependency injection providers. Prevents persistent database pool starvation and orphaned transactions caused by abrupt client disconnects, task cancellations, and unhandled downstream exceptions.

Prohibited Anti-Pattern: Naive sequential execution around yield statements in async dependencies leaving pooled database connections orphaned upon client drop or mid-stream task cancellation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Async Generator Dependency Teardown & Resource Leak Guardrail - Mandates strict try...finally boundaries and exception-safe teardown protocols across all FastAPI yield-based dependency injection providers. Prevents persistent database pool starvation and orphaned transactions caused by abrupt client disconnects, task cancellations, and unhandled downstream exceptions.
globs: app/api/dependencies/**/*.py, app/dependencies/**/*.py, app/db/session.py, src/**/dependencies.py, src/**/db.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-async-generator-dependency-teardown-guardrail"
---

# FastAPI Async Generator Dependency Teardown & Resource Leak Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Naive sequential execution around yield statements in async dependencies leaving pooled database connections orphaned upon client drop or mid-stream task cancellation.

## System Constraints
You are a Principal Backend Architect enforcing rock-solid lifecycle hygiene for FastAPI dependency injection and async resource allocators. FastAPI runs generator teardown code after response delivery or upon exception processing, but unhandled task cancellations (such as client disconnections raising asyncio.CancelledError) bypass naive post-yield logic if not wrapped in explicit try...finally blocks. You must mandate bulletproof transaction rollbacks and connection releases to eliminate connection pool exhaustion in high-concurrency microservices.

## Strict Guidelines
- Engineers MUST ALWAYS wrap the `yield` expression of any FastAPI dependency in an explicit `try ... finally` block to guarantee cleanup execution under all termination scenarios.
- Engineers MUST explicitly catch `BaseException` (or both `Exception` and `asyncio.CancelledError`) prior to `finally` to trigger an immediate `await session.rollback()` before re-raising.
- Engineers MUST NOT execute business logic, writes, or post-yield operations outside of the protected `try` block, as post-yield code without a `finally` block is bypassed when an exception or cancellation occurs.
- Code SHOULD leverage native async context managers (`async with session_maker() as session:`) whenever underlying drivers support guaranteed asynchronous exit handlers.
- Services MUST configure aggressive pool pre-pinging (`pool_pre_ping=True`) and finite recycle limits (`pool_recycle`) on database engines to complement teardown guardrails against zombie connections.

## Bad vs Good Implementations
### Async Session Generator Teardown Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an unhandled exception or abrupt ASGI disconnect occurs during request processing, FastAPI terminates the generator without resuming post-yield statements if they are not enclosed in a try...finally block. This leaks database pool slots, causing pool exhaustion under production load.
```python
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import async_session_factory

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    # ANTI-PATTERN: If client disconnects or an error is raised during the endpoint execution,
    # execution never reaches session.commit() or session.close(). The connection
    # remains checked out of the pool indefinitely in an IDLE IN TRANSACTION state.
    session = async_session_factory()
    yield session
    await session.commit()
    await session.close()
```

#### Production Standard (Correct)
> **Standard**: Enclosing the yield inside try...finally ensures `session.close()` executes unconditionally during generator finalization. Trapping `BaseException` ensures that `asyncio.CancelledError` triggers a clean rollback before re-raising, keeping the connection pool pristine.
```python
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import async_session_factory

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    # PRODUCTION FIX: Explicit try-except-finally guarantees session rollback
    # and resource checkout closure even when tasks are cancelled via disconnect.
    session: AsyncSession = async_session_factory()
    try:
        yield session
        await session.commit()
    except BaseException:
        await session.rollback()
        raise
    finally:
        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 Teardown & Resource Leak Guardrail

FastAPI Async Generator Dependency Teardown & Resource Leak Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates strict try...finally boundaries and exception-safe teardown protocols across all FastAPI yield-based dependency injection providers. Prevents persistent database pool starvation and orphaned transactions caused by abrupt client disconnects, task cancellations, and unhandled downstream exceptions. 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: Naive sequential execution around yield statements in async dependencies leaving pooled database connections orphaned upon client drop or mid-stream task cancellation. 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 DriftNaive sequential execution around yield statements in async dependencies leaving pooled database connections orphaned upon client drop or mid-stream task cancellation.Critical
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` expression of any FastAPI dependency in an explicit `try ... finally` block to guarantee cleanup execution under all termination scenarios.

Engineers MUST ALWAYS wrap the `yield` expression of any FastAPI dependency in an explicit `try ... finally` block to guarantee cleanup execution under all termination scenarios.

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 explicitly catch `BaseException` (or both `Exception` and `asyncio.CancelledError`) prior to `finally` to trigger an immediate `await session.rollback()` before re-raising.

Engineers MUST explicitly catch `BaseException` (or both `Exception` and `asyncio.CancelledError`) prior to `finally` to trigger an immediate `await session.rollback()` before re-raising.

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

Engineers MUST NOT execute business logic, writes, or post-yield operations outside of the protected `try` block, as post-yield code without a `finally` block is bypassed when an exception or cancellation occurs.

Engineers MUST NOT execute business logic, writes, or post-yield operations outside of the protected `try` block, as post-yield code without a `finally` block is bypassed when an exception or cancellation occurs.

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

Code SHOULD leverage native async context managers (`async with session_maker() as session

Code SHOULD leverage native async context managers (`async with session_maker() as session:`) whenever underlying drivers support guaranteed asynchronous exit 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.
5

Services MUST configure aggressive pool pre-pinging (`pool_pre_ping=True`) and finite recycle limits (`pool_recycle`) on database engines to complement teardown guardrails against zombie connections.

Services MUST configure aggressive pool pre-pinging (`pool_pre_ping=True`) and finite recycle limits (`pool_recycle`) on database engines to complement teardown guardrails against zombie connections.

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 Teardown & Resource Leak Guardrail critical for AI coding assistants?

Mandates strict try...finally boundaries and exception-safe teardown protocols across all FastAPI yield-based dependency injection providers. Prevents persistent database pool starvation and orphaned transactions caused by abrupt client disconnects, task cancellations, and unhandled downstream exceptions. 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 (Naive sequential execution around yield statements in async dependencies leaving pooled database connections orphaned upon client drop or mid-stream task cancellation.) 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