This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-di-request-scope-lifecycle-fencing

FastAPI Dependency Injection Request-Scope Lifecycle Fencing

Enforces strict isolation between FastAPI request-scoped dependency lifecycles and asynchronous background execution. Passing request-bound yield dependencies, such as database sessions or transaction contexts, directly into BackgroundTasks or detached asyncio tasks causes race conditions, premature connection pool exhaustion, and catastrophic transaction deadlocks.

Prohibited Anti-Pattern: Leaking Request-Scoped Yield Dependencies into Detached BackgroundTasks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Dependency Injection Request-Scope Lifecycle Fencing - Enforces strict isolation between FastAPI request-scoped dependency lifecycles and asynchronous background execution. Passing request-bound yield dependencies, such as database sessions or transaction contexts, directly into BackgroundTasks or detached asyncio tasks causes race conditions, premature connection pool exhaustion, and catastrophic transaction deadlocks.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-di-request-scope-lifecycle-fencing"
---

# FastAPI Dependency Injection Request-Scope Lifecycle Fencing

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking Request-Scoped Yield Dependencies into Detached BackgroundTasks

## System Constraints
You are a Principal Backend Architect enforcing strict execution boundaries between FastAPI request-scoped dependencies and background task execution contexts. You must forbid passing request-bound yield fixtures (such as SQLAlchemy AsyncSession or transactional units of work) into BackgroundTasks or detached asyncio Coroutines. Require explicit session factories or dedicated worker queues to manage independent lifecycles for decoupled asynchronous operations.

## Strict Guidelines
- Engineers MUST NEVER pass a request-scoped dependency injected via `yield` (e.g., `AsyncSession`, `ClientSession`, `UnitOfWork`) as an argument to `BackgroundTasks.add_task` or `asyncio.create_task`.
- Engineers MUST ALWAYS instantiate a dedicated, independently scoped context manager or session factory inside background task workers to manage their own resource lifecycles.
- Background worker functions MUST accept scalar primary keys, immutable IDs, or serialized schemas rather than active ORM entities or live connection objects.
- FastAPI endpoint handlers MUST commit, rollback, or close request-bound transactions exclusively within the request-response lifecycle boundaries before returning the response payload.
- Yield-based dependency cleanup code MUST assume that all operations relying on yielded resources are completely terminated upon response dispatch.

## Bad vs Good Implementations
### Passing Request-Bound AsyncSession vs Isolated Context Factory in BackgroundTasks

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: FastAPI triggers dependency teardown immediately after the endpoint function returns. Passing `db` into `BackgroundTasks` races against dependency exit (`await session.close()`), throwing `InterfaceError`, operating on a closed transaction, or leaking checked-out connections back to the connection pool.
```python
from fastapi import FastAPI, Depends, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db, User

app = FastAPI()

async def send_welcome_and_audit(session: AsyncSession, user_id: int):
    # Anti-pattern: Using closed/returned session after HTTP response has been sent
    user = await session.get(User, user_id)
    user.notified = True
    await session.commit()

@app.post("/users/{user_id}/activate")
async def activate_user(
    user_id: int,
    background_tasks: BackgroundTasks,
    db: AsyncSession = Depends(get_db)
):
    user = await db.get(User, user_id)
    user.is_active = True
    await db.commit()
    # BUG: get_db cleans up at the end of the request, causing dangling pool locks or greenlet errors in background execution
    background_tasks.add_task(send_welcome_and_audit, db, user_id)
    return {"status": "activation_scheduled"}
```

#### Production Standard (Correct)
> **Standard**: The endpoint operates purely within its own request-scoped transaction boundary. The background task receives a stateless factory and scalar ID, acquiring and closing an independent connection via a context manager without racing against the request lifecycle.
```python
from fastapi import FastAPI, Depends, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from app.database import get_db, async_session_factory, User

app = FastAPI()

async def send_welcome_and_audit(session_maker: async_sessionmaker[AsyncSession], user_id: int):
    # Invariant: Background process manages its own independent lifecycle and transaction boundaries
    async with session_maker() as session:
        async with session.begin():
            user = await session.get(User, user_id)
            if user:
                user.notified = True

@app.post("/users/{user_id}/activate")
async def activate_user(
    user_id: int,
    background_tasks: BackgroundTasks,
    db: AsyncSession = Depends(get_db)
):
    user = await db.get(User, user_id)
    if not user:
        return {"status": "not_found"}
    user.is_active = True
    await db.commit()
    
    # Safe: Pass only the primitive ID and independent session factory, preserving request-scope fences
    background_tasks.add_task(send_welcome_and_audit, async_session_factory, user_id)
    return {"status": "activation_scheduled"}
```

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 Dependency Injection Request-Scope Lifecycle Fencing

FastAPI Dependency Injection Request-Scope Lifecycle Fencing defines an industrial-grade behavioral standard for backend engineering. Enforces strict isolation between FastAPI request-scoped dependency lifecycles and asynchronous background execution. Passing request-bound yield dependencies, such as database sessions or transaction contexts, directly into BackgroundTasks or detached asyncio tasks causes race conditions, premature connection pool exhaustion, and catastrophic transaction deadlocks. 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: Leaking Request-Scoped Yield Dependencies into Detached BackgroundTasks 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 DriftLeaking Request-Scoped Yield Dependencies into Detached BackgroundTasksCritical
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 NEVER pass a request-scoped dependency injected via `yield` (e.g., `AsyncSession`, `ClientSession`, `UnitOfWork`) as an argument to `BackgroundTasks.add_task` or `asyncio.create_task`.

Engineers MUST NEVER pass a request-scoped dependency injected via `yield` (e.g., `AsyncSession`, `ClientSession`, `UnitOfWork`) as an argument to `BackgroundTasks.add_task` or `asyncio.create_task`.

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 instantiate a dedicated, independently scoped context manager or session factory inside background task workers to manage their own resource lifecycles.

Engineers MUST ALWAYS instantiate a dedicated, independently scoped context manager or session factory inside background task workers to manage their own resource lifecycles.

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

Background worker functions MUST accept scalar primary keys, immutable IDs, or serialized schemas rather than active ORM entities or live connection objects.

Background worker functions MUST accept scalar primary keys, immutable IDs, or serialized schemas rather than active ORM entities or live connection objects.

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

FastAPI endpoint handlers MUST commit, rollback, or close request-bound transactions exclusively within the request-response lifecycle boundaries before returning the response payload.

FastAPI endpoint handlers MUST commit, rollback, or close request-bound transactions exclusively within the request-response lifecycle boundaries before returning the response payload.

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

Yield-based dependency cleanup code MUST assume that all operations relying on yielded resources are completely terminated upon response dispatch.

Yield-based dependency cleanup code MUST assume that all operations relying on yielded resources are completely terminated upon response dispatch.

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 Dependency Injection Request-Scope Lifecycle Fencing critical for AI coding assistants?

Enforces strict isolation between FastAPI request-scoped dependency lifecycles and asynchronous background execution. Passing request-bound yield dependencies, such as database sessions or transaction contexts, directly into BackgroundTasks or detached asyncio tasks causes race conditions, premature connection pool exhaustion, and catastrophic transaction deadlocks. 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 (Leaking Request-Scoped Yield Dependencies into Detached BackgroundTasks) 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