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

FastAPI Free-Threaded (Python 3.13 nogil) Shared-Memory Concurrency Standard

Mandates explicit thread-safe synchronization primitives for shared in-process state in Python 3.13 free-threaded (PEP 703 / nogil) FastAPI runtimes. In environments without the Global Interpreter Lock, compound operations on native collections produce race conditions, lost updates, and memory-inconsistency bugs across parallel execution threads.

Prohibited Anti-Pattern: Unsynchronized in-memory state manipulation assuming legacy GIL serialization in Python 3.13t

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Free-Threaded (Python 3.13 nogil) Shared-Memory Concurrency Standard - Mandates explicit thread-safe synchronization primitives for shared in-process state in Python 3.13 free-threaded (PEP 703 / nogil) FastAPI runtimes. In environments without the Global Interpreter Lock, compound operations on native collections produce race conditions, lost updates, and memory-inconsistency bugs across parallel execution threads.
globs: app/**/*.py, src/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-nogil-concurrency-guardrail"
---

# FastAPI Free-Threaded (Python 3.13 nogil) Shared-Memory Concurrency Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized in-memory state manipulation assuming legacy GIL serialization in Python 3.13t

## System Constraints
You are a Principal Backend Architect enforcing strict thread safety and synchronization standards for FastAPI services running on Python 3.13 Free-Threaded (nogil) runtimes. Mandate explicit synchronization primitives, eliminate unsafe shared in-process mutable collections, and prevent deadlocks across true OS-level parallel workers.

## Strict Guidelines
- Engineers MUST ALWAYS protect shared in-process mutable state (caches, token buckets, singletons) using explicit OS-level synchronization primitives (`threading.Lock`, `threading.RLock`) or lock-free concurrent structures.
- Engineers MUST NOT rely on implicit GIL atomicity for compound operations (e.g., check-then-act `if k not in d: d[k] = v`, in-place counter increments `count += 1`, or `dict.pop()`).
- Engineers MUST NOT use `asyncio.Lock` to protect shared state accessible by both synchronous (`def`) endpoints executed in threadpools and asynchronous (`async def`) coroutines.
- Code SHOULD enforce minimal critical section scopes by acquiring locks strictly around state reads/writes, never holding locks across I/O or downstream HTTP/database calls.
- Services MUST prefer external distributed state (e.g., Redis, Valkey, KeyDB) or read-only/copy-on-write immutable data structures over highly contested in-process shared state.

## Bad vs Good Implementations
### Unsynchronized Global Cache vs. Thread-Safe In-Process Cache with Lock Discipline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Python 3.13 free-threaded (nogil), true parallel OS threads execute opcode sequences concurrently. Compound read-modify-write patterns and dictionary mutation without synchronization result in lost updates, torn reads, and nondeterministic state corruption.
```python
from fastapi import FastAPI

app = FastAPI()
# GLOBAL STATE: Subject to race conditions under Python 3.13 free-threaded (nogil)
_cache: dict[str, int] = {}

@app.get("/counter/{key}")
def increment_counter(key: str) -> dict[str, int]:
    # ANTI-PATTERN: Read-modify-write is not atomic without the GIL
    # Multiple OS threads executing this concurrently will drop updates
    current = _cache.get(key, 0)
    current += 1
    _cache[key] = current
    return {"key": key, "count": _cache[key]}
```

#### Production Standard (Correct)
> **Standard**: Wraps shared mutable state inside a class guarded by `threading.Lock`. The critical section is tightly scoped to the minimal memory modification, guaranteeing linearizable operations across parallel threads in Python 3.13 nogil runtimes.
```python
from threading import Lock
from fastapi import FastAPI

app = FastAPI()

class ThreadSafeCounterCache:
    def __init__(self) -> None:
        self._lock = Lock()
        self._data: dict[str, int] = {}

    def increment(self, key: str) -> int:
        # CRITICAL SECTION: Explicit OS-level mutex guarantees mutual exclusion
        with self._lock:
            val = self._data.get(key, 0) + 1
            self._data[key] = val
            return val

    def get(self, key: str) -> int:
        with self._lock:
            return self._data.get(key, 0)

counter_cache = ThreadSafeCounterCache()

@app.get("/counter/{key}")
def increment_counter(key: str) -> dict[str, int]:
    count = counter_cache.increment(key)
    return {"key": key, "count": 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 (Python 3.13 nogil) Shared-Memory Concurrency Standard

FastAPI Free-Threaded (Python 3.13 nogil) Shared-Memory Concurrency Standard defines an industrial-grade behavioral standard for backend engineering. Mandates explicit thread-safe synchronization primitives for shared in-process state in Python 3.13 free-threaded (PEP 703 / nogil) FastAPI runtimes. In environments without the Global Interpreter Lock, compound operations on native collections produce race conditions, lost updates, and memory-inconsistency bugs across parallel execution threads. 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 in-memory state manipulation assuming legacy GIL serialization in Python 3.13t 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 in-memory state manipulation assuming legacy GIL serialization in Python 3.13tCritical
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 protect shared in-process mutable state (caches, token buckets, singletons) using explicit OS-level synchronization primitives (`threading.Lock`, `threading.RLock`) or lock-free concurrent structures.

Engineers MUST ALWAYS protect shared in-process mutable state (caches, token buckets, singletons) using explicit OS-level synchronization primitives (`threading.Lock`, `threading.RLock`) or lock-free concurrent 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.
2

Engineers MUST NOT rely on implicit GIL atomicity for compound operations (e.g., check-then-act `if k not in d

Engineers MUST NOT rely on implicit GIL atomicity for compound operations (e.g., check-then-act `if k not in d: d[k] = v`, in-place counter increments `count += 1`, or `dict.pop()`).

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 use `asyncio.Lock` to protect shared state accessible by both synchronous (`def`) endpoints executed in threadpools and asynchronous (`async def`) coroutines.

Engineers MUST NOT use `asyncio.Lock` to protect shared state accessible by both synchronous (`def`) endpoints executed in threadpools and asynchronous (`async def`) coroutines.

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 enforce minimal critical section scopes by acquiring locks strictly around state reads/writes, never holding locks across I/O or downstream HTTP/database calls.

Code SHOULD enforce minimal critical section scopes by acquiring locks strictly around state reads/writes, never holding locks across I/O or downstream HTTP/database calls.

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 MUST prefer external distributed state (e.g., Redis, Valkey, KeyDB) or read-only/copy-on-write immutable data structures over highly contested in-process shared state.

Services MUST prefer external distributed state (e.g., Redis, Valkey, KeyDB) or read-only/copy-on-write immutable data structures over highly contested in-process shared 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.
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.13 nogil) Shared-Memory Concurrency Standard critical for AI coding assistants?

Mandates explicit thread-safe synchronization primitives for shared in-process state in Python 3.13 free-threaded (PEP 703 / nogil) FastAPI runtimes. In environments without the Global Interpreter Lock, compound operations on native collections produce race conditions, lost updates, and memory-inconsistency bugs across parallel execution threads. 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 in-memory state manipulation assuming legacy GIL serialization in Python 3.13t) 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