This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-python313-nogil-shared-state-invariant

FastAPI Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail

Enforces strict thread-safety and concurrency invariants in FastAPI applications deployed on Python 3.13 free-threaded (PEP 703) runtimes. Strictly eliminates unshielded mutable in-memory singletons and race conditions across OS thread pools and asynchronous event loops while maximizing true multi-core parallel execution.

Prohibited Anti-Pattern: Unprotected In-Memory Shared Mutable State Across Free-Threaded Worker Pools

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail - Enforces strict thread-safety and concurrency invariants in FastAPI applications deployed on Python 3.13 free-threaded (PEP 703) runtimes. Strictly eliminates unshielded mutable in-memory singletons and race conditions across OS thread pools and asynchronous event loops while maximizing true multi-core parallel execution.
globs: app/**/*.py, src/**/*.py, services/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-python313-nogil-shared-state-invariant"
---

# FastAPI Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unprotected In-Memory Shared Mutable State Across Free-Threaded Worker Pools

## System Constraints
You are a Principal Software Architect enforcing thread safety and race-free architecture in FastAPI running on Python 3.13 Free-Threaded (No-GIL, PEP 703) runtimes. In a free-threaded Python environment, multiple OS threads execute pure Python bytecode simultaneously across physical cores without global serialization. You must mandate immutable state sharing, lock-striped concurrency primitives, externalized state, or atomic synchronization constructs, strictly banning raw mutable global or module-level singletons.

## Strict Guidelines
- Engineers MUST NOT rely on implicit GIL-based atomicity guarantees for Python built-ins like dict, list, or set operations.
- Engineers MUST ALWAYS isolate shared mutable operational state into external persistence layers (Redis, PostgreSQL) or synchronize in-memory state using threading.Lock, threading.RLock, or concurrent lock-free primitives.
- Engineers MUST NOT mutate raw module-level dictionaries or class-level attributes within FastAPI route handlers, dependencies, or background tasks.
- Code SHOULD leverage immutable data structures (typing.NamedTuple, dataclasses with frozen=True, or Pydantic models with frozen=True) for objects shared across worker threads.
- Services executing CPU-bound workloads via concurrent.futures.ThreadPoolExecutor MUST guarantee that target callable arguments and closures are strictly decoupled or read-only.
- Components NEVER use asyncio.Lock to shield resources concurrently accessed across OS worker threads running outside the primary event loop thread.

## Bad vs Good Implementations
### Module-Level Shared Cache Mutation in Free-Threaded FastAPI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Python 3.13 free-threaded builds, multiple OS threads executing route handlers simultaneously will corrupt non-atomic dictionary updates, resulting in severe data races and lost mutations without the GIL serializing bytecodes.
```python
from fastapi import FastAPI

app = FastAPI()

# Anti-pattern: Unshielded mutable singleton; causes data race under Python 3.13 free-threading
METRICS_CACHE: dict[str, int] = {}

@app.post("/record/{metric_name}")
async def record_metric(metric_name: str) -> dict[str, int]:
    # Non-atomic read-modify-write causes lost updates under true parallelism
    current = METRICS_CACHE.get(metric_name, 0)
    METRICS_CACHE[metric_name] = current + 1
    return {"metric": metric_name, "count": METRICS_CACHE[metric_name]}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates shared state within a class utilizing an explicit OS-level threading.Lock to synchronize multi-threaded access across Python 3.13 native threads, guaranteeing atomic mutations and consistent memory visibility.
```python
from fastapi import FastAPI
from threading import Lock
from collections import defaultdict

app = FastAPI()

class SynchronizedMetricsRegistry:
    __slots__ = ("_lock", "_counters")

    def __init__(self) -> None:
        self._lock = Lock()
        self._counters: dict[str, int] = defaultdict(int)

    def increment(self, metric_name: str) -> int:
        with self._lock:
            self._counters[metric_name] += 1
            return self._counters[metric_name]

metrics_registry = SynchronizedMetricsRegistry()

@app.post("/record/{metric_name}")
async def record_metric(metric_name: str) -> dict[str, int]:
    updated_count = metrics_registry.increment(metric_name)
    return {"metric": metric_name, "count": updated_count}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail

FastAPI Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict thread-safety and concurrency invariants in FastAPI applications deployed on Python 3.13 free-threaded (PEP 703) runtimes. Strictly eliminates unshielded mutable in-memory singletons and race conditions across OS thread pools and asynchronous event loops while maximizing true multi-core parallel execution. 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: Unprotected In-Memory Shared Mutable State Across Free-Threaded Worker Pools 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 DriftUnprotected In-Memory Shared Mutable State Across Free-Threaded Worker PoolsCritical
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 implicit GIL-based atomicity guarantees for Python built-ins like dict, list, or set operations.

Engineers MUST NOT rely on implicit GIL-based atomicity guarantees for Python built-ins like dict, list, or set operations.

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 shared mutable operational state into external persistence layers (Redis, PostgreSQL) or synchronize in-memory state using threading.Lock, threading.RLock, or concurrent lock-free primitives.

Engineers MUST ALWAYS isolate shared mutable operational state into external persistence layers (Redis, PostgreSQL) or synchronize in-memory state using threading.Lock, threading.RLock, or concurrent lock-free primitives.

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 mutate raw module-level dictionaries or class-level attributes within FastAPI route handlers, dependencies, or background tasks.

Engineers MUST NOT mutate raw module-level dictionaries or class-level attributes within FastAPI route handlers, dependencies, or background 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.
4

Code SHOULD leverage immutable data structures (typing.NamedTuple, dataclasses with frozen=True, or Pydantic models with frozen=True) for objects shared across worker threads.

Code SHOULD leverage immutable data structures (typing.NamedTuple, dataclasses with frozen=True, or Pydantic models with frozen=True) for objects shared across worker 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.
5

Services executing CPU-bound workloads via concurrent.futures.ThreadPoolExecutor MUST guarantee that target callable arguments and closures are strictly decoupled or read-only.

Services executing CPU-bound workloads via concurrent.futures.ThreadPoolExecutor MUST guarantee that target callable arguments and closures are strictly decoupled or read-only.

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 use asyncio.Lock to shield resources concurrently accessed across OS worker threads running outside the primary event loop thread.

Components NEVER use asyncio.Lock to shield resources concurrently accessed across OS worker threads running outside the primary event loop thread.

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 Python 3.13 Free-Threaded (No-GIL) Shared-State Thread-Safety Guardrail critical for AI coding assistants?

Enforces strict thread-safety and concurrency invariants in FastAPI applications deployed on Python 3.13 free-threaded (PEP 703) runtimes. Strictly eliminates unshielded mutable in-memory singletons and race conditions across OS thread pools and asynchronous event loops while maximizing true multi-core parallel execution. 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 (Unprotected In-Memory Shared Mutable State Across Free-Threaded Worker Pools) 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