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

FastAPI Python 3.13 Free-Threaded (No-GIL) State and Pool Invariant

Enforces strict thread-safe encapsulation of mutable module-level state and database connection pools under Python 3.13 free-threaded execution (PEP 703). Eliminates data races, torn reads/writes, and multiple-instantiation bugs caused by the absence of the Global Interpreter Lock.

Prohibited Anti-Pattern: Unprotected Module-Level State and Unsynchronized Lazy Pool Instantiation in Free-Threaded Python

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Python 3.13 Free-Threaded (No-GIL) State and Pool Invariant - Enforces strict thread-safe encapsulation of mutable module-level state and database connection pools under Python 3.13 free-threaded execution (PEP 703). Eliminates data races, torn reads/writes, and multiple-instantiation bugs caused by the absence of the Global Interpreter Lock.
globs: app/**/*.py, src/**/*.py, **/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-python313-freethreaded-concurrency-boundary"
---

# FastAPI Python 3.13 Free-Threaded (No-GIL) State and Pool Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unprotected Module-Level State and Unsynchronized Lazy Pool Instantiation in Free-Threaded Python

## System Constraints
You are a Principal Engineer enforcing strict concurrency boundaries for FastAPI applications executing on Python 3.13 free-threaded runtimes (no-GIL). You must disallow all unprotected module-level mutable variables, naive lazy singletons, and implicit atomic dictionary operations. All shared resources, database connection pools, and caches must be explicitly synchronized or bound strictly to the FastAPI lifespan lifecycle.

## Strict Guidelines
- Engineers MUST ALWAYS initialize database engines, connection pools, and shared clients inside the FastAPI lifespan context manager and attach them to `app.state`.
- Engineers MUST NOT rely on module-level lazy singletons (e.g., `if _engine is None: _engine = create_engine(...)`) without explicit `threading.Lock` double-checked synchronization.
- Engineers MUST NOT use standard mutable types (`dict`, `list`, `set`) as shared in-memory state across requests without explicit mutual exclusion locks (`threading.Lock` or `threading.RLock`).
- Services MUST NEVER assume Python bytecode execution guarantees atomicity for composite operations (e.g., `dict[k] = dict.get(k, 0) + 1` or `setdefault`) in Python 3.13 free-threaded builds.
- Code SHOULD leverage `contextvars.ContextVar` for request-scoped isolation and immutable data structures (such as frozen dataclasses) for read-heavy cross-thread configuration.

## Bad vs Good Implementations
### Module-Level Lazy Database Engine vs Lifespan app.state Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Python 3.13 without the GIL, concurrent threads entering `get_engine` concurrently evaluate `_engine is None` as true, instantiating redundant connection pools and leaking sockets. In addition, updating `_cache` without synchronization leads to lost updates and internal dictionary corruption.
```python
from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine

# Anti-pattern: Global mutable reference with lazy initialization
_engine: AsyncEngine | None = None
_cache: dict[str, int] = {}  # Anti-pattern: Unsynchronized module state

async def get_engine() -> AsyncEngine:
    global _engine
    if _engine is None:
        # Race condition under Python 3.13 free-threading: multiple threads can enter and leak pools
        _engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db", pool_size=20)
    return _engine

app = FastAPI()

@app.get("/metrics")
async def increment_metric(key: str):
    # Data race: non-atomic increment under true OS-thread concurrency
    _cache[key] = _cache.get(key, 0) + 1
    return {"count": _cache[key]}
```

#### Production Standard (Correct)
> **Standard**: Database resources are deterministically created during application startup and cleanly closed at shutdown via `lifespan`, preventing connection pool thrashing. Shared state operations are isolated within a dedicated class guarded by an explicit `threading.Lock`, ensuring thread safety in Python 3.13 free-threaded mode.
```python
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
import threading
from fastapi import FastAPI, Request
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine

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

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

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # Invariant: Centralized, deterministic allocation inside the lifespan boundary
    engine: AsyncEngine = create_async_engine(
        "postgresql+asyncpg://user:pass@localhost/db",
        pool_size=20,
        max_overflow=10
    )
    app.state.engine = engine
    app.state.metrics = ThreadSafeMetrics()
    try:
        yield
    finally:
        await engine.dispose()

app = FastAPI(lifespan=lifespan)

@app.get("/metrics")
async def increment_metric(request: Request, key: str) -> dict[str, int]:
    metrics: ThreadSafeMetrics = request.app.state.metrics
    new_count = metrics.increment(key)
    return {"count": new_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) State and Pool Invariant

FastAPI Python 3.13 Free-Threaded (No-GIL) State and Pool Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict thread-safe encapsulation of mutable module-level state and database connection pools under Python 3.13 free-threaded execution (PEP 703). Eliminates data races, torn reads/writes, and multiple-instantiation bugs caused by the absence of the Global Interpreter Lock. 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 Module-Level State and Unsynchronized Lazy Pool Instantiation in Free-Threaded 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 DriftUnprotected Module-Level State and Unsynchronized Lazy Pool Instantiation in Free-Threaded 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 ALWAYS initialize database engines, connection pools, and shared clients inside the FastAPI lifespan context manager and attach them to `app.state`.

Engineers MUST ALWAYS initialize database engines, connection pools, and shared clients inside the FastAPI lifespan context manager and attach them to `app.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.
2

Engineers MUST NOT rely on module-level lazy singletons (e.g., `if _engine is None

Engineers MUST NOT rely on module-level lazy singletons (e.g., `if _engine is None: _engine = create_engine(...)`) without explicit `threading.Lock` double-checked 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.
3

Engineers MUST NOT use standard mutable types (`dict`, `list`, `set`) as shared in-memory state across requests without explicit mutual exclusion locks (`threading.Lock` or `threading.RLock`).

Engineers MUST NOT use standard mutable types (`dict`, `list`, `set`) as shared in-memory state across requests without explicit mutual exclusion locks (`threading.Lock` or `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

Services MUST NEVER assume Python bytecode execution guarantees atomicity for composite operations (e.g., `dict[k] = dict.get(k, 0) + 1` or `setdefault`) in Python 3.13 free-threaded builds.

Services MUST NEVER assume Python bytecode execution guarantees atomicity for composite operations (e.g., `dict[k] = dict.get(k, 0) + 1` or `setdefault`) in Python 3.13 free-threaded builds.

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 leverage `contextvars.ContextVar` for request-scoped isolation and immutable data structures (such as frozen dataclasses) for read-heavy cross-thread configuration.

Code SHOULD leverage `contextvars.ContextVar` for request-scoped isolation and immutable data structures (such as frozen dataclasses) for read-heavy cross-thread configuration.

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) State and Pool Invariant critical for AI coding assistants?

Enforces strict thread-safe encapsulation of mutable module-level state and database connection pools under Python 3.13 free-threaded execution (PEP 703). Eliminates data races, torn reads/writes, and multiple-instantiation bugs caused by the absence of the Global Interpreter Lock. 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 Module-Level State and Unsynchronized Lazy Pool Instantiation in Free-Threaded 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