This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-anyio-capacity-limiter-partitioning-standard

FastAPI AnyIO Dynamic CapacityLimiter Partitioning Standard

Enforces isolated AnyIO CapacityLimiter instances across distinct FastAPI endpoint concurrency tiers to eliminate worker thread pool starvation. By default, AnyIO executes synchronous endpoints against a single global thread limiter (40 tokens), allowing slow, blocking I/O or legacy synchronous SDK calls to monopolize worker threads and starve latency-critical endpoints. Explicitly partitioning thread pool limiters by operational profile guarantees deterministic latency and resilient concurrency isolation.

Prohibited Anti-Pattern: Global AnyIO Thread Pool Monopolization via Unpartitioned Synchronous Endpoints

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI AnyIO Dynamic CapacityLimiter Partitioning Standard - Enforces isolated AnyIO CapacityLimiter instances across distinct FastAPI endpoint concurrency tiers to eliminate worker thread pool starvation. By default, AnyIO executes synchronous endpoints against a single global thread limiter (40 tokens), allowing slow, blocking I/O or legacy synchronous SDK calls to monopolize worker threads and starve latency-critical endpoints. Explicitly partitioning thread pool limiters by operational profile guarantees deterministic latency and resilient concurrency isolation.
globs: app/**/*.py, src/**/*.py, routers/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-anyio-capacity-limiter-partitioning-standard"
---

# FastAPI AnyIO Dynamic CapacityLimiter Partitioning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global AnyIO Thread Pool Monopolization via Unpartitioned Synchronous Endpoints

## System Constraints
You are a Principal Software Architect enforcing the FastAPI AnyIO Dynamic CapacityLimiter Partitioning Standard. Mandate explicit concurrency isolation between high-throughput quick operations and slow blocking legacy tasks executed within FastAPI worker threads. Ensure no single workload category starves the default AnyIO thread pool.

## Strict Guidelines
- Engineers MUST NEVER execute heterogeneous blocking workloads against the default global AnyIO CapacityLimiter without explicit limiter partitioning.
- Engineers MUST ALWAYS isolate distinct workload profiles (e.g., fast CPU-bound tasks, heavy legacy DB calls, slow third-party SDKs) into distinct `anyio.CapacityLimiter` instances.
- Services MUST instantiate partition limiters at application startup within the FastAPI lifespan context and inject them via FastAPI dependencies or application state.
- Engineers MUST NOT instantiate new `anyio.CapacityLimiter` instances per request, as this bypasses concurrency bounds and leaks OS-level thread resources.
- All explicit thread delegations MUST use `anyio.to_thread.run_sync(func, *args, limiter=scoped_limiter)` instead of generic `starlette.concurrency.run_in_threadpool` for non-uniform tasks.
- FastAPI `def` route endpoints that execute prolonged blocking operations MUST be refactored to `async def` and explicitly offloaded with an assigned limiter to protect fast `def` routes from starvation.

## Bad vs Good Implementations
### Unbounded Global Limiter Starvation vs. Isolated Dynamic CapacityLimiter Partitioning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring slow endpoints as synchronous `def` routes causes FastAPI to offload execution to the shared default AnyIO worker thread pool. 40 concurrent slow requests completely saturate the thread pool, causing fast synchronous endpoints and health checks to hang indefinitely.
```python
from fastapi import FastAPI
import time
import anyio

app = FastAPI()

# ANTI-PATTERN: Standard def routes execute on the shared global AnyIO limiter (default 40 tokens).
# A surge of slow legacy requests completely starves fast synchronous routes and health checks.
@app.get("/slow-legacy-export")
def slow_legacy_export():
    time.sleep(10)  # Blocks worker thread in global AnyIO thread pool
    return {"status": "complete"}

@app.get("/fast-metadata")
def fast_metadata():
    # Queued behind slow_legacy_export threads; causes cascading timeouts and latency spikes
    return {"status": "ok"}
```

#### Production Standard (Correct)
> **Standard**: The slow blocking operation is refactored into an async endpoint that explicitly delegates execution via `anyio.to_thread.run_sync` using a dedicated, bounded `CapacityLimiter`. The slow export route cannot consume more than 10 worker threads, leaving remaining thread resources and the event loop unstarved.
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, Request
import time
import anyio

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize partitioned limiters bound to application state
    app.state.legacy_export_limiter = anyio.CapacityLimiter(10)
    app.state.fast_sync_limiter = anyio.CapacityLimiter(50)
    yield

app = FastAPI(lifespan=lifespan)

def get_export_limiter(request: Request) -> anyio.CapacityLimiter:
    return request.app.state.legacy_export_limiter

def blocking_export_work() -> dict:
    time.sleep(10)  # Simulated blocking I/O / legacy SDK call
    return {"status": "complete"}

# PRODUCTION FIX: Declare as async def and explicitly offload with a dedicated CapacityLimiter
@app.get("/slow-legacy-export")
async def slow_legacy_export(
    limiter: anyio.CapacityLimiter = Depends(get_export_limiter)
):
    result = await anyio.to_thread.run_sync(
        blocking_export_work, 
        limiter=limiter
    )
    return result

@app.get("/fast-metadata")
async def fast_metadata():
    # Pure async endpoint remains entirely unaffected on the asyncio event loop
    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 Dynamic CapacityLimiter Partitioning Standard

FastAPI AnyIO Dynamic CapacityLimiter Partitioning Standard defines an industrial-grade behavioral standard for backend engineering. Enforces isolated AnyIO CapacityLimiter instances across distinct FastAPI endpoint concurrency tiers to eliminate worker thread pool starvation. By default, AnyIO executes synchronous endpoints against a single global thread limiter (40 tokens), allowing slow, blocking I/O or legacy synchronous SDK calls to monopolize worker threads and starve latency-critical endpoints. Explicitly partitioning thread pool limiters by operational profile guarantees deterministic latency and resilient concurrency isolation. 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: Global AnyIO Thread Pool Monopolization via Unpartitioned Synchronous Endpoints 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 DriftGlobal AnyIO Thread Pool Monopolization via Unpartitioned Synchronous EndpointsCritical
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 heterogeneous blocking workloads against the default global AnyIO CapacityLimiter without explicit limiter partitioning.

Engineers MUST NEVER execute heterogeneous blocking workloads against the default global AnyIO CapacityLimiter without explicit limiter partitioning.

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 ALWAYS isolate distinct workload profiles (e.g., fast CPU-bound tasks, heavy legacy DB calls, slow third-party SDKs) into distinct `anyio.CapacityLimiter` instances.

Engineers MUST ALWAYS isolate distinct workload profiles (e.g., fast CPU-bound tasks, heavy legacy DB calls, slow third-party SDKs) into distinct `anyio.CapacityLimiter` instances.

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

Services MUST instantiate partition limiters at application startup within the FastAPI lifespan context and inject them via FastAPI dependencies or application state.

Services MUST instantiate partition limiters at application startup within the FastAPI lifespan context and inject them via FastAPI dependencies or application state.

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 NOT instantiate new `anyio.CapacityLimiter` instances per request, as this bypasses concurrency bounds and leaks OS-level thread resources.

Engineers MUST NOT instantiate new `anyio.CapacityLimiter` instances per request, as this bypasses concurrency bounds and leaks OS-level thread resources.

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

All explicit thread delegations MUST use `anyio.to_thread.run_sync(func, *args, limiter=scoped_limiter)` instead of generic `starlette.concurrency.run_in_threadpool` for non-uniform tasks.

All explicit thread delegations MUST use `anyio.to_thread.run_sync(func, *args, limiter=scoped_limiter)` instead of generic `starlette.concurrency.run_in_threadpool` for non-uniform tasks.

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

FastAPI `def` route endpoints that execute prolonged blocking operations MUST be refactored to `async def` and explicitly offloaded with an assigned limiter to protect fast `def` routes from starvation.

FastAPI `def` route endpoints that execute prolonged blocking operations MUST be refactored to `async def` and explicitly offloaded with an assigned limiter to protect fast `def` routes from starvation.

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 Dynamic CapacityLimiter Partitioning Standard critical for AI coding assistants?

Enforces isolated AnyIO CapacityLimiter instances across distinct FastAPI endpoint concurrency tiers to eliminate worker thread pool starvation. By default, AnyIO executes synchronous endpoints against a single global thread limiter (40 tokens), allowing slow, blocking I/O or legacy synchronous SDK calls to monopolize worker threads and starve latency-critical endpoints. Explicitly partitioning thread pool limiters by operational profile guarantees deterministic latency and resilient concurrency isolation. 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 (Global AnyIO Thread Pool Monopolization via Unpartitioned Synchronous Endpoints) 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