This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-python-313t-free-threaded-thread-safety

FastAPI Free-Threaded Python 3.13t Thread-Safety & Memory Invariant Standard

Enforces strict thread-safety invariants for FastAPI applications running on free-threaded Python 3.13t (no-GIL) runtimes. Prohibits unsynchronized mutable module-level state and mandates reentrant locks across async offloads invoking non-thread-safe C-extensions to prevent memory corruption and segmentation faults.

Prohibited Anti-Pattern: Unsynchronized Global State Mutation and Unlocked C-Extension Invocations Under Free-Threaded (PEP 703) Python

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Free-Threaded Python 3.13t Thread-Safety & Memory Invariant Standard - Enforces strict thread-safety invariants for FastAPI applications running on free-threaded Python 3.13t (no-GIL) runtimes. Prohibits unsynchronized mutable module-level state and mandates reentrant locks across async offloads invoking non-thread-safe C-extensions to prevent memory corruption and segmentation faults.
globs: **/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-python-313t-free-threaded-thread-safety"
---

# FastAPI Free-Threaded Python 3.13t Thread-Safety & Memory Invariant Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Global State Mutation and Unlocked C-Extension Invocations Under Free-Threaded (PEP 703) Python

## System Constraints
You are a Principal Software Architect enforcing thread safety in FastAPI microservices running under free-threaded Python 3.13t (PEP 703). With the Global Interpreter Lock (GIL) disabled, bytecodes and native structures execute across true multi-core OS threads simultaneously. You must ensure zero naked mutable global variables, mandate explicit synchronization primitives for shared runtime state, and enforce reentrant locking whenever asynchronous tasks delegate to non-thread-safe native C-extensions.

## Strict Guidelines
- Engineers MUST NOT declare or mutate unsynchronized module-level collections (e.g., dict, list, set) in Python 3.13t applications.
- Engineers MUST ALWAYS wrap shared state accesses in fine-grained synchronization primitives (e.g., `threading.Lock`, `threading.RLock`, or `concurrent.futures.locks`) or use atomic data stores (e.g., Redis).
- Services MUST serialize calls to legacy C-extensions or external C-libraries dispatched through `anyio.to_thread.run_sync` or `asyncio.to_thread` using a module-level `threading.RLock`.
- Engineers MUST use `threading.local()` or `contextvars.ContextVar` for request-scoped state instead of module-level tracking structures.
- Code SHOULD verify thread-safety flags on third-party C-extensions via `sys._is_gil_enabled()` checks during startup verification routines.

## Bad vs Good Implementations
### Module-Level Mutable State and Async C-Extension Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Python 3.13t without the GIL, concurrent OS worker threads concurrently mutate `METRICS_CACHE` without synchronization, corrupting dict internals. Offloading non-thread-safe C-extension calls via an executor allows simultaneous execution inside unshielded C functions, causing native memory corruption and segmentation faults.
```python
import asyncio
from fastapi import FastAPI
import legacy_c_crypto  # Hypothetical legacy C-extension lacking internal mutexes

app = FastAPI()

# ANTI-PATTERN: Unsynchronized module-level state causes race conditions and memory corruption in Python 3.13t
METRICS_CACHE: dict[str, int] = {}

@app.post("/encrypt")
async def encrypt_payload(data: str):
    METRICS_CACHE["active_requests"] = METRICS_CACHE.get("active_requests", 0) + 1
    
    # ANTI-PATTERN: Free-threaded runtime executes concurrent C-extension invocations without locks,
    # causing internal C buffer corruption or SIGSEGV.
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, legacy_c_crypto.process_buffer, data)
    
    METRICS_CACHE["active_requests"] -= 1
    return {"status": "ok", "result": result}
```

#### Production Standard (Correct)
> **Standard**: All mutable module-level state accesses are enclosed in standard synchronization blocks (`_METRICS_LOCK`), and legacy native C-extension invocations are guarded by `_C_EXTENSION_LOCK`, ensuring memory safety across OS threads in free-threaded runtimes.
```python
import asyncio
import threading
from fastapi import FastAPI
import legacy_c_crypto

app = FastAPI()

# PRODUCTION FIX: Protect shared memory state with threading locks and serialize native C-calls
_METRICS_LOCK = threading.Lock()
_METRICS_CACHE: dict[str, int] = {"active_requests": 0}
_C_EXTENSION_LOCK = threading.RLock()

def _safe_c_call(data: str) -> str:
    with _C_EXTENSION_LOCK:
        return legacy_c_crypto.process_buffer(data)

@app.post("/encrypt")
async def encrypt_payload(data: str):
    with _METRICS_LOCK:
        _METRICS_CACHE["active_requests"] += 1
        
    try:
        # Synchronized execution through dedicated thread pool with reentrant locking
        result = await asyncio.to_thread(_safe_c_call, data)
        return {"status": "ok", "result": result}
    finally:
        with _METRICS_LOCK:
            _METRICS_CACHE["active_requests"] -= 1
```

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 Python 3.13t Thread-Safety & Memory Invariant Standard

FastAPI Free-Threaded Python 3.13t Thread-Safety & Memory Invariant Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict thread-safety invariants for FastAPI applications running on free-threaded Python 3.13t (no-GIL) runtimes. Prohibits unsynchronized mutable module-level state and mandates reentrant locks across async offloads invoking non-thread-safe C-extensions to prevent memory corruption and segmentation faults. 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 Global State Mutation and Unlocked C-Extension Invocations Under Free-Threaded (PEP 703) Python 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 Global State Mutation and Unlocked C-Extension Invocations Under Free-Threaded (PEP 703) PythonCritical
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 declare or mutate unsynchronized module-level collections (e.g., dict, list, set) in Python 3.13t applications.

Engineers MUST NOT declare or mutate unsynchronized module-level collections (e.g., dict, list, set) in Python 3.13t applications.

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 wrap shared state accesses in fine-grained synchronization primitives (e.g., `threading.Lock`, `threading.RLock`, or `concurrent.futures.locks`) or use atomic data stores (e.g., Redis).

Engineers MUST ALWAYS wrap shared state accesses in fine-grained synchronization primitives (e.g., `threading.Lock`, `threading.RLock`, or `concurrent.futures.locks`) or use atomic data stores (e.g., Redis).

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 serialize calls to legacy C-extensions or external C-libraries dispatched through `anyio.to_thread.run_sync` or `asyncio.to_thread` using a module-level `threading.RLock`.

Services MUST serialize calls to legacy C-extensions or external C-libraries dispatched through `anyio.to_thread.run_sync` or `asyncio.to_thread` using a module-level `threading.RLock`.

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 `threading.local()` or `contextvars.ContextVar` for request-scoped state instead of module-level tracking structures.

Engineers MUST use `threading.local()` or `contextvars.ContextVar` for request-scoped state instead of module-level tracking structures.

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 verify thread-safety flags on third-party C-extensions via `sys._is_gil_enabled()` checks during startup verification routines.

Code SHOULD verify thread-safety flags on third-party C-extensions via `sys._is_gil_enabled()` checks during startup verification routines.

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 Python 3.13t Thread-Safety & Memory Invariant Standard critical for AI coding assistants?

Enforces strict thread-safety invariants for FastAPI applications running on free-threaded Python 3.13t (no-GIL) runtimes. Prohibits unsynchronized mutable module-level state and mandates reentrant locks across async offloads invoking non-thread-safe C-extensions to prevent memory corruption and segmentation faults. 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 Global State Mutation and Unlocked C-Extension Invocations Under Free-Threaded (PEP 703) Python) 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