This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-anyio4-taskgroup-cancellation-propagation-standard

FastAPI AnyIO 4 TaskGroup Cancellation Propagation Standard

Enforces fail-safe structured concurrency under AnyIO 4 and ASGI servers by guaranteeing client disconnect signals cascade immediately into database execution boundaries. Prevents silent cancellation absorption and unmanaged asyncio task detachment that lead to orphan query thread starvation, connection pool exhaustion, and zombie writes.

Prohibited Anti-Pattern: Swallowing CancelledError in Generic Exception Handlers and Spawning Detached Background Tasks Across DB Transactions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO 4 TaskGroup Cancellation Propagation Standard - Enforces fail-safe structured concurrency under AnyIO 4 and ASGI servers by guaranteeing client disconnect signals cascade immediately into database execution boundaries. Prevents silent cancellation absorption and unmanaged asyncio task detachment that lead to orphan query thread starvation, connection pool exhaustion, and zombie writes.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio4-taskgroup-cancellation-propagation-standard"
---

# FastAPI AnyIO 4 TaskGroup Cancellation Propagation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Swallowing CancelledError in Generic Exception Handlers and Spawning Detached Background Tasks Across DB Transactions

## System Constraints
You are a Principal Backend Architect enforcing AnyIO 4 structured concurrency standards in FastAPI applications. You must mandate that client disconnects, task cancellations, and ASGI lifecycle aborts immediately cascade into asynchronous database transactions and long-running sub-tasks. Reject any usage of raw `asyncio.create_task` within request lifecycles, reject catching `BaseException` or `Exception` without re-raising cancellation exceptions, and enforce shielded rollback blocks during unwinding.

## Strict Guidelines
- Engineers MUST ALWAYS re-raise `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) when intercepting exceptions in database transaction blocks.
- Engineers MUST NOT spawn unbounded concurrent tasks with raw `asyncio.create_task` inside route handlers; all concurrency MUST be managed via `anyio.create_task_group()` tied to the request lifecycle.
- Engineers MUST wrap asynchronous transaction rollbacks and connection release routines inside `anyio.CancelScope(shield=True)` to prevent aborted rollback coroutines from leaking open pool slots during cancellation cascades.
- Services MUST monitor client disconnect events or let AnyIO task cancellation propagate upward natively instead of masking network aborts behind fallback HTTP responses.
- Database query boundaries MUST use drivers with native cancellation hooks (e.g., `asyncpg`) to ensure socket abort frames terminate the remote backend query execution immediately upon task group cancellation.

## Bad vs Good Implementations
### Database Transaction Handling Under Client Disconnect Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning detached tasks with `asyncio.create_task` disconnects execution from FastAPI's ASGI lifecycle. If the client disconnects, the query continues running on the PostgreSQL engine, starving the connection pool. Additionally, blanket exception trapping without re-raising cancellation interrupts the cancellation propagation chain.
```python
import asyncio
from fastapi import FastAPI, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_session

app = FastAPI()

@app.post("/process-batch")
async def process_batch(request: Request, session: AsyncSession = Depends(get_session)):
    # ANTI-PATTERN: Detached task ignores request cancellation and generic catch swallows CancelledError
    async def worker():
        try:
            await session.execute("SELECT pg_sleep(30);")
            await session.commit()
        except Exception as exc:
            # Catches CancelledError in Python <=3.7 or prevents propagation if BaseException is caught
            await session.rollback()
            return {"status": "error", "detail": str(exc)}

    asyncio.create_task(worker())  # Leaks task, runs as orphan if client disconnects
    return {"status": "accepted"}
```

#### Production Standard (Correct)
> **Standard**: Using `anyio.create_task_group()` ties child execution directly to the request cancellation scope. When the client disconnects, AnyIO signals `cancelled_exc`, which immediately cancels the pending DB statement socket. The rollback logic is isolated in a `CancelScope(shield=True)` to guarantee the transaction cleans up without itself being aborted.
```python
import anyio
from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_session

app = FastAPI()

@app.post("/process-batch")
async def process_batch(session: AsyncSession = Depends(get_session)):
    # PRODUCTION FIX: AnyIO 4 TaskGroup propagates cancellation instantly;
    # Rollback is strictly shielded to guarantee clean connection state unwinding.
    cancelled_exc = anyio.get_cancelled_exc_class()
    try:
        async with anyio.create_task_group() as tg:
            tg.start_soon(session.execute, "SELECT pg_sleep(30);")
        await session.commit()
        return {"status": "completed"}
    except cancelled_exc:
        with anyio.CancelScope(shield=True):
            await session.rollback()
        raise
    except Exception:
        with anyio.CancelScope(shield=True):
            await session.rollback()
        raise
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI AnyIO 4 TaskGroup Cancellation Propagation Standard

FastAPI AnyIO 4 TaskGroup Cancellation Propagation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces fail-safe structured concurrency under AnyIO 4 and ASGI servers by guaranteeing client disconnect signals cascade immediately into database execution boundaries. Prevents silent cancellation absorption and unmanaged asyncio task detachment that lead to orphan query thread starvation, connection pool exhaustion, and zombie writes. 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: Swallowing CancelledError in Generic Exception Handlers and Spawning Detached Background Tasks Across DB Transactions 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 DriftSwallowing CancelledError in Generic Exception Handlers and Spawning Detached Background Tasks Across DB TransactionsCritical
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 re-raise `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) when intercepting exceptions in database transaction blocks.

Engineers MUST ALWAYS re-raise `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) when intercepting exceptions in database transaction blocks.

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 spawn unbounded concurrent tasks with raw `asyncio.create_task` inside route handlers

Engineers MUST NOT spawn unbounded concurrent tasks with raw `asyncio.create_task` inside route handlers; all concurrency MUST be managed via `anyio.create_task_group()` tied to the request lifecycle.

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 wrap asynchronous transaction rollbacks and connection release routines inside `anyio.CancelScope(shield=True)` to prevent aborted rollback coroutines from leaking open pool slots during cancellation cascades.

Engineers MUST wrap asynchronous transaction rollbacks and connection release routines inside `anyio.CancelScope(shield=True)` to prevent aborted rollback coroutines from leaking open pool slots during cancellation cascades.

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 monitor client disconnect events or let AnyIO task cancellation propagate upward natively instead of masking network aborts behind fallback HTTP responses.

Services MUST monitor client disconnect events or let AnyIO task cancellation propagate upward natively instead of masking network aborts behind fallback HTTP responses.

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

Database query boundaries MUST use drivers with native cancellation hooks (e.g., `asyncpg`) to ensure socket abort frames terminate the remote backend query execution immediately upon task group cancellation.

Database query boundaries MUST use drivers with native cancellation hooks (e.g., `asyncpg`) to ensure socket abort frames terminate the remote backend query execution immediately upon task group cancellation.

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 AnyIO 4 TaskGroup Cancellation Propagation Standard critical for AI coding assistants?

Enforces fail-safe structured concurrency under AnyIO 4 and ASGI servers by guaranteeing client disconnect signals cascade immediately into database execution boundaries. Prevents silent cancellation absorption and unmanaged asyncio task detachment that lead to orphan query thread starvation, connection pool exhaustion, and zombie writes. 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 (Swallowing CancelledError in Generic Exception Handlers and Spawning Detached Background Tasks Across DB Transactions) 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