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

FastAPI AnyIO Threadpool Backpressure and Worker Exhaustion Guardrail

FastAPI delegates synchronous endpoint handlers and starlette background tasks to AnyIO worker threads (anyio.to_thread.run_sync), which rely on a globally bounded threadpool. Unbounded synchronous blocking I/O, heavy CPU tasks without capacity tokens, or failure to tune AnyIO thread limits leads to threadpool starvation, cascading latency spikes, and deadlocks in the event loop. Systems MUST enforce bounded concurrency limiters, tune max_threadpool_tokens, and offload CPU-intensive operations to dedicated multiprocessing pools or external message queues.

Prohibited Anti-Pattern: Unbounded Synchronous Execution Starving AnyIO Worker Threadpool and Event Loop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Threadpool Backpressure and Worker Exhaustion Guardrail - FastAPI delegates synchronous endpoint handlers and starlette background tasks to AnyIO worker threads (anyio.to_thread.run_sync), which rely on a globally bounded threadpool. Unbounded synchronous blocking I/O, heavy CPU tasks without capacity tokens, or failure to tune AnyIO thread limits leads to threadpool starvation, cascading latency spikes, and deadlocks in the event loop. Systems MUST enforce bounded concurrency limiters, tune max_threadpool_tokens, and offload CPU-intensive operations to dedicated multiprocessing pools or external message queues.
globs: **/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-threadpool-backpressure-invariant"
---

# FastAPI AnyIO Threadpool Backpressure and Worker Exhaustion Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Synchronous Execution Starving AnyIO Worker Threadpool and Event Loop

## System Constraints
You are a Principal Backend Architect enforcing strict concurrency and threadpool invariants in FastAPI applications powered by AnyIO/Starlette. You must intercept and correct any unconstrained offloading of blocking tasks to the AnyIO default threadpool. Enforce explicit concurrency limiting via `anyio.CapacityLimiter`, configure `anyio.to_thread.current_default_thread_limiter()`, and prevent synchronous CPU-bound bottlenecks from starving asynchronous HTTP request handling.

## Strict Guidelines
- Engineers MUST ALWAYS configure `anyio.to_thread.current_default_thread_limiter().total_tokens` during application lifespan startup to match real infrastructure capacity and prevent unbounded OS thread spawns.
- Engineers MUST NOT offload compute-intensive/CPU-bound operations (e.g., cryptographic hashing, image processing, massive DataFrame manipulations) to `anyio.to_thread.run_sync`; use `concurrent.futures.ProcessPoolExecutor` or dedicated Celery/ARQ workers instead.
- Engineers MUST instantiate a dedicated `anyio.CapacityLimiter` for high-latency external synchronous I/O operations (e.g., legacy SDKs, synchronous database drivers) to isolate them from standard def endpoint workers.
- Services MUST monitor AnyIO thread limiter statistics (`limiter.borrowed_tokens`, `limiter.total_tokens`) through OpenTelemetry or Prometheus metrics to detect backpressure saturation before deadlocks occur.
- Components NEVER execute raw `time.sleep()`, synchronous `requests.get()`, or blocking disk I/O directly within `async def` routes without wrapping in a dedicated bounded worker limiter.

## Bad vs Good Implementations
### Unbounded Synchronous Worker Starvation vs. Isolated Bounded Capacity Limiter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring endpoints with standard 'def' causes FastAPI to execute them via AnyIO's global default thread limiter (default 40 tokens). Heavy traffic or high latency instantly consumes all available worker threads, causing subsequent requests to queue indefinitely and starving system-critical background tasks.
```python
import time
from fastapi import FastAPI

app = FastAPI()

# ANTI-PATTERN: Defining 'def' endpoint with slow blocking I/O
# FastAPI automatically offloads this to the default AnyIO threadpool without isolation.
# A burst of requests exhausts the default 40 tokens, stalling all other sync routes.
@app.post("/process-legacy")
def process_legacy_task(payload: dict):
    # Synchronous blocking call consumes a worker thread indefinitely
    time.sleep(5.0)
    return {"status": "completed", "data": payload}
```

#### Production Standard (Correct)
> **Standard**: The fix sets a global thread limit on application startup and uses an async route that offloads the blocking call to `to_thread.run_sync` with a dedicated `CapacityLimiter(10)`. This guarantees that legacy blocking operations can never consume more than 10 threads, preserving the remaining threadpool capacity for other endpoints.
```python
import time
from contextlib import asynccontextmanager
import anyio
from anyio import to_thread
from fastapi import FastAPI, Depends

# INVARIANT: Dedicated isolated capacity limiter for legacy synchronous blocking I/O
LEGACY_IO_LIMITER = anyio.CapacityLimiter(10)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Explicitly configure the AnyIO default threadpool capacity
    to_thread.current_default_thread_limiter().total_tokens = 100
    yield

app = FastAPI(lifespan=lifespan)

def blocking_sync_task(payload: dict) -> dict:
    time.sleep(5.0)
    return {"status": "completed", "data": payload}

@app.post("/process-legacy")
async def process_legacy_task(payload: dict):
    # INVARIANT: Run sync tasks inside an async handler using an explicit, isolated CapacityLimiter
    result = await to_thread.run_sync(
        blocking_sync_task,
        payload,
        limiter=LEGACY_IO_LIMITER
    )
    return result
```

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 Threadpool Backpressure and Worker Exhaustion Guardrail

FastAPI AnyIO Threadpool Backpressure and Worker Exhaustion Guardrail defines an industrial-grade behavioral standard for backend engineering. FastAPI delegates synchronous endpoint handlers and starlette background tasks to AnyIO worker threads (anyio.to_thread.run_sync), which rely on a globally bounded threadpool. Unbounded synchronous blocking I/O, heavy CPU tasks without capacity tokens, or failure to tune AnyIO thread limits leads to threadpool starvation, cascading latency spikes, and deadlocks in the event loop. Systems MUST enforce bounded concurrency limiters, tune max_threadpool_tokens, and offload CPU-intensive operations to dedicated multiprocessing pools or external message queues. 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: Unbounded Synchronous Execution Starving AnyIO Worker Threadpool and 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 DriftUnbounded Synchronous Execution Starving AnyIO Worker Threadpool and Event LoopCritical
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 configure `anyio.to_thread.current_default_thread_limiter().total_tokens` during application lifespan startup to match real infrastructure capacity and prevent unbounded OS thread spawns.

Engineers MUST ALWAYS configure `anyio.to_thread.current_default_thread_limiter().total_tokens` during application lifespan startup to match real infrastructure capacity and prevent unbounded OS thread spawns.

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 offload compute-intensive/CPU-bound operations (e.g., cryptographic hashing, image processing, massive DataFrame manipulations) to `anyio.to_thread.run_sync`

Engineers MUST NOT offload compute-intensive/CPU-bound operations (e.g., cryptographic hashing, image processing, massive DataFrame manipulations) to `anyio.to_thread.run_sync`; use `concurrent.futures.ProcessPoolExecutor` or dedicated Celery/ARQ workers instead.

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 instantiate a dedicated `anyio.CapacityLimiter` for high-latency external synchronous I/O operations (e.g., legacy SDKs, synchronous database drivers) to isolate them from standard def endpoint workers.

Engineers MUST instantiate a dedicated `anyio.CapacityLimiter` for high-latency external synchronous I/O operations (e.g., legacy SDKs, synchronous database drivers) to isolate them from standard def endpoint workers.

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 monitor AnyIO thread limiter statistics (`limiter.borrowed_tokens`, `limiter.total_tokens`) through OpenTelemetry or Prometheus metrics to detect backpressure saturation before deadlocks occur.

Services MUST monitor AnyIO thread limiter statistics (`limiter.borrowed_tokens`, `limiter.total_tokens`) through OpenTelemetry or Prometheus metrics to detect backpressure saturation before deadlocks occur.

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 `time.sleep()`, synchronous `requests.get()`, or blocking disk I/O directly within `async def` routes without wrapping in a dedicated bounded worker limiter.

Components NEVER execute raw `time.sleep()`, synchronous `requests.get()`, or blocking disk I/O directly within `async def` routes without wrapping in a dedicated bounded worker 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is FastAPI AnyIO Threadpool Backpressure and Worker Exhaustion Guardrail critical for AI coding assistants?

FastAPI delegates synchronous endpoint handlers and starlette background tasks to AnyIO worker threads (anyio.to_thread.run_sync), which rely on a globally bounded threadpool. Unbounded synchronous blocking I/O, heavy CPU tasks without capacity tokens, or failure to tune AnyIO thread limits leads to threadpool starvation, cascading latency spikes, and deadlocks in the event loop. Systems MUST enforce bounded concurrency limiters, tune max_threadpool_tokens, and offload CPU-intensive operations to dedicated multiprocessing pools or external message queues. 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 (Unbounded Synchronous Execution Starving AnyIO Worker Threadpool and 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