USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksBackend Book
HomeBackend BookFastAPI
PreviousRequest, Response, and OpenAPI ContractsNextErrors, Middleware, and Request Context
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

13 sections

Progress0%
1 / 13

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Dependency Injection and Application Lifespan

FastAPI dependencies construct request-scoped values and enforce reusable boundary rules; lifespan owns resources shared for the application process. Good dependency design makes identity, authorization, database sessions, gateways, and cleanup explicit. It does not hide business logic in decorators or create a service locator that can return anything from anywhere.

What will you be able to do?

  • distinguish application-, request-, and operation-scoped resources;
  • yield dependencies that always clean up;
  • compose identity and service dependencies;
  • override dependencies in deterministic tests.

How should ownership look?

python
from collections.abc import AsyncIterator from contextlib import asynccontextmanager from fastapi import Depends, FastAPI, Request from httpx import AsyncClient @asynccontextmanager async def lifespan(app: FastAPI): app.state.model_http = AsyncClient(timeout=20.0) try: yield finally: await app.state.model_http.aclose() app = FastAPI(lifespan=lifespan) def get_model_http(request: Request) -> AsyncClient: return request.app.state.model_http async def get_session() -> AsyncIterator["AsyncSession"]: async with session_factory() as session: try: yield session finally: await session.close()

The HTTP connection pool belongs to the process lifespan. A database session belongs to one request or unit of work. The repository and application service can be composed from the session dependency.

Where should authorization happen?

Authentication dependencies can establish a trusted principal. A reusable dependency may reject a missing organization membership. Resource-specific authorization still belongs near the use case because it needs both the principal and the resource. Avoid trusting organization_id from a header without binding it to verified membership.

How do tests replace infrastructure?

python
def override_ticket_service() -> FakeTicketService: return FakeTicketService() app.dependency_overrides[get_ticket_service] = override_ticket_service try: response = client.get("/v1/tickets/t_1") finally: app.dependency_overrides.clear()

Use fixtures so overrides cannot leak between tests.

Why does this matter in AI-native systems?

One process-level provider client can reuse connections, while every call receives request-scoped identity, tenant, budget, trace, and cancellation context. Never store the current user in a global provider client. Tool execution dependencies must derive authority from trusted server context, not model arguments.

Common mistakes

  • Creating a new HTTP client for every model call wastes connections.
  • Sharing one database session across requests creates concurrency corruption.
  • Performing network calls during module import makes startup unobservable and tests brittle.
  • Caching a dependency containing user state leaks identities across requests.
  • Business rules spread across dependency functions become difficult to reuse outside HTTP.

AI Pair-Programmer Prompt

text
Map every resource in this FastAPI application to process, request, transaction, or operation scope. Identify who creates and closes it, whether it contains user or tenant state, how tests replace it, and what happens during cancellation or startup failure. Flag global mutable state and hidden service locators.

Exercise

Create a ticket-service dependency backed by a fake repository. Override it for a test and prove cleanup occurs when the route raises.

Acceptance criteria: repeated tests do not share records, overrides are cleared, and cleanup evidence appears on both success and failure.

Knowledge check

  1. Which scope owns a database session?
  2. Why reuse a provider HTTP client?
  3. Can a model-provided tenant ID establish authority?

Answers

  1. A request or explicit unit of work.
  2. To reuse connection pools and centralize timeouts while keeping request state separate.
  3. No; authority comes from authenticated server context and verified membership.

Completion checklist

  • Every resource has an owner and cleanup path.
  • Tests override ports without infrastructure.
  • No global value contains current-user state.

Primary references

  • FastAPI dependencies
  • FastAPI lifespan