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

FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard

Prevents premature termination of critical audit-logging, state persistence, and resource cleanup coroutines caused by client-driven HTTP disconnects. Mandates explicit AnyIO shielded cancellation scopes or decoupled application-lifetime TaskGroups for operations that must survive client dropoffs.

Prohibited Anti-Pattern: Executing Non-Idempotent Audit Trails and State Finalization Inside Unshielded HTTP Request TaskScopes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard - Prevents premature termination of critical audit-logging, state persistence, and resource cleanup coroutines caused by client-driven HTTP disconnects. Mandates explicit AnyIO shielded cancellation scopes or decoupled application-lifetime TaskGroups for operations that must survive client dropoffs.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-cancellation-isolation-standard"
---

# FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing Non-Idempotent Audit Trails and State Finalization Inside Unshielded HTTP Request TaskScopes

## System Constraints
You are a Principal Software Architect enforcing the FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard. You must prevent premature termination of critical cleanup and audit-logging coroutines by isolating background execution contexts from incoming HTTP client-driven AnyIO task cancellations. Enforce strict separation between HTTP request cancellation scopes and non-cancellable side effects.

## Strict Guidelines
- Engineers MUST ALWAYS isolate critical mutations, audit logs, and external state flushes from client-induced cancellation using `anyio.CancelScope(shield=True)` or a persistent application-scoped task group.
- Engineers MUST NOT rely on Starlette's `BackgroundTasks` for guaranteed execution of mission-critical mutations, as unhandled exceptions in the handler can leave them unexecuted or interrupted during worker recycling.
- Code MUST apply an explicit, bounded deadline when creating shielded scopes (`with anyio.CancelScope(shield=True, deadline=...):`) to prevent unkillable hanging tasks if external dependencies stall.
- Services MUST manage fire-and-forget worker tasks via an application-level lifespan `TaskGroup` or a dedicated queue worker rather than spawning unbounded tasks inside the request lifecycle.
- Components NEVER swallow `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) without re-raising, unless explicitly executing inside a designated shielded finalization block.

## Bad vs Good Implementations
### Cancellation Isolation for Audit Logs and Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts the connection, the incoming ASGI request's AnyIO task is cancelled. The unshielded task group propagates this cancellation immediately, killing the audit log query midway and failing to record the state change.
```python
import anyio
from fastapi import FastAPI, Depends, Request
from app.db import DatabaseSession, get_db

app = FastAPI()

@app.post("/orders/{order_id}/finalize")
async def finalize_order(order_id: str, db: DatabaseSession = Depends(get_db)):
    # Vulnerable: If the client disconnects here, AnyIO cancels the entire coroutine scope
    await db.execute("UPDATE orders SET status = 'PROCESSING' WHERE id = :id", {"id": order_id})
    
    # ANTI-PATTERN: Client disconnection mid-flight cancels this critical audit step,
    # leaving the database in an inconsistent state without record of the transaction attempt.
    async with anyio.create_task_group() as tg:
        tg.start_soon(db.execute, "INSERT INTO audit_logs (order_id, action) VALUES (:id, 'FINALIZED')", {"id": order_id})
    
    return {"status": "ok"}
```

#### Production Standard (Correct)
> **Standard**: Uses `anyio.CancelScope(shield=True)` with a bounded timeout (`move_on_after`) to guarantee that critical audit events and state commits run to completion even if the HTTP client terminates the connection prematurely.
```python
import anyio
from fastapi import FastAPI, Depends, HTTPException
from app.db import DatabaseSession, get_db

app = FastAPI()
CLEANUP_DEADLINE_SECONDS = 5.0

@app.post("/orders/{order_id}/finalize")
async def finalize_order(order_id: str, db: DatabaseSession = Depends(get_db)):
    try:
        await db.execute("UPDATE orders SET status = 'PROCESSING' WHERE id = :id", {"id": order_id})
    except anyio.get_cancelled_exc_class():
        # Invariant: Catch cancel, but ensure bounded, shielded cleanup/audit executes
        with anyio.CancelScope(shield=True):
            with anyio.move_on_after(CLEANUP_DEADLINE_SECONDS):
                await db.execute(
                    "INSERT INTO audit_logs (order_id, action, status) VALUES (:id, 'FINALIZE_ABORTED', 'CANCELLED')",
                    {"id": order_id}
                )
        raise

    # Invariant: Critical commit and finalization run in a bounded, shielded scope
    with anyio.CancelScope(shield=True):
        with anyio.move_on_after(CLEANUP_DEADLINE_SECONDS):
            await db.execute(
                "INSERT INTO audit_logs (order_id, action, status) VALUES (:id, 'FINALIZED', 'SUCCESS')",
                {"id": order_id}
            )
            await db.commit()

    return {"status": "ok"}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard

FastAPI AnyIO Dynamic TaskGroup Cancellation Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Prevents premature termination of critical audit-logging, state persistence, and resource cleanup coroutines caused by client-driven HTTP disconnects. Mandates explicit AnyIO shielded cancellation scopes or decoupled application-lifetime TaskGroups for operations that must survive client dropoffs. 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: Executing Non-Idempotent Audit Trails and State Finalization Inside Unshielded HTTP Request TaskScopes 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 DriftExecuting Non-Idempotent Audit Trails and State Finalization Inside Unshielded HTTP Request TaskScopesCritical
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 isolate critical mutations, audit logs, and external state flushes from client-induced cancellation using `anyio.CancelScope(shield=True)` or a persistent application-scoped task group.

Engineers MUST ALWAYS isolate critical mutations, audit logs, and external state flushes from client-induced cancellation using `anyio.CancelScope(shield=True)` or a persistent application-scoped 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.
2

Engineers MUST NOT rely on Starlette's `BackgroundTasks` for guaranteed execution of mission-critical mutations, as unhandled exceptions in the handler can leave them unexecuted or interrupted during worker recycling.

Engineers MUST NOT rely on Starlette's `BackgroundTasks` for guaranteed execution of mission-critical mutations, as unhandled exceptions in the handler can leave them unexecuted or interrupted during worker recycling.

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 MUST apply an explicit, bounded deadline when creating shielded scopes (`with anyio.CancelScope(shield=True, deadline=...)

Code MUST apply an explicit, bounded deadline when creating shielded scopes (`with anyio.CancelScope(shield=True, deadline=...):`) to prevent unkillable hanging tasks if external dependencies stall.

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 manage fire-and-forget worker tasks via an application-level lifespan `TaskGroup` or a dedicated queue worker rather than spawning unbounded tasks inside the request lifecycle.

Services MUST manage fire-and-forget worker tasks via an application-level lifespan `TaskGroup` or a dedicated queue worker rather than spawning unbounded tasks inside 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.
5

Components NEVER swallow `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) without re-raising, unless explicitly executing inside a designated shielded finalization block.

Components NEVER swallow `anyio.get_cancelled_exc_class()` (or `asyncio.CancelledError`) without re-raising, unless explicitly executing inside a designated shielded finalization block.

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 Dynamic TaskGroup Cancellation Isolation Standard critical for AI coding assistants?

Prevents premature termination of critical audit-logging, state persistence, and resource cleanup coroutines caused by client-driven HTTP disconnects. Mandates explicit AnyIO shielded cancellation scopes or decoupled application-lifetime TaskGroups for operations that must survive client dropoffs. 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 (Executing Non-Idempotent Audit Trails and State Finalization Inside Unshielded HTTP Request TaskScopes) 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