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

Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints

Enforces deterministic release of sockets, transactions, and telemetry spans yielded by FastAPI async generator dependencies during client disconnects or ASGI stream cancellations. Because Starlette StreamingResponse teardowns occur outside the immediate task context upon asyncio.CancelledError, generator dependencies must guarantee idempotency and shield finalization blocks from premature task death.

Prohibited Anti-Pattern: Resource Leakage via Abrupt ASGI Cancellation in Dependency-Injected Streaming Generators

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints - Enforces deterministic release of sockets, transactions, and telemetry spans yielded by FastAPI async generator dependencies during client disconnects or ASGI stream cancellations. Because Starlette StreamingResponse teardowns occur outside the immediate task context upon asyncio.CancelledError, generator dependencies must guarantee idempotency and shield finalization blocks from premature task death.
globs: **/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-async-generator-stream-teardown-guardrail"
---

# Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Resource Leakage via Abrupt ASGI Cancellation in Dependency-Injected Streaming Generators

## System Constraints
You are a Principal Software Architect enforcing reliable teardown semantics across FastAPI streaming architectures. In Starlette and FastAPI, yielding dependencies execute post-yield cleanup inside a finally block after the response is sent. When a client disconnects during a StreamingResponse, an asyncio.CancelledError propagates through the generator runner, which can prematurely abort naive teardown blocks or cause unhandled exceptions that leave database connections checked out, socket file descriptors dangling, and distributed traces unclosed. You must mandate bulletproof, non-cancellable resource cleanups using asyncio.shield and defensive context management.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate yield statements inside try...finally blocks within async generator dependencies.
- Engineers MUST NOT allow asyncio.CancelledError or BaseException to bypass connection pool release or telemetry context closure.
- Code SHOULD wrap critical cleanup routines (e.g., connection.close(), span.end(), session.rollback()) in asyncio.shield() or ensure synchronous teardown runs without interruption if an async cancel occurs.
- Services MUST explicitly handle client disconnection signals within StreamingResponse iterators by catching asyncio.CancelledError and breaking cleanly.
- Components NEVER assume post-yield code executes in an uncancelled task state when serving long-lived SSE or WebSocket streams.

## Bad vs Good Implementations
### Async Generator Dependency Cleanup Under Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If a client disconnects mid-stream, asyncio.CancelledError is injected into the running task. The finally block is entered, but any subsequent await within the cleanup (such as session.rollback()) is immediately aborted by the pending cancellation token, stranding connection locks in the pool.
```python
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
import asyncio

app = FastAPI()

async def get_db_session():
    session = await pool.acquire()
    try:
        yield session
    finally:
        # Fails silently or gets aborted midway if client disconnects abruptly
        # while the generator is paused at yield during stream consumption
        await session.rollback()
        await pool.release(session)

@app.get("/events")
async def stream_events(db=Depends(get_db_session)):
    async def event_generator():
        while True:
            data = await db.fetch_next_event()
            yield f"data: {data}\n\n"
            await asyncio.sleep(1)
    return StreamingResponse(event_generator(), media_type="text/event-stream")
```

#### Production Standard (Correct)
> **Standard**: The cleanup logic is encapsulated inside an inner coroutine and executed under asyncio.shield(), ensuring that the ASGI task cancellation signal cannot truncate the release of connection pool resources.
```python
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import logging

logger = logging.getLogger(__name__)
app = FastAPI()

async def get_db_session():
    session = await pool.acquire()
    try:
        yield session
    finally:
        # Ensure teardown executes deterministically without being interrupted by CancelledError
        async def _safe_cleanup():
            try:
                await session.rollback()
            except Exception:
                logger.exception("Error rolling back session during stream teardown")
            finally:
                await pool.release(session)
        
        # Shield cleanup execution from ASGI task cancellation context
        await asyncio.shield(_safe_cleanup())

@app.get("/events")
async def stream_events(db=Depends(get_db_session)):
    async def event_generator():
        try:
            while True:
                data = await db.fetch_next_event()
                yield f"data: {data}\n\n"
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            logger.info("Client disconnected from event stream; propagating cancellation cleanly.")
            raise
    return StreamingResponse(event_generator(), media_type="text/event-stream")
```

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: Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints

Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic release of sockets, transactions, and telemetry spans yielded by FastAPI async generator dependencies during client disconnects or ASGI stream cancellations. Because Starlette StreamingResponse teardowns occur outside the immediate task context upon asyncio.CancelledError, generator dependencies must guarantee idempotency and shield finalization blocks from premature task death. 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: Resource Leakage via Abrupt ASGI Cancellation in Dependency-Injected Streaming Generators 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 DriftResource Leakage via Abrupt ASGI Cancellation in Dependency-Injected Streaming GeneratorsCritical
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 encapsulate yield statements inside try...finally blocks within async generator dependencies.

Engineers MUST ALWAYS encapsulate yield statements inside try...finally blocks within async generator dependencies.

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 allow asyncio.CancelledError or BaseException to bypass connection pool release or telemetry context closure.

Engineers MUST NOT allow asyncio.CancelledError or BaseException to bypass connection pool release or telemetry context closure.

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 wrap critical cleanup routines (e.g., connection.close(), span.end(), session.rollback()) in asyncio.shield() or ensure synchronous teardown runs without interruption if an async cancel occurs.

Code SHOULD wrap critical cleanup routines (e.g., connection.close(), span.end(), session.rollback()) in asyncio.shield() or ensure synchronous teardown runs without interruption if an async cancel 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

Services MUST explicitly handle client disconnection signals within StreamingResponse iterators by catching asyncio.CancelledError and breaking cleanly.

Services MUST explicitly handle client disconnection signals within StreamingResponse iterators by catching asyncio.CancelledError and breaking cleanly.

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 post-yield code executes in an uncancelled task state when serving long-lived SSE or WebSocket streams.

Components NEVER assume post-yield code executes in an uncancelled task state when serving long-lived SSE or WebSocket streams.

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 Deterministic Teardown for Dependency-Injected Async Generators in Streaming Endpoints critical for AI coding assistants?

Enforces deterministic release of sockets, transactions, and telemetry spans yielded by FastAPI async generator dependencies during client disconnects or ASGI stream cancellations. Because Starlette StreamingResponse teardowns occur outside the immediate task context upon asyncio.CancelledError, generator dependencies must guarantee idempotency and shield finalization blocks from premature task death. 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 (Resource Leakage via Abrupt ASGI Cancellation in Dependency-Injected Streaming Generators) 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

Deterministic