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

FastAPI AnyIO Worker Thread Boundary and Event Loop Starvation Guardrail

Enforces strict physical boundaries between the asyncio event loop, AnyIO worker thread pools, and process pools in FastAPI applications. Prevents synchronous legacy I/O drivers, unbuffered disk operations, and heavy CPU-bound serialization from monopolizing the event loop tick and inducing severe cascading tail-latency under burst concurrency.

Prohibited Anti-Pattern: Executing blocking synchronous I/O or heavy CPU-bound parsing directly within `async def` endpoints, starving the single-threaded asyncio event loop.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Worker Thread Boundary and Event Loop Starvation Guardrail - Enforces strict physical boundaries between the asyncio event loop, AnyIO worker thread pools, and process pools in FastAPI applications. Prevents synchronous legacy I/O drivers, unbuffered disk operations, and heavy CPU-bound serialization from monopolizing the event loop tick and inducing severe cascading tail-latency under burst concurrency.
globs: **/*.py, app/**/*.py, routers/**/*.py, services/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-worker-thread-boundary-loop-starvation-guardrail"
---

# FastAPI AnyIO Worker Thread Boundary and Event Loop Starvation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing blocking synchronous I/O or heavy CPU-bound parsing directly within `async def` endpoints, starving the single-threaded asyncio event loop.

## System Constraints
You are a Principal Engineer enforcing the FastAPI AnyIO Worker Thread Boundary and Loop Starvation Guardrail. You mandate that the asyncio event loop is never blocked by sync I/O or CPU-intensive serialization. You require explicit usage of `anyio.to_thread.run_sync` with custom `CapacityLimiter` instances for blocking drivers, and process pools for heavy computation, preventing loop starvation and threadpool saturation.

## Strict Guidelines
- Engineers MUST NEVER execute blocking I/O operations (e.g., synchronous SQLAlchemy, `requests`, `boto3`, legacy redis, `open()`) inside an `async def` endpoint or coroutine.
- Engineers MUST wrap legacy synchronous blocking functions with `anyio.to_thread.run_sync` using a dedicated, bounded `anyio.CapacityLimiter` when async alternatives do not exist.
- Engineers MUST NOT rely on the default AnyIO thread limiter (40 tokens) for high-latency external dependencies, as this risks thread exhaustion across unrelated application routes.
- CPU-bound operations taking more than 5ms (e.g., bulk Pydantic model serialization of 10,000+ items, PDF generation, cryptographic operations) MUST be delegated to a `concurrent.futures.ProcessPoolExecutor` or an external worker queue.
- Engineers MUST understand FastAPI route declaration mechanics: defining standard `def` routes automatically offloads execution to the default AnyIO threadpool, which MUST NOT be starved by unmetered long-lived blocking calls.
- Streaming responses MUST yield via non-blocking async generators to avoid pinning AnyIO worker threads throughout the duration of client transfer.
- Database connections inside thread workers MUST be scoped and safely returned to the pool using synchronous context managers inside the worker boundary, never retaining open cross-loop states.

## Bad vs Good Implementations
### Blocking Legacy I/O and Bulk Serialization in Async Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing `requests.get` and synchronous file I/O directly in an `async def` function blocks the asyncio event loop for the duration of the network trip and disk write. All other concurrent requests sharing this worker process will stall, leading to high latency and failed Kubernetes liveness probes.
```python
import json
import requests
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

router = APIRouter()

class DataPayload(BaseModel):
    id: str
    metadata: dict

@router.post("/ingest/{item_id}")
async def ingest_item(item_id: str):
    # CRITICAL FLAW: Blocking synchronous HTTP request inside async def halts event loop
    resp = requests.get(f"https://legacy-api.internal/items/{item_id}", timeout=10)
    if resp.status_code != 200:
        raise HTTPException(status_code=502, detail="Upstream failure")
    
    raw_data = resp.json()
    
    # CRITICAL FLAW: CPU-heavy JSON stringification and transformation on 50,000 entities
    # blocks the event loop tick, causing health checks and concurrent requests to time out
    serialized = [DataPayload(**item).model_dump() for item in raw_data["items"]]
    with open(f"/tmp/cache_{item_id}.json", "w") as f:
        json.dump(serialized, f)
        
    return {"status": "ok", "count": len(serialized)}
```

#### Production Standard (Correct)
> **Standard**: The revised handler utilizes `httpx.AsyncClient` for non-blocking network calls, delegates CPU-bound payload deserialization to a dedicated `ProcessPoolExecutor`, and utilizes non-blocking file operations (`anyio.open_file`). The asyncio event loop remains fully responsive.
```python
from concurrent.futures import ProcessPoolExecutor
from functools import partial
import anyio
from anyio import to_thread, CapacityLimiter
from fastapi import APIRouter, HTTPException
import httpx
from pydantic import BaseModel

router = APIRouter()
LEGACY_LIMITER = CapacityLimiter(20)
PROCESS_POOL = ProcessPoolExecutor(max_workers=4)

class DataPayload(BaseModel):
    id: str
    metadata: dict

def cpu_transform_payload(raw_items: list[dict]) -> list[dict]:
    # Isolated in a separate process to avoid GIL and event loop starvation
    return [DataPayload(**item).model_dump() for item in raw_items]

@router.post("/ingest/{item_id}")
async def ingest_item(item_id: str):
    # 1. Non-blocking asynchronous I/O
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(f"https://legacy-api.internal/items/{item_id}")
        if resp.status_code != 200:
            raise HTTPException(status_code=502, detail="Upstream failure")
        raw_data = resp.json()

    # 2. CPU-bound parsing offloaded to ProcessPoolExecutor
    loop = anyio.get_running_loop()
    serialized = await loop.run_in_executor(
        PROCESS_POOL, 
        partial(cpu_transform_payload, raw_data["items"])
    )

    # 3. Synchronous disk write isolated to AnyIO worker thread with bounded limiter
    async with await anyio.open_file(f"/tmp/cache_{item_id}.json", "w") as f:
        await f.write(str(serialized))
        
    return {"status": "ok", "count": len(serialized)}
```

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 Worker Thread Boundary and Event Loop Starvation Guardrail

FastAPI AnyIO Worker Thread Boundary and Event Loop Starvation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict physical boundaries between the asyncio event loop, AnyIO worker thread pools, and process pools in FastAPI applications. Prevents synchronous legacy I/O drivers, unbuffered disk operations, and heavy CPU-bound serialization from monopolizing the event loop tick and inducing severe cascading tail-latency under burst concurrency. 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 blocking synchronous I/O or heavy CPU-bound parsing directly within `async def` endpoints, starving the single-threaded asyncio event loop. 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 blocking synchronous I/O or heavy CPU-bound parsing directly within `async def` endpoints, starving the single-threaded asyncio event loop.Critical
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 execute blocking I/O operations (e.g., synchronous SQLAlchemy, `requests`, `boto3`, legacy redis, `open()`) inside an `async def` endpoint or coroutine.

Engineers MUST NEVER execute blocking I/O operations (e.g., synchronous SQLAlchemy, `requests`, `boto3`, legacy redis, `open()`) inside an `async def` endpoint or coroutine.

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 wrap legacy synchronous blocking functions with `anyio.to_thread.run_sync` using a dedicated, bounded `anyio.CapacityLimiter` when async alternatives do not exist.

Engineers MUST wrap legacy synchronous blocking functions with `anyio.to_thread.run_sync` using a dedicated, bounded `anyio.CapacityLimiter` when async alternatives do not exist.

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 rely on the default AnyIO thread limiter (40 tokens) for high-latency external dependencies, as this risks thread exhaustion across unrelated application routes.

Engineers MUST NOT rely on the default AnyIO thread limiter (40 tokens) for high-latency external dependencies, as this risks thread exhaustion across unrelated application routes.

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

CPU-bound operations taking more than 5ms (e.g., bulk Pydantic model serialization of 10,000+ items, PDF generation, cryptographic operations) MUST be delegated to a `concurrent.futures.ProcessPoolExecutor` or an external worker queue.

CPU-bound operations taking more than 5ms (e.g., bulk Pydantic model serialization of 10,000+ items, PDF generation, cryptographic operations) MUST be delegated to a `concurrent.futures.ProcessPoolExecutor` or an external worker queue.

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 understand FastAPI route declaration mechanics

Engineers MUST understand FastAPI route declaration mechanics: defining standard `def` routes automatically offloads execution to the default AnyIO threadpool, which MUST NOT be starved by unmetered long-lived blocking calls.

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

Streaming responses MUST yield via non-blocking async generators to avoid pinning AnyIO worker threads throughout the duration of client transfer.

Streaming responses MUST yield via non-blocking async generators to avoid pinning AnyIO worker threads throughout the duration of client transfer.

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

Database connections inside thread workers MUST be scoped and safely returned to the pool using synchronous context managers inside the worker boundary, never retaining open cross-loop states.

Database connections inside thread workers MUST be scoped and safely returned to the pool using synchronous context managers inside the worker boundary, never retaining open cross-loop states.

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 Worker Thread Boundary and Event Loop Starvation Guardrail critical for AI coding assistants?

Enforces strict physical boundaries between the asyncio event loop, AnyIO worker thread pools, and process pools in FastAPI applications. Prevents synchronous legacy I/O drivers, unbuffered disk operations, and heavy CPU-bound serialization from monopolizing the event loop tick and inducing severe cascading tail-latency under burst concurrency. 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 blocking synchronous I/O or heavy CPU-bound parsing directly within `async def` endpoints, starving the single-threaded asyncio event loop.) 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