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

FastAPI AnyIO Structured Concurrency and Lifespan Exception Shielding

Enforces strict structured concurrency in FastAPI application lifespans using AnyIO TaskGroups to prevent orphaned coroutines, unhandled task leakage, and silent process crashes. Guarantees clean resource draining and graceful shutdowns by wrapping resource teardown in cancel-shielded scopes during termination signals.

Prohibited Anti-Pattern: Spawning detached asyncio.create_task coroutines during lifespan and unshielded teardown execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Structured Concurrency and Lifespan Exception Shielding - Enforces strict structured concurrency in FastAPI application lifespans using AnyIO TaskGroups to prevent orphaned coroutines, unhandled task leakage, and silent process crashes. Guarantees clean resource draining and graceful shutdowns by wrapping resource teardown in cancel-shielded scopes during termination signals.
globs: app/**/*.py, src/**/*.py, **/lifespan.py, **/main.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-structured-concurrency-shielding"
---

# FastAPI AnyIO Structured Concurrency and Lifespan Exception Shielding

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached asyncio.create_task coroutines during lifespan and unshielded teardown execution

## System Constraints
You are a Principal Backend Engineer enforcing AnyIO structured concurrency and cancel-safe lifespan resource management across FastAPI services. You must reject fire-and-forget task patterns such as raw asyncio.create_task in FastAPI lifespans, enforce cancel-shielded teardown routines, and mandate scoped TaskGroups.

## Strict Guidelines
- Engineers MUST ALWAYS manage persistent background coroutines within an explicit AnyIO TaskGroup instantiated in the FastAPI lifespan.
- Engineers MUST NOT invoke `asyncio.create_task` or `asyncio.ensure_future` for long-running workers during lifespan setup without deterministic supervisor bounds.
- Engineers MUST wrap post-yield lifespan cleanup code in `with anyio.CancelScope(shield=True):` to guarantee critical teardown operations run uninterrupted during cancellation cascades.
- Engineers MUST catch or properly propagate `ExceptionGroup` (or `BaseExceptionGroup`) when handling task failures spawned within the lifespan task group.
- Background worker tasks SHOULD implement explicit cancellation checkpoints using `await anyio.sleep(0)` or `anyio.checkpoint()` inside tight execution loops.

## Bad vs Good Implementations
### Lifespan Background Coroutine Supervision & Shielded Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning detached background tasks via asyncio.create_task decouples coroutines from the lifespan context. If metric_flusher raises an exception, it is unhandled until garbage collected. Furthermore, if teardown is interrupted by a cancellation signal, app.state.db.disconnect() is aborted midway, causing connection leaks.
```python
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI

async def metric_flusher():
    while True:
        await asyncio.sleep(5)
        print("Flushing metrics...")

@asynccontextmanager
async def lifespan(app: FastAPI):
    # ANTI-PATTERN: Fire-and-forget detached coroutine. Leaks if app crashes or reloads;
    # exceptions in flusher vanish or crash unhandled.
    task = asyncio.create_task(metric_flusher())
    yield
    # ANTI-PATTERN: Unshielded cancellation; if lifespan context is cancelled via SIGINT/SIGTERM,
    # database disconnect will be aborted halfway through.
    task.cancel()
    await app.state.db.disconnect()
```

#### Production Standard (Correct)
> **Standard**: Using anyio.create_task_group() establishes strict structured concurrency. If metric_flusher fails, the exception group propagates deterministically. Wrapping the shutdown sequence in a shielded cancel scope guarantees database connections drain completely without being interrupted by cancellation signals.
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
import anyio

async def metric_flusher():
    while True:
        await anyio.sleep(5)
        print("Flushing metrics...")

@asynccontextmanager
async def lifespan(app: FastAPI):
    async with anyio.create_task_group() as tg:
        # Scoped to lifespan: task lifecycle bound directly to the FastAPI server lifecycle
        tg.start_soon(metric_flusher)
        try:
            yield
        finally:
            # Shield cleanup to guarantee execution even during SIGTERM / cancellation cascades
            with anyio.CancelScope(shield=True):
                tg.cancel_scope.cancel()
                await app.state.db.disconnect()
```

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 Lifespan Exception Shielding

FastAPI AnyIO Structured Concurrency and Lifespan Exception Shielding defines an industrial-grade behavioral standard for backend engineering. Enforces strict structured concurrency in FastAPI application lifespans using AnyIO TaskGroups to prevent orphaned coroutines, unhandled task leakage, and silent process crashes. Guarantees clean resource draining and graceful shutdowns by wrapping resource teardown in cancel-shielded scopes during termination signals. 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: Spawning detached asyncio.create_task coroutines during lifespan and unshielded teardown execution 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 DriftSpawning detached asyncio.create_task coroutines during lifespan and unshielded teardown executionCritical
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 manage persistent background coroutines within an explicit AnyIO TaskGroup instantiated in the FastAPI lifespan.

Engineers MUST ALWAYS manage persistent background coroutines within an explicit AnyIO TaskGroup instantiated in the FastAPI lifespan.

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 invoke `asyncio.create_task` or `asyncio.ensure_future` for long-running workers during lifespan setup without deterministic supervisor bounds.

Engineers MUST NOT invoke `asyncio.create_task` or `asyncio.ensure_future` for long-running workers during lifespan setup without deterministic supervisor bounds.

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 post-yield lifespan cleanup code in `with anyio.CancelScope(shield=True)

Engineers MUST wrap post-yield lifespan cleanup code in `with anyio.CancelScope(shield=True):` to guarantee critical teardown operations run uninterrupted 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

Engineers MUST catch or properly propagate `ExceptionGroup` (or `BaseExceptionGroup`) when handling task failures spawned within the lifespan task group.

Engineers MUST catch or properly propagate `ExceptionGroup` (or `BaseExceptionGroup`) when handling task failures spawned within the lifespan task group.

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

Background worker tasks SHOULD implement explicit cancellation checkpoints using `await anyio.sleep(0)` or `anyio.checkpoint()` inside tight execution loops.

Background worker tasks SHOULD implement explicit cancellation checkpoints using `await anyio.sleep(0)` or `anyio.checkpoint()` inside tight execution 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.
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 Lifespan Exception Shielding critical for AI coding assistants?

Enforces strict structured concurrency in FastAPI application lifespans using AnyIO TaskGroups to prevent orphaned coroutines, unhandled task leakage, and silent process crashes. Guarantees clean resource draining and graceful shutdowns by wrapping resource teardown in cancel-shielded scopes during termination signals. 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 (Spawning detached asyncio.create_task coroutines during lifespan and unshielded teardown execution) 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