This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-pep703-free-threaded-dependency-barrier

FastAPI Free-Threaded (PEP 703) Async Dependency Concurrency Barrier

Enforces strict thread-safe isolation and synchronization barriers for FastAPI dependency providers and shared singletons operating under Python 3.13 free-threaded (nogil) runtimes. Without the Global Interpreter Lock, multi-threaded event loop worker topologies trigger data races, non-atomic cache updates, and memory corruption in mutable stateful dependencies.

Prohibited Anti-Pattern: Unsynchronized Singleton State Mutation Across Multi-Threaded Free-Threaded Workers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Free-Threaded (PEP 703) Async Dependency Concurrency Barrier - Enforces strict thread-safe isolation and synchronization barriers for FastAPI dependency providers and shared singletons operating under Python 3.13 free-threaded (nogil) runtimes. Without the Global Interpreter Lock, multi-threaded event loop worker topologies trigger data races, non-atomic cache updates, and memory corruption in mutable stateful dependencies.
globs: app/**/*.py, src/**/*.py, services/**/*.py, dependencies/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-pep703-free-threaded-dependency-barrier"
---

# FastAPI Free-Threaded (PEP 703) Async Dependency Concurrency Barrier

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Singleton State Mutation Across Multi-Threaded Free-Threaded Workers

## System Constraints
You are a Principal Backend Architect enforcing PEP 703 (Free-Threaded CPython) safety invariants in FastAPI services. Under Python 3.13+ nogil runtimes, relying on the GIL for implicit atomicity across application dependencies is fatal. You must guarantee thread-safe state access, eliminate unsynchronized module-level caching, mandate thread-safe primitives (such as threading.Lock or cross-thread mutexes), and enforce immutable dependency injection patterns.

## Strict Guidelines
- Engineers MUST NOT rely on Python dictionary operations or in-memory caches being thread-safe under PEP 703 free-threaded builds without explicit synchronization.
- Engineers MUST ALWAYS protect mutable module-level or singleton states within FastAPI dependencies using `threading.Lock` or `threading.RLock`, never pure `asyncio.Lock` when work is dispatched across native thread pools.
- Services MUST isolate thread-bound event loops by ensuring async synchronization barriers do not leak or cross native OS thread boundaries created by multi-threaded ASGI worker servers.
- Engineers MUST use thread-safe data structures like `queue.Queue` or thread-locked dict containers instead of standard collections for cross-request aggregation.
- Code SHOULD prefer immutable dependency injection via request-scoped `dataclasses(frozen=True)` rather than shared stateful singleton instances.

## Bad vs Good Implementations
### PEP 703 Unsynchronized In-Memory Cache Dependency vs Thread-Safe Locking Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Under PEP 703 free-threaded CPython, dictionary accesses and read-modify-write patterns are no longer protected by the GIL. Concurrent execution from worker threads causes torn reads, lost updates, and potential interpreter crash vectors under heavy concurrent request loads.
```python
from fastapi import Depends, FastAPI

app = FastAPI()

# Anti-pattern: Global state shared across threads without GIL
_metrics_cache: dict[str, int] = {}

async def get_metrics_store() -> dict[str, int]:
    # In Python 3.13 free-threaded runtimes, concurrent writes from
    # multiple threads dispatching async tasks corrupt internal dict state
    return _metrics_cache

@app.post("/increment/{metric}")
async def record_metric(metric: str, store: dict[str, int] = Depends(get_metrics_store)):
    current = store.get(metric, 0)
    store[metric] = current + 1  # Race condition: non-atomic check-then-act
    return {"metric": metric, "count": store[metric]}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates shared mutable state behind an explicit `threading.Lock` barrier within a slotted dataclass. Under free-threaded Python 3.13, multi-threaded worker pipelines obtain mutual exclusion over the data structure, preventing race conditions and heap corruption.
```python
from dataclasses import dataclass, field
import threading
from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

@dataclass(slots=True)
class ThreadSafeMetricsStore:
    _lock: threading.Lock = field(default_factory=threading.Lock)
    _data: dict[str, int] = field(default_factory=dict)

    def increment(self, metric: str) -> int:
        with self._lock:
            val = self._data.get(metric, 0) + 1
            self._data[metric] = val
            return val

# Explicit singleton instance with thread synchronization barrier
_singleton_store = ThreadSafeMetricsStore()

def get_metrics_store() -> ThreadSafeMetricsStore:
    return _singleton_store

@app.post("/increment/{metric}")
async def record_metric(
    metric: str,
    store: Annotated[ThreadSafeMetricsStore, Depends(get_metrics_store)]
):
    new_count = store.increment(metric)
    return {"metric": metric, "count": new_count}
```

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 Free-Threaded (PEP 703) Async Dependency Concurrency Barrier

FastAPI Free-Threaded (PEP 703) Async Dependency Concurrency Barrier defines an industrial-grade behavioral standard for backend engineering. Enforces strict thread-safe isolation and synchronization barriers for FastAPI dependency providers and shared singletons operating under Python 3.13 free-threaded (nogil) runtimes. Without the Global Interpreter Lock, multi-threaded event loop worker topologies trigger data races, non-atomic cache updates, and memory corruption in mutable stateful dependencies. 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: Unsynchronized Singleton State Mutation Across Multi-Threaded Free-Threaded Workers 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 DriftUnsynchronized Singleton State Mutation Across Multi-Threaded Free-Threaded WorkersCritical
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 NOT rely on Python dictionary operations or in-memory caches being thread-safe under PEP 703 free-threaded builds without explicit synchronization.

Engineers MUST NOT rely on Python dictionary operations or in-memory caches being thread-safe under PEP 703 free-threaded builds without explicit synchronization.

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 protect mutable module-level or singleton states within FastAPI dependencies using `threading.Lock` or `threading.RLock`, never pure `asyncio.Lock` when work is dispatched across native thread pools.

Engineers MUST ALWAYS protect mutable module-level or singleton states within FastAPI dependencies using `threading.Lock` or `threading.RLock`, never pure `asyncio.Lock` when work is dispatched across native thread pools.

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 isolate thread-bound event loops by ensuring async synchronization barriers do not leak or cross native OS thread boundaries created by multi-threaded ASGI worker servers.

Services MUST isolate thread-bound event loops by ensuring async synchronization barriers do not leak or cross native OS thread boundaries created by multi-threaded ASGI worker servers.

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 use thread-safe data structures like `queue.Queue` or thread-locked dict containers instead of standard collections for cross-request aggregation.

Engineers MUST use thread-safe data structures like `queue.Queue` or thread-locked dict containers instead of standard collections for cross-request aggregation.

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

Code SHOULD prefer immutable dependency injection via request-scoped `dataclasses(frozen=True)` rather than shared stateful singleton instances.

Code SHOULD prefer immutable dependency injection via request-scoped `dataclasses(frozen=True)` rather than shared stateful singleton 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is FastAPI Free-Threaded (PEP 703) Async Dependency Concurrency Barrier critical for AI coding assistants?

Enforces strict thread-safe isolation and synchronization barriers for FastAPI dependency providers and shared singletons operating under Python 3.13 free-threaded (nogil) runtimes. Without the Global Interpreter Lock, multi-threaded event loop worker topologies trigger data races, non-atomic cache updates, and memory corruption in mutable stateful dependencies. 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 (Unsynchronized Singleton State Mutation Across Multi-Threaded Free-Threaded Workers) 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