This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-anyio-worker-threadpool-circuit-breaker

FastAPI AnyIO Worker Thread Pool Offloading and Concurrency Shedding Circuit Breaker

Uninstrumented synchronous I/O and intensive CPU-bound serialization inside async FastAPI handlers cause severe asyncio event loop starvation and thread pool starvation. This standard mandates explicit offloading to AnyIO worker thread pools governed by an isolated CapacityLimiter and an adaptive circuit breaker that sheds load before thread worker queue saturation degrades service reliability.

Prohibited Anti-Pattern: Executing blocking I/O or heavy Pydantic serialization directly in async def handlers or unbounded run_in_threadpool invocations.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Worker Thread Pool Offloading and Concurrency Shedding Circuit Breaker - Uninstrumented synchronous I/O and intensive CPU-bound serialization inside async FastAPI handlers cause severe asyncio event loop starvation and thread pool starvation. This standard mandates explicit offloading to AnyIO worker thread pools governed by an isolated CapacityLimiter and an adaptive circuit breaker that sheds load before thread worker queue saturation degrades service reliability.
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-worker-threadpool-circuit-breaker"
---

# FastAPI AnyIO Worker Thread Pool Offloading and Concurrency Shedding Circuit Breaker

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing blocking I/O or heavy Pydantic serialization directly in async def handlers or unbounded run_in_threadpool invocations.

## System Constraints
You are a Principal Backend Architect enforcing non-blocking event-loop hygiene and thread-safe bounded concurrency in FastAPI applications. You must reject any code executing blocking I/O, heavy CPU transformations, or unbounded sync calls inside async route handlers. You mandate the use of anyio.to_thread.run_sync bound with explicit anyio.CapacityLimiter instances and circuit-breaker rejection semantics.

## Strict Guidelines
- Engineers MUST NEVER execute blocking I/O (e.g., standard open(), requests, legacy synchronous database drivers) or high-complexity Pydantic/JSON transformations directly inside async def routes.
- Engineers MUST configure and inject an isolated anyio.CapacityLimiter rather than relying on the shared default AnyIO worker thread pool token budget.
- Engineers MUST implement explicit load shedding (HTTP 503 Service Unavailable or fallback responses) via a fail-fast timeout or limiter acquisition check before offloading work to threads.
- Code SHOULD wrap CPU-bound Pydantic serialization operations exceeding 5ms p99 latency in anyio.to_thread.run_sync using a dedicated CPU-bound limiter.
- Services MUST monitor limiter statistics (borrowed_tokens and available_tokens) and expose these metrics to telemetry collectors to detect thread exhaustion.
- Components NEVER invoke starlette.concurrency.run_in_threadpool without an explicit limiter or queue bounds, as it relies on unbounded thread scheduling defaults.

## Bad vs Good Implementations
### Unbounded Sync Execution vs. Capacity-Limited Thread Offload with Shedding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly running time.sleep() or CPU-intensive data transformations in an async def function halts the single-threaded asyncio event loop. All concurrent network I/O, heartbeat signals, and health check endpoints freeze during execution.
```python
import time
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class HeavyPayload(BaseModel):
    data: list[dict]

@app.post("/process")
async def process_payload(payload: HeavyPayload):
    # VIOLATION: Blocking sleep / synchronous I/O on the main asyncio event loop
    # Starves the loop, blocking all concurrent requests and health checks.
    time.sleep(0.25)
    
    # VIOLATION: CPU-bound heavy serialization on the event loop
    transformed = [item for item in payload.data if "valid" in item]
    return {"status": "completed", "count": len(transformed)}
```

#### Production Standard (Correct)
> **Standard**: The synchronous operation is offloaded via anyio.to_thread.run_sync governed by an isolated CapacityLimiter. If the limiter is saturated, incoming calls are rejected early with HTTP 503, protecting the asyncio loop and downstream resources.
```python
import anyio
from anyio import to_thread
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel

app = FastAPI()

# Bounded worker capacity limiter preventing thread exhaustion
SYNC_IO_LIMITER = anyio.CapacityLimiter(total_tokens=20)

class HeavyPayload(BaseModel):
    data: list[dict]

def _blocking_io_work(data: list[dict]) -> int:
    # Simulating unavoidable synchronous legacy SDK or file I/O
    import time
    time.sleep(0.25)
    return len([item for item in data if "valid" in item])

@app.post("/process")
async def process_payload(payload: HeavyPayload):
    # Circuit breaker / Concurrency Shedding check
    if SYNC_IO_LIMITER.available_tokens <= 0:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Worker pool saturated; load shed to protect event loop."
        )
    
    try:
        # Enforce execution in bounded worker thread with strict acquisition timeout
        async with anyio.fail_after(delay=1.0):
            result = await to_thread.run_sync(
                _blocking_io_work,
                payload.data,
                limiter=SYNC_IO_LIMITER
            )
        return {"status": "completed", "count": result}
    except* TimeoutError:
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT,
            detail="Synchronous processing timed out"
        )
```

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 Pool Offloading and Concurrency Shedding Circuit Breaker

FastAPI AnyIO Worker Thread Pool Offloading and Concurrency Shedding Circuit Breaker defines an industrial-grade behavioral standard for backend engineering. Uninstrumented synchronous I/O and intensive CPU-bound serialization inside async FastAPI handlers cause severe asyncio event loop starvation and thread pool starvation. This standard mandates explicit offloading to AnyIO worker thread pools governed by an isolated CapacityLimiter and an adaptive circuit breaker that sheds load before thread worker queue saturation degrades service reliability. 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 I/O or heavy Pydantic serialization directly in async def handlers or unbounded run_in_threadpool invocations. 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 I/O or heavy Pydantic serialization directly in async def handlers or unbounded run_in_threadpool invocations.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 (e.g., standard open(), requests, legacy synchronous database drivers) or high-complexity Pydantic/JSON transformations directly inside async def routes.

Engineers MUST NEVER execute blocking I/O (e.g., standard open(), requests, legacy synchronous database drivers) or high-complexity Pydantic/JSON transformations directly inside async def 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.
2

Engineers MUST configure and inject an isolated anyio.CapacityLimiter rather than relying on the shared default AnyIO worker thread pool token budget.

Engineers MUST configure and inject an isolated anyio.CapacityLimiter rather than relying on the shared default AnyIO worker thread pool token budget.

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 implement explicit load shedding (HTTP 503 Service Unavailable or fallback responses) via a fail-fast timeout or limiter acquisition check before offloading work to threads.

Engineers MUST implement explicit load shedding (HTTP 503 Service Unavailable or fallback responses) via a fail-fast timeout or limiter acquisition check before offloading work to threads.

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

Code SHOULD wrap CPU-bound Pydantic serialization operations exceeding 5ms p99 latency in anyio.to_thread.run_sync using a dedicated CPU-bound limiter.

Code SHOULD wrap CPU-bound Pydantic serialization operations exceeding 5ms p99 latency in anyio.to_thread.run_sync using a dedicated CPU-bound limiter.

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

Services MUST monitor limiter statistics (borrowed_tokens and available_tokens) and expose these metrics to telemetry collectors to detect thread exhaustion.

Services MUST monitor limiter statistics (borrowed_tokens and available_tokens) and expose these metrics to telemetry collectors to detect thread exhaustion.

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

Components NEVER invoke starlette.concurrency.run_in_threadpool without an explicit limiter or queue bounds, as it relies on unbounded thread scheduling defaults.

Components NEVER invoke starlette.concurrency.run_in_threadpool without an explicit limiter or queue bounds, as it relies on unbounded thread scheduling defaults.

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 Pool Offloading and Concurrency Shedding Circuit Breaker critical for AI coding assistants?

Uninstrumented synchronous I/O and intensive CPU-bound serialization inside async FastAPI handlers cause severe asyncio event loop starvation and thread pool starvation. This standard mandates explicit offloading to AnyIO worker thread pools governed by an isolated CapacityLimiter and an adaptive circuit breaker that sheds load before thread worker queue saturation degrades service reliability. 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 I/O or heavy Pydantic serialization directly in async def handlers or unbounded run_in_threadpool invocations.) 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