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

Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant

Enforces strict thread-safe access patterns, fine-grained locking, or externalized state management for Python 3.13 free-threaded (PEP 703) runtimes. Without the Global Interpreter Lock (GIL), in-memory mutations on built-in collections across concurrent worker threads cause non-deterministic race conditions, torn reads, and memory corruption in ASGI applications. All shared application state must use synchronized primitives, atomics, or immutable data structures.

Prohibited Anti-Pattern: Unsynchronized In-Memory State Mutation Across Concurrent ASGI Worker Threads in Free-Threaded Python

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant - Enforces strict thread-safe access patterns, fine-grained locking, or externalized state management for Python 3.13 free-threaded (PEP 703) runtimes. Without the Global Interpreter Lock (GIL), in-memory mutations on built-in collections across concurrent worker threads cause non-deterministic race conditions, torn reads, and memory corruption in ASGI applications. All shared application state must use synchronized primitives, atomics, or immutable data structures.
globs: app/**/*.py, src/**/*.py, services/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/python-313-freethreaded-fastapi-state-guardrail"
---

# Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized In-Memory State Mutation Across Concurrent ASGI Worker Threads in Free-Threaded Python

## System Constraints
You are a Principal Software Architect enforcing thread safety and memory model invariants for FastAPI services running on Python 3.13 free-threaded mode (PEP 703, GIL disabled). You must prohibit reliance on legacy GIL-guaranteed atomicity (e.g., in-place dict/list operations, non-atomic counter increments). Mandate explicit synchronization primitives, lock-free patterns, or external state distribution for all shared ASGI state.

## Strict Guidelines
- Engineers MUST ALWAYS protect shared in-memory mutable state (`app.state`, module-level containers, singletons) with explicit synchronization primitives such as `threading.Lock`, `threading.RLock`, or read-write locks.
- Engineers MUST NOT rely on historical CPython GIL atomicity assumptions (e.g., assuming `dict[key] = value`, `dict.setdefault()`, or `list.append()` are safe under high-concurrency free-threaded execution).
- Services MUST prefer externalized state (e.g., Redis, Dragonfly, PostgreSQL) or immutability (frozen dataclasses, Pyrsistent) over process-local mutable shared memory in multi-threaded ASGI environments.
- Engineers MUST use atomic primitives or synchronizers for metric tracking and counters rather than standard `+=` operator manipulations.
- FastAPI dependency-injected singletons MUST be thread-safe for re-entrant access by multiple OS threads executing concurrent async/sync route handlers simultaneously.
- Components NEVER store request-scoped context in module-level global variables; all request-bound context MUST use `contextvars.ContextVar`.

## Bad vs Good Implementations
### Shared In-Memory State: Unsynchronized Dict vs. Lock-Synchronized State Container

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Python 3.13 free-threaded builds, bytecodes are executed concurrently by multiple OS threads without the GIL. Non-atomic reads and writes to `metrics_cache` cause race conditions, lost updates, and corrupted internal state under concurrent load.
```python
from fastapi import FastAPI

app = FastAPI()
# ANTI-PATTERN: Direct global mutable state mutation without the GIL.
# In Python 3.13t (free-threaded), concurrent access to this dict
# produces race conditions, torn reads, or unexpected key drops.
metrics_cache: dict[str, int] = {}

@app.post("/events/{event_type}")
async def record_event(event_type: str) -> dict[str, int]:
    current_count = metrics_cache.get(event_type, 0)
    metrics_cache[event_type] = current_count + 1
    return {"event": event_type, "count": metrics_cache[event_type]}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates shared mutable state within a structured class guarded by an explicit `threading.Lock`. Mutations and reads are serialized atomically, preserving consistency across all worker threads in a GIL-free runtime.
```python
from fastapi import FastAPI
from threading import Lock
from dataclasses import dataclass, field

@dataclass
class ThreadSafeMetrics:
    _lock: Lock = field(default_factory=Lock)
    _counts: dict[str, int] = field(default_factory=dict)

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

app = FastAPI()
state_metrics = ThreadSafeMetrics()

@app.post("/events/{event_type}")
async def record_event(event_type: str) -> dict[str, int]:
    count = state_metrics.increment(event_type)
    return {"event": event_type, "count": 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: Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant

Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict thread-safe access patterns, fine-grained locking, or externalized state management for Python 3.13 free-threaded (PEP 703) runtimes. Without the Global Interpreter Lock (GIL), in-memory mutations on built-in collections across concurrent worker threads cause non-deterministic race conditions, torn reads, and memory corruption in ASGI applications. All shared application state must use synchronized primitives, atomics, or immutable data structures. 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 Mutation Across Concurrent ASGI Worker Threads 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 DriftUnsynchronized In-Memory State Mutation Across Concurrent ASGI Worker Threads 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 protect shared in-memory mutable state (`app.state`, module-level containers, singletons) with explicit synchronization primitives such as `threading.Lock`, `threading.RLock`, or read-write locks.

Engineers MUST ALWAYS protect shared in-memory mutable state (`app.state`, module-level containers, singletons) with explicit synchronization primitives such as `threading.Lock`, `threading.RLock`, or read-write locks.

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 historical CPython GIL atomicity assumptions (e.g., assuming `dict[key] = value`, `dict.setdefault()`, or `list.append()` are safe under high-concurrency free-threaded execution).

Engineers MUST NOT rely on historical CPython GIL atomicity assumptions (e.g., assuming `dict[key] = value`, `dict.setdefault()`, or `list.append()` are safe under high-concurrency free-threaded execution).

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 prefer externalized state (e.g., Redis, Dragonfly, PostgreSQL) or immutability (frozen dataclasses, Pyrsistent) over process-local mutable shared memory in multi-threaded ASGI environments.

Services MUST prefer externalized state (e.g., Redis, Dragonfly, PostgreSQL) or immutability (frozen dataclasses, Pyrsistent) over process-local mutable shared memory in multi-threaded ASGI environments.

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 atomic primitives or synchronizers for metric tracking and counters rather than standard `+=` operator manipulations.

Engineers MUST use atomic primitives or synchronizers for metric tracking and counters rather than standard `+=` operator manipulations.

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

FastAPI dependency-injected singletons MUST be thread-safe for re-entrant access by multiple OS threads executing concurrent async/sync route handlers simultaneously.

FastAPI dependency-injected singletons MUST be thread-safe for re-entrant access by multiple OS threads executing concurrent async/sync route handlers simultaneously.

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 store request-scoped context in module-level global variables

Components NEVER store request-scoped context in module-level global variables; all request-bound context MUST use `contextvars.ContextVar`.

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 Python 3.13 Free-Threaded FastAPI Shared State & Concurrency Invariant critical for AI coding assistants?

Enforces strict thread-safe access patterns, fine-grained locking, or externalized state management for Python 3.13 free-threaded (PEP 703) runtimes. Without the Global Interpreter Lock (GIL), in-memory mutations on built-in collections across concurrent worker threads cause non-deterministic race conditions, torn reads, and memory corruption in ASGI applications. All shared application state must use synchronized primitives, atomics, or immutable data structures. 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 Mutation Across Concurrent ASGI Worker Threads 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

Python