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

FastAPI Async Dependency Injection Concurrency and Deadlock Guardrail

Enforces strict isolation between asynchronous event loop contexts and blocking synchronous I/O operations within FastAPI dependency injection graphs. Prevents complete asyncio event loop starvation, threadpool deadlocks, and worker worker-hang cascades by mandating fully non-blocking asynchronous drivers or explicit offloading via anyio.to_thread.run_sync.

Prohibited Anti-Pattern: Calling blocking I/O calls directly within async def dependencies or mixing synchronous database engines into async endpoint execution graphs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Async Dependency Injection Concurrency and Deadlock Guardrail - Enforces strict isolation between asynchronous event loop contexts and blocking synchronous I/O operations within FastAPI dependency injection graphs. Prevents complete asyncio event loop starvation, threadpool deadlocks, and worker worker-hang cascades by mandating fully non-blocking asynchronous drivers or explicit offloading via anyio.to_thread.run_sync.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-async-di-deadlock-guardrail"
---

# FastAPI Async Dependency Injection Concurrency and Deadlock Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Calling blocking I/O calls directly within async def dependencies or mixing synchronous database engines into async endpoint execution graphs

## System Constraints
You are a Principal Software Architect enforcing production-grade concurrency invariants in FastAPI applications. Your mission is to eliminate asyncio event loop stalling and anyio/starlette threadpool exhaustion caused by misuse of synchronous I/O, synchronous database sessions, and blocking third-party SDKs inside async def dependencies and route handlers. You mandate Ruff/Bake AST linting patterns (e.g., flake8-async, ASYNC rules) and pure asynchronous dependency trees.

## Strict Guidelines
- Engineers MUST NEVER invoke synchronous blocking I/O calls (such as requests.get, time.sleep, blocking redis-py, standard open(), or sync SQLAlchemy Session operations) directly inside an 'async def' dependency or route handler.
- Engineers MUST declare dependencies requiring synchronous libraries as plain synchronous functions ('def dep(...)') so FastAPI automatically offloads them to the external anyio threadpool, OR explicitly offload them via 'await anyio.to_thread.run_sync(...)'.
- Engineers MUST NOT declare 'async def' dependencies that yield a synchronous database session (e.g., yielding sqlalchemy.orm.Session within an async generator), as this forces synchronous context tearing onto the asyncio loop.
- Engineers MUST configure all asynchronous database integrations using dedicated async sessions (e.g., AsyncSession from sqlalchemy.ext.asyncio) and fully asynchronous drivers (e.g., asyncpg, psycopg3 async).
- Engineers MUST verify static compliance using Ruff with rules ASYNC100, ASYNC101, ASYNC102, ASYNC210, and ASYNC220 enabled across all dependency and router paths.
- Services MUST bound the threadpool size via anyio/concurrent.futures when heavy mixed workloads run to prevent unbounded thread context-switching overhead.

## Bad vs Good Implementations
### Blocking Database Session and Sync HTTP in Async Dependency Tree

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking synchronous operations (requests.get, time.sleep, session.close, db.execute) inside an 'async def' function blocks the single thread hosting the asyncio event loop. Under concurrent load, all other concurrent requests are blocked from processing, causing latency spikes, timed-out connections, and worker deadlock.
```python
import time
import requests
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
from app.db import sync_session_factory

app = FastAPI()

# Anti-pattern: async def using synchronous session and blocking network call
async def get_db_and_tenant():
    session = sync_session_factory()
    try:
        # Stalls the entire asyncio event loop for all concurrent requests
        resp = requests.get("https://auth.internal/tenant/verify", timeout=5)
        time.sleep(0.05)  # Blocking sleep
        yield session
    finally:
        session.close()  # Synchronous commit/close blocking event loop

@app.get("/data")
async def fetch_data(db: Session = Depends(get_db_and_tenant)):
    # Blocking database read on event loop
    return db.execute("SELECT 1").scalars().all()
```

#### Production Standard (Correct)
> **Standard**: Replaces synchronous I/O with native asynchronous primitives: AsyncSession with asyncpg/psycopg3, httpx.AsyncClient for external HTTP calls, and native async context managers. The event loop remains unblocked and fully responsive under high throughput.
```python
from collections.abc import AsyncGenerator
import httpx
from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import async_session_factory

app = FastAPI()

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_factory() as session:
        yield session

async def verify_tenant(client: httpx.AsyncClient = Depends()) -> dict:
    # Pure non-blocking async network I/O
    resp = await client.get("https://auth.internal/tenant/verify", timeout=5.0)
    resp.raise_for_status()
    return resp.json()

@app.get("/data")
async def fetch_data(
    tenant: dict = Depends(verify_tenant),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(text("SELECT 1"))
    return result.scalars().all()
```

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 Async Dependency Injection Concurrency and Deadlock Guardrail

FastAPI Async Dependency Injection Concurrency and Deadlock Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict isolation between asynchronous event loop contexts and blocking synchronous I/O operations within FastAPI dependency injection graphs. Prevents complete asyncio event loop starvation, threadpool deadlocks, and worker worker-hang cascades by mandating fully non-blocking asynchronous drivers or explicit offloading via anyio.to_thread.run_sync. 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: Calling blocking I/O calls directly within async def dependencies or mixing synchronous database engines into async endpoint execution graphs 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 DriftCalling blocking I/O calls directly within async def dependencies or mixing synchronous database engines into async endpoint execution graphsCritical
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 invoke synchronous blocking I/O calls (such as requests.get, time.sleep, blocking redis-py, standard open(), or sync SQLAlchemy Session operations) directly inside an 'async def' dependency or route handler.

Engineers MUST NEVER invoke synchronous blocking I/O calls (such as requests.get, time.sleep, blocking redis-py, standard open(), or sync SQLAlchemy Session operations) directly inside an 'async def' dependency or route handler.

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 declare dependencies requiring synchronous libraries as plain synchronous functions ('def dep(...)') so FastAPI automatically offloads them to the external anyio threadpool, OR explicitly offload them via 'await anyio.to_thread.run_sync(...)'.

Engineers MUST declare dependencies requiring synchronous libraries as plain synchronous functions ('def dep(...)') so FastAPI automatically offloads them to the external anyio threadpool, OR explicitly offload them via 'await anyio.to_thread.run_sync(...)'.

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 NOT declare 'async def' dependencies that yield a synchronous database session (e.g., yielding sqlalchemy.orm.Session within an async generator), as this forces synchronous context tearing onto the asyncio loop.

Engineers MUST NOT declare 'async def' dependencies that yield a synchronous database session (e.g., yielding sqlalchemy.orm.Session within an async generator), as this forces synchronous context tearing onto the asyncio loop.

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 configure all asynchronous database integrations using dedicated async sessions (e.g., AsyncSession from sqlalchemy.ext.asyncio) and fully asynchronous drivers (e.g., asyncpg, psycopg3 async).

Engineers MUST configure all asynchronous database integrations using dedicated async sessions (e.g., AsyncSession from sqlalchemy.ext.asyncio) and fully asynchronous drivers (e.g., asyncpg, psycopg3 async).

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

Engineers MUST verify static compliance using Ruff with rules ASYNC100, ASYNC101, ASYNC102, ASYNC210, and ASYNC220 enabled across all dependency and router paths.

Engineers MUST verify static compliance using Ruff with rules ASYNC100, ASYNC101, ASYNC102, ASYNC210, and ASYNC220 enabled across all dependency and router paths.

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

Services MUST bound the threadpool size via anyio/concurrent.futures when heavy mixed workloads run to prevent unbounded thread context-switching overhead.

Services MUST bound the threadpool size via anyio/concurrent.futures when heavy mixed workloads run to prevent unbounded thread context-switching overhead.

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 Async Dependency Injection Concurrency and Deadlock Guardrail critical for AI coding assistants?

Enforces strict isolation between asynchronous event loop contexts and blocking synchronous I/O operations within FastAPI dependency injection graphs. Prevents complete asyncio event loop starvation, threadpool deadlocks, and worker worker-hang cascades by mandating fully non-blocking asynchronous drivers or explicit offloading via anyio.to_thread.run_sync. 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 (Calling blocking I/O calls directly within async def dependencies or mixing synchronous database engines into async endpoint execution graphs) 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