This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-anyio-structured-taskgroup-guardrail

FastAPI AnyIO Structured Concurrency and TaskGroup Socket Lifecycle Invariants

Enforces strict structured concurrency in FastAPI background workers and parallel request handlers via AnyIO TaskGroups. Prevents silent fire-and-forget sub-task orphaning, enforces deterministic cancellation cascades, and guarantees active HTTP/2 and database connection sockets are gracefully terminated when exceptions occur in concurrent branches.

Prohibited Anti-Pattern: Orphaning concurrent coroutines via unshielded fire-and-forget asyncio.create_task and unhandled ExceptionGroup socket leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Structured Concurrency and TaskGroup Socket Lifecycle Invariants - Enforces strict structured concurrency in FastAPI background workers and parallel request handlers via AnyIO TaskGroups. Prevents silent fire-and-forget sub-task orphaning, enforces deterministic cancellation cascades, and guarantees active HTTP/2 and database connection sockets are gracefully terminated when exceptions occur in concurrent branches.
globs: app/**/*.py, src/**/*.py, services/**/*.py, workers/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-structured-taskgroup-guardrail"
---

# FastAPI AnyIO Structured Concurrency and TaskGroup Socket Lifecycle Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaning concurrent coroutines via unshielded fire-and-forget asyncio.create_task and unhandled ExceptionGroup socket leaks

## System Constraints
You are a Principal Backend Architect enforcing structured concurrency invariants in FastAPI applications using AnyIO. You must eliminate all unmanaged asyncio.create_task patterns, ensure deterministic cancellation tree propagation, and guarantee that socket resources (HTTP/2 sessions, streaming clients, database handles) do not leak when concurrent subtasks fail.

## Strict Guidelines
- Engineers MUST ALWAYS use 'anyio.create_task_group()' context managers rather than raw 'asyncio.create_task()' or 'asyncio.gather()' when fanning out background coroutines.
- Engineers MUST NOT spawn detached fire-and-forget tasks inside FastAPI route handlers or dependency lifecycles without bound TaskGroup boundaries or supervised worker queues.
- Services MUST catch 'ExceptionGroup' (or BaseExceptionGroup in Python 3.11+) or use 'anyio.from_thread' bridges to prevent unhandled partial failures from hanging sibling coroutines.
- Components NEVER hold open persistent HTTP/2 connection pools across cancellation scopes without wrapping acquisition and cleanup inside deterministic 'try ... finally' blocks.
- Code SHOULD explicitly utilize 'anyio.move_on_after()' or 'anyio.fail_after()' timeout scopes to bound asynchronous fan-outs instead of unbounded async loops.
- Engineers MUST use 'anyio.CancelScope(shield=True)' strictly for non-deferrable cleanup tasks within 'finally' blocks to prevent cancellation aborts during socket teardown.

## Bad vs Good Implementations
### Unstructured Task Spawning vs AnyIO Structured TaskGroup with Resource Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using asyncio.create_task and asyncio.gather without structured concurrency causes orphaned tasks if one branch fails. The httpx.AsyncClient HTTP/2 socket remains unclosed, leaking file descriptors and pool connections under high load.
```python
import asyncio
import httpx
from fastapi import APIRouter, HTTPException

router = APIRouter()

async def fetch_upstream(client: httpx.AsyncClient, url: str) -> dict:
    resp = await client.get(url)
    resp.raise_for_status()
    return resp.json()

@router.post("/aggregate")
async def aggregate_metrics():
    # ANTI-PATTERN: Raw asyncio.gather and unshielded client
    # If url_b fails, url_a task continues running detached;
    # HTTP/2 client socket leaks or hangs when aborted prematurely.
    client = httpx.AsyncClient(http2=True)
    task1 = asyncio.create_task(fetch_upstream(client, "https://service-a.internal/data"))
    task2 = asyncio.create_task(fetch_upstream(client, "https://service-b.internal/faulty"))
    
    try:
        results = await asyncio.gather(task1, task2)
        return {"data": results}
    except Exception as exc:
        # Orphaned tasks keep running in the background; client is never closed
        raise HTTPException(status_code=502, detail=str(exc))
```

#### Production Standard (Correct)
> **Standard**: The AnyIO TaskGroup guarantees structured concurrency: if one subtask raises an HTTPError, the entire task group cancels remaining siblings cleanly. Wrapping inside httpx.AsyncClient's context manager ensures HTTP/2 sockets are gracefully closed upon exit.
```python
import anyio
import httpx
from fastapi import APIRouter, HTTPException

router = APIRouter()

async def fetch_upstream(client: httpx.AsyncClient, url: str, collector: list[dict]) -> None:
    resp = await client.get(url)
    resp.raise_for_status()
    collector.append(resp.json())

@router.post("/aggregate")
async def aggregate_metrics():
    results: list[dict] = []
    try:
        # DETERMINISTIC LIFECYCLE: Enforce client lifecycle and structured task group
        async with httpx.AsyncClient(http2=True, timeout=5.0) as client:
            async with anyio.create_task_group() as tg:
                tg.start_soon(fetch_upstream, client, "https://service-a.internal/data", results)
                tg.start_soon(fetch_upstream, client, "https://service-b.internal/faulty", results)
    except* httpx.HTTPError as eg:
        # ExceptionGroup unpacking (Python 3.11+) ensures all tasks cancel and sockets close
        raise HTTPException(status_code=502, detail=f"Upstream failure: {eg.exceptions}")
    
    return {"data": results}
```

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 AnyIO Structured Concurrency and TaskGroup Socket Lifecycle Invariants

FastAPI AnyIO Structured Concurrency and TaskGroup Socket Lifecycle Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict structured concurrency in FastAPI background workers and parallel request handlers via AnyIO TaskGroups. Prevents silent fire-and-forget sub-task orphaning, enforces deterministic cancellation cascades, and guarantees active HTTP/2 and database connection sockets are gracefully terminated when exceptions occur in concurrent branches. 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: Orphaning concurrent coroutines via unshielded fire-and-forget asyncio.create_task and unhandled ExceptionGroup socket leaks 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 DriftOrphaning concurrent coroutines via unshielded fire-and-forget asyncio.create_task and unhandled ExceptionGroup socket leaksCritical
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 use 'anyio.create_task_group()' context managers rather than raw 'asyncio.create_task()' or 'asyncio.gather()' when fanning out background coroutines.

Engineers MUST ALWAYS use 'anyio.create_task_group()' context managers rather than raw 'asyncio.create_task()' or 'asyncio.gather()' when fanning out background coroutines.

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 detached fire-and-forget tasks inside FastAPI route handlers or dependency lifecycles without bound TaskGroup boundaries or supervised worker queues.

Engineers MUST NOT spawn detached fire-and-forget tasks inside FastAPI route handlers or dependency lifecycles without bound TaskGroup boundaries or supervised worker queues.

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

Services MUST catch 'ExceptionGroup' (or BaseExceptionGroup in Python 3.11+) or use 'anyio.from_thread' bridges to prevent unhandled partial failures from hanging sibling coroutines.

Services MUST catch 'ExceptionGroup' (or BaseExceptionGroup in Python 3.11+) or use 'anyio.from_thread' bridges to prevent unhandled partial failures from hanging sibling coroutines.

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

Components NEVER hold open persistent HTTP/2 connection pools across cancellation scopes without wrapping acquisition and cleanup inside deterministic 'try ... finally' blocks.

Components NEVER hold open persistent HTTP/2 connection pools across cancellation scopes without wrapping acquisition and cleanup inside deterministic 'try ... finally' 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.
5

Code SHOULD explicitly utilize 'anyio.move_on_after()' or 'anyio.fail_after()' timeout scopes to bound asynchronous fan-outs instead of unbounded async loops.

Code SHOULD explicitly utilize 'anyio.move_on_after()' or 'anyio.fail_after()' timeout scopes to bound asynchronous fan-outs instead of unbounded async loops.

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.
6

Engineers MUST use 'anyio.CancelScope(shield=True)' strictly for non-deferrable cleanup tasks within 'finally' blocks to prevent cancellation aborts during socket teardown.

Engineers MUST use 'anyio.CancelScope(shield=True)' strictly for non-deferrable cleanup tasks within 'finally' blocks to prevent cancellation aborts during socket teardown.

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 Structured Concurrency and TaskGroup Socket Lifecycle Invariants critical for AI coding assistants?

Enforces strict structured concurrency in FastAPI background workers and parallel request handlers via AnyIO TaskGroups. Prevents silent fire-and-forget sub-task orphaning, enforces deterministic cancellation cascades, and guarantees active HTTP/2 and database connection sockets are gracefully terminated when exceptions occur in concurrent branches. 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 (Orphaning concurrent coroutines via unshielded fire-and-forget asyncio.create_task and unhandled ExceptionGroup socket leaks) 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