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

FastAPI AnyIO Structured Concurrency Session Poison Shielding

Enforces strict structured concurrency boundaries around pooled database sessions when executing concurrent child tasks via AnyIO TaskGroups or asyncio.gather in FastAPI. Prevents unhandled task cancellations and exceptions from stranding uncommitted, dirty, or transactionally poisoned connections in shared connection pools (such as SQLAlchemy AsyncEngine or asyncpg). Mandates explicit error boundaries, shielded rollbacks, and per-task isolated transactional units.

Prohibited Anti-Pattern: Sharing a Single Database Session Across AnyIO TaskGroups Without Shielded Teardown and Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Structured Concurrency Session Poison Shielding - Enforces strict structured concurrency boundaries around pooled database sessions when executing concurrent child tasks via AnyIO TaskGroups or asyncio.gather in FastAPI. Prevents unhandled task cancellations and exceptions from stranding uncommitted, dirty, or transactionally poisoned connections in shared connection pools (such as SQLAlchemy AsyncEngine or asyncpg). Mandates explicit error boundaries, shielded rollbacks, and per-task isolated transactional units.
globs: app/**/*.py, src/**/*.py, services/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-taskgroup-poison-shielding"
---

# FastAPI AnyIO Structured Concurrency Session Poison Shielding

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Sharing a Single Database Session Across AnyIO TaskGroups Without Shielded Teardown and Isolation

## System Constraints
You are a Principal Software Architect enforcing production-grade structured concurrency and resource integrity in FastAPI services using AnyIO and asynchronous database clients (SQLAlchemy AsyncSession, asyncpg). You must mandate strict transactional isolation, child task shielding, and deterministic session cleanup to prevent poisoned connections from leaking back into shared connection pools upon task failure or cancellation.

## Strict Guidelines
- Engineers MUST NEVER pass a single AsyncSession or pooled database connection across multiple concurrent tasks inside an AnyIO create_task_group() or asyncio.gather().
- Each concurrent child task MUST obtain its own distinct AsyncSession from the sessionmaker or pool to prevent race conditions on underlying protocol buffers.
- Engineers MUST wrap session cleanup (rollback or close) in anyio.CancelScope(shield=True) within finally blocks to ensure teardown runs even if the parent TaskGroup is cancelled.
- Services MUST explicitly call session.rollback() before releasing connections to the pool in exception handlers, preventing uncommitted transactional state from bleeding into subsequent requests.
- Components NEVER execute raw transactional queries inside an unhandled TaskGroup without wrapping the group in a top-level try/except/finally resource management context.

## Bad vs Good Implementations
### Poisoned Shared Session in AnyIO TaskGroup vs Shielded Per-Task Sessions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sharing a single SQLAlchemy AsyncSession or raw asyncpg connection across multiple tasks inside an AnyIO TaskGroup causes protocol race conditions. When one task raises an exception, the task group cancels all other tasks, leaving the shared transaction uncommitted and unrolled-back. Returning this dirty session to the pool poisons future requests reusing that socket.
```python
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
import anyio
from app.db import get_session

router = APIRouter()

async def worker(session: AsyncSession, item_id: int):
    # Concurrent writes on the same AsyncSession cause protocol corruption
    await session.execute("UPDATE items SET processed = true WHERE id = :id", {"id": item_id})
    if item_id == 13:
        raise ValueError("Simulated crash")

@router.post("/batch-process")
async def process_batch(session: AsyncSession = Depends(get_session)):
    # Anti-pattern: Sharing session across task group leaves uncommitted transaction
    # on failure and corrupts the connection in the pool.
    async with anyio.create_task_group() as tg:
        for item_id in range(20):
            tg.start_soon(worker, session, item_id)
    await session.commit()
    return {"status": "ok"}
```

#### Production Standard (Correct)
> **Standard**: Every concurrent child task spawns its own AsyncSession from the factory. AnyIO cancel shielding guarantees that session.rollback() runs even if the parent task group triggers a cancellation cascade, completely isolating failures and preserving connection pool integrity.
```python
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
import anyio
from app.db import get_session_factory

router = APIRouter()

async def isolated_worker(session_factory: async_sessionmaker[AsyncSession], item_id: int):
    # Each concurrent task manages its own isolated connection lifecycle
    async with session_factory() as session:
        try:
            async with session.begin():
                await session.execute("UPDATE items SET processed = true WHERE id = :id", {"id": item_id})
                if item_id == 13:
                    raise ValueError("Simulated crash")
        except Exception:
            # Shield rollback from AnyIO cancellation to ensure pool hygiene
            with anyio.CancelScope(shield=True):
                await session.rollback()
            raise

@router.post("/batch-process")
async def process_batch(session_factory: async_sessionmaker[AsyncSession] = Depends(get_session_factory)):
    async with anyio.create_task_group() as tg:
        for item_id in range(20):
            tg.start_soon(isolated_worker, session_factory, item_id)
    return {"status": "ok"}
```

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 Session Poison Shielding

FastAPI AnyIO Structured Concurrency Session Poison Shielding defines an industrial-grade behavioral standard for backend engineering. Enforces strict structured concurrency boundaries around pooled database sessions when executing concurrent child tasks via AnyIO TaskGroups or asyncio.gather in FastAPI. Prevents unhandled task cancellations and exceptions from stranding uncommitted, dirty, or transactionally poisoned connections in shared connection pools (such as SQLAlchemy AsyncEngine or asyncpg). Mandates explicit error boundaries, shielded rollbacks, and per-task isolated transactional units. 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: Sharing a Single Database Session Across AnyIO TaskGroups Without Shielded Teardown and Isolation 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 DriftSharing a Single Database Session Across AnyIO TaskGroups Without Shielded Teardown and IsolationCritical
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 NEVER pass a single AsyncSession or pooled database connection across multiple concurrent tasks inside an AnyIO create_task_group() or asyncio.gather().

Engineers MUST NEVER pass a single AsyncSession or pooled database connection across multiple concurrent tasks inside an AnyIO create_task_group() or asyncio.gather().

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

Each concurrent child task MUST obtain its own distinct AsyncSession from the sessionmaker or pool to prevent race conditions on underlying protocol buffers.

Each concurrent child task MUST obtain its own distinct AsyncSession from the sessionmaker or pool to prevent race conditions on underlying protocol buffers.

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 session cleanup (rollback or close) in anyio.CancelScope(shield=True) within finally blocks to ensure teardown runs even if the parent TaskGroup is cancelled.

Engineers MUST wrap session cleanup (rollback or close) in anyio.CancelScope(shield=True) within finally blocks to ensure teardown runs even if the parent TaskGroup is cancelled.

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 call session.rollback() before releasing connections to the pool in exception handlers, preventing uncommitted transactional state from bleeding into subsequent requests.

Services MUST explicitly call session.rollback() before releasing connections to the pool in exception handlers, preventing uncommitted transactional state from bleeding into subsequent requests.

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 execute raw transactional queries inside an unhandled TaskGroup without wrapping the group in a top-level try/except/finally resource management context.

Components NEVER execute raw transactional queries inside an unhandled TaskGroup without wrapping the group in a top-level try/except/finally resource management context.

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 Session Poison Shielding critical for AI coding assistants?

Enforces strict structured concurrency boundaries around pooled database sessions when executing concurrent child tasks via AnyIO TaskGroups or asyncio.gather in FastAPI. Prevents unhandled task cancellations and exceptions from stranding uncommitted, dirty, or transactionally poisoned connections in shared connection pools (such as SQLAlchemy AsyncEngine or asyncpg). Mandates explicit error boundaries, shielded rollbacks, and per-task isolated transactional units. 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 (Sharing a Single Database Session Across AnyIO TaskGroups Without Shielded Teardown and Isolation) 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