What are FastAPI and Litestar, and how does each request lifecycle work?

FastAPI is a thin layer on top of Starlette. The application object subclasses Starlette's, so routing, the middleware stack, request and response classes, and the test client all come from Starlette. FastAPI adds dependency injection driven by function signatures, Pydantic-based validation and serialization, and automatic OpenAPI generation.

A FastAPI request follows this path:

  1. The ASGI server (Uvicorn, Hypercorn, Granian) passes the connection to the app.
  2. Starlette middleware wraps the call.
  3. The router matches a path to a route.
  4. FastAPI resolves the dependency tree for that route, caching each dependency once per request.
  5. Pydantic validates path, query, header and body parameters.
  6. The handler runs.
  7. If a response model is declared, Pydantic validates and serializes the return value before it is encoded to JSON.

Litestar has its own ASGI core and is not built on Starlette. Its request path covers the same stages: server, middleware, router, dependency resolution, parameter parsing, handler, serialization. The defaults are different, though. msgspec handles parsing and encoding natively. Pydantic models, dataclasses and attrs classes go through a pluggable DTO and serialization layer. Configuration such as dependencies, guards and middleware can be set at the app, router, controller or handler level, and the more specific level overrides the broader one.

Starlette compatibility has a direct practical effect. Any Starlette middleware or Starlette-oriented library plugs into FastAPI without changes. Litestar cannot use Starlette's request or response objects, so it needs its own equivalents. Its only shared ground with that ecosystem is generic ASGI middleware, which works with any ASGI application.

       FastAPI (on Starlette)                 Litestar (own ASGI core)
+----------------------------------+    +----------------------------------+
| ASGI server                      |    | ASGI server                      |
| (Uvicorn, Hypercorn, Granian)    |    | (Uvicorn, Hypercorn, Granian)    |
+----------------v-----------------+    +----------------v-----------------+
| Starlette middleware stack       |    | Litestar middleware              |
| (Starlette or generic ASGI)      |    | (own or generic ASGI only)       |
+----------------v-----------------+    +----------------v-----------------+
| Starlette router                 |    | Litestar router (own ASGI core)  |
+----------------v-----------------+    +----------------v-----------------+
| FastAPI DI from signatures,      |    | Layered DI/guards/middleware:    |
| each dep cached once/request     |    | app>router>controller>handler    |
+----------------v-----------------+    +----------------v-----------------+
| Pydantic validates path, query,  |    | msgspec parses params + body;    |
| headers, body                    |    | Pydantic/dataclass/attrs: DTO    |
+----------------v-----------------+    +----------------v-----------------+
| Handler                          |    | Handler                          |
+----------------v-----------------+    +----------------v-----------------+
| response_model: Pydantic         |    | msgspec encodes natively;        |
| validates + serializes -> JSON   |    | other types via DTO layer        |
+----------------------------------+    +----------------------------------+

+--------------------------------------------------------------------------+
| Starlette middleware/tooling -> plugs into FastAPI unchanged             |
| Generic ASGI middleware      -> works with FastAPI and Litestar          |
| Starlette Request/Response   -> not usable; Litestar has its own         |
+--------------------------------------------------------------------------+

Request lifecycle in FastAPI (Starlette core, Pydantic validation) and Litestar (own ASGI core, native msgspec with a DTO layer for other model types), and where Starlette compatibility applies.

Where does ASGI performance actually come from?

A request's latency splits into four parts. Framework overhead covers routing, middleware and dependency resolution. Validation and serialization covers parsing the request body into typed objects and encoding the response. Event loop and server depend on the ASGI server, the loop implementation and the worker count. Application I/O is time spent waiting on databases, caches and other services.

Component Main driver Changes when you switch framework?
Routing and middleware Framework design Yes
Validation and serialization Modeling library Partly
Event loop and server Deployment choice No
Application I/O Your queries and network No

Hello-world benchmarks remove the last row and shrink the second, so framework overhead looks like most of the cost.

msgspec is a serialization and validation library built on Struct types, implemented in C. It decodes JSON straight into typed objects and validates them in a single pass, which helps most with large payloads or high request volumes. In exchange, you lose most of Pydantic's custom validators, its flexible coercion rules, its field-level customization and its plugin ecosystem.

Illustrative estimate (assumed inputs, not a measurement): take 0.3 ms of framework overhead, 0.5 ms of serialization and 15 ms waiting on a database, for about 15.8 ms in total. Halving framework and serialization cost saves 0.4 ms, about 2.5% of end-to-end latency. Halving a comparable share of other in-process work as well only gets you toward roughly 5%. I/O dominates.

Speed claims depend on the workload. Published charts often use different servers, settings or payloads, so their results rarely carry over to your service.

How do you benchmark FastAPI vs Litestar fairly on your own workload?

Build one test harness and change only the framework. Put each app behind the same ASGI server with the same worker count, on the same machine, and run the load generator on a separate host so it doesn't compete for CPU. A generic launch for both looks like uvicorn app:app --workers 4 --no-access-log. Access logging is off because it adds per-request cost that has nothing to do with the framework.

Make the endpoint resemble production. The example that follows defines one route in each framework that awaits a single I/O dependency, either a real database query or an asyncio.sleep stand-in sized to your observed query latency. Each route returns a nested response model with a list of 20 to 50 items. A "hello world" route measures routing overhead only, and the previous section showed that this overhead is rarely what limits throughput.

Pin every dependency, including the framework, server, serializer and event loop, in a lockfile. Record those versions alongside your results so they can be reproduced.

Run a warm-up pass of 30 to 60 seconds before measuring, then take several runs at fixed concurrency levels. Report p50, p95 and p99 latency for each level, not just requests per second. A framework can post higher throughput while its tail latency degrades under load, and tail latency is what users and upstream timeouts experience.

This takes about a day. If the results show both frameworks within a few percent of each other once the I/O wait is included, you have avoided a multi-week rewrite aimed at a bottleneck you don't have.

# bench_apps.py - one module, two apps, identical models and I/O stand-in.
# Pin fastapi, litestar, uvicorn and the event loop in a lockfile.
# Launch each the same way, one at a time:
#   uvicorn bench_apps:fastapi_app --workers 4 --no-access-log
#   uvicorn bench_apps:litestar_app --workers 4 --no-access-log
import asyncio
from dataclasses import dataclass

from fastapi import FastAPI
from litestar import Litestar, get

QUERY_LATENCY_S = 0.008  # set to your observed p50 DB query time
ITEM_COUNT = 30          # realistic list size, 20-50 items

@dataclass
class LineItem:
    sku: str
    quantity: int
    unit_price_cents: int

@dataclass
class Order:
    order_id: int
    customer_email: str
    items: list[LineItem]

async def load_order(order_id: int) -> Order:
    await asyncio.sleep(QUERY_LATENCY_S)  # stand-in for one DB round trip
    items = [LineItem(f"SKU-{i:04d}", i % 5 + 1, 1999) for i in range(ITEM_COUNT)]
    return Order(order_id, "buyer@example.com", items)

fastapi_app = FastAPI()

@fastapi_app.get("/orders/{order_id}", response_model=Order)
async def fastapi_order(order_id: int) -> Order:
    return await load_order(order_id)

@get("/orders/{order_id:int}")
async def litestar_order(order_id: int) -> Order:
    return await load_order(order_id)

litestar_app = Litestar(route_handlers=[litestar_order])

Equivalent FastAPI and Litestar endpoints that share the same response model and the same simulated database call, both served by the same uvicorn command and worker count, so the framework is the only variable under test.

How do typing and dependency injection differ between FastAPI and Litestar?

That claim targets a framework difference that rarely dominates. How each framework wires dependencies has a larger day-to-day effect.

Declaration and resolution

FastAPI resolves dependencies from the handler signature. The idiomatic form is db: Annotated[Session, Depends(get_db)]. This alias can be defined once and reused across handlers. Tests swap providers globally with app.dependency_overrides[get_db] = fake_db.

Litestar resolves dependencies by parameter name. A layer registers dependencies={"db": Provide(get_db)}, and any handler beneath it that declares a db parameter receives the value. That layer can be the app, a router, a Controller class or a single handler. Lower layers override higher ones, so a controller can replace an app-wide provider for its routes only. Tests usually build a small app or test client with substitute Provide entries instead of patching a global mapping.

What type checkers see

In both frameworks, mypy and pyright check the declared parameter type inside the handler. Neither checker confirms that the provider actually returns that type. With FastAPI, the Annotated type and get_db's return annotation can disagree silently. With Litestar, the link is a string key, which static analysis cannot follow. Both rely on runtime resolution, so test coverage of the wiring matters more than checker output.

Trade-offs

FastAPI's minimal core imposes no structure. In large codebases, teams often drift toward a mix of aliases, inline Depends calls and module-level singletons. Litestar's layering and controllers enforce consistency. The cost is a scoping model developers must learn, and that model can feel heavy for a service with five endpoints.

from typing import Annotated

from fastapi import Depends, FastAPI
from litestar import Controller, Litestar, get
from litestar.di import Provide


async def get_db() -> str:
    return "postgresql://app@db-primary/orders"


async def get_replica() -> str:
    return "postgresql://app@db-replica/orders"


# FastAPI: the alias is defined once and reused. Checkers do not verify that get_db returns str.
DB = Annotated[str, Depends(get_db)]
fastapi_app = FastAPI()


@fastapi_app.get("/items")
async def list_items_fastapi(db: DB) -> dict:
    return {"db": db}

# Test override: a global mapping keyed by the provider function.
# fastapi_app.dependency_overrides[get_db] = lambda: "sqlite://"


# Litestar: the provider is bound to the key "db" and matched by parameter name.
class ItemController(Controller):
    path = "/items"
    # This controller-level provider overrides the app-level one for its routes only.
    dependencies = {"db": Provide(get_replica)}

    @get("/")
    async def list_items(self, db: str) -> dict:
        return {"db": db}


litestar_app = Litestar(route_handlers=[ItemController], dependencies={"db": Provide(get_db)})

The same read-only endpoint in both frameworks: FastAPI reuses an Annotated/Depends alias and is tested with a global override, while Litestar binds providers by name at the app and controller layers, and the controller layer takes precedence.

Data modeling, DTOs and OpenAPI generation

Litestar's DTOs separate the shape of the wire format from the shape of your model. You declare a model once, as a dataclass, msgspec Struct, Pydantic model or SQLAlchemy model. Then you attach a DTO whose config lists the fields to exclude or rename for a given handler. A UserCreate DTO might exclude id and created_at. A UserRead DTO might exclude password_hash. The framework generates the transfer logic from that config. FastAPI's common pattern is more explicit. You write UserIn and UserOut as separate Pydantic models, often sharing a UserBase, and set response_model=UserOut on the route.

DTOs reduce boilerplate when you have many models with mostly overlapping fields, especially ORM models. They add complexity when the input and output shapes differ structurally rather than by a few fields. In those cases, two plain models are easier to read. Exclusion lists are also a real risk. Add a sensitive column to the model, forget the exclude on one read DTO, and the field ships to clients with no error. A typo in a field name can also drop a field quietly. Test the serialized output for each DTO directly. A related cost comes from mixing Structs, Pydantic models and dataclasses in one codebase. Developers then have to track three sets of validation, default and serialization rules.

Both frameworks build OpenAPI schemas from type annotations, and both can get edge cases wrong. Check how each one renders discriminated unions, Optional versus nullable, and generic response wrappers. Learn the customization hooks: FastAPI's openapi_extra and an overridable openapi() method, and Litestar's OpenAPIConfig. Confirm the docs UI you want is available. Litestar offers several renderers, and FastAPI ships Swagger UI and ReDoc. Export the schema in CI and diff it against the committed version. That catches accidental contract changes before clients see them.

from dataclasses import dataclass, field
from datetime import datetime, timezone
from uuid import UUID, uuid4

# --- Litestar: one model, per-handler DTOs control the wire shape ---
from litestar import Litestar, post
from litestar.dto import DataclassDTO, DTOConfig

@dataclass
class User:
    email: str
    password_hash: str
    id: UUID = field(default_factory=uuid4)
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

class UserCreateDTO(DataclassDTO[User]):
    config = DTOConfig(exclude={"id", "created_at"})  # client cannot set these

class UserReadDTO(DataclassDTO[User]):
    config = DTOConfig(exclude={"password_hash"})  # new sensitive fields need adding here too

@post("/users", dto=UserCreateDTO, return_dto=UserReadDTO)
async def create_user(data: User) -> User:
    return data

litestar_app = Litestar([create_user])

# --- FastAPI: separate Pydantic models, shape is visible in each class ---
from fastapi import FastAPI
from pydantic import BaseModel

class UserBase(BaseModel):
    email: str

class UserIn(UserBase):
    password: str  # accepted on input only

class UserOut(UserBase):
    id: UUID
    created_at: datetime  # new fields stay hidden until added here

fastapi_app = FastAPI()

@fastapi_app.post("/users", response_model=UserOut)
async def create_user_fa(user: UserIn) -> dict:
    return {"email": user.email, "id": uuid4(), "created_at": datetime.now(timezone.utc)}

The same create-user endpoint built twice: once with Litestar DTOs that exclude fields from a single dataclass, and once with FastAPI's separate input and output Pydantic models.

How big is the ecosystem gap, and what does it cost in development time?

Contract checks catch API drift. The ecosystem gap shows up elsewhere: in how long it takes to fix something nobody on your team has seen before.

Factor FastAPI Litestar
Tutorials and Q&A coverage Extensive; most errors are already answered somewhere Thinner; expect to read the docs and source code
Auth, admin, ORM, observability integrations Many community packages Fewer; some built in, others you write yourself
Hiring familiarity Common on backend CVs Rare; plan for ramp-up time
LLM-assisted coding accuracy Generally good, since training data is abundant Often mixes in FastAPI idioms or outdated APIs; review generated code closely

FastAPI's community is an operational asset. A new hire can usually find a working example of an unfamiliar pattern, and an obscure traceback has often been reported before. With Litestar, expect fewer ready-made examples and extensions. When something breaks, you will spend more time stepping through framework internals.

Illustrative estimate (assumed numbers, not a benchmark): Extra hours per year = issues without a ready answer × extra hours to resolve each. Assume 12 such issues and 3 extra hours each: 12 × 3 = 36 hours. Plug in your own team's figures.

Before you commit, check Litestar's maintainer base, governance model and release cadence yourself. Don't assume they are healthy or unhealthy.

Both frameworks have shipped breaking changes across major releases. Whichever you choose, pinning dependencies and reading changelogs before each upgrade is a recurring cost to budget for.

When should you choose FastAPI, Litestar or an alternative, and when should you avoid migrating?

Choose FastAPI when onboarding speed and integrations matter most. More engineers already know it, more tutorials and third-party packages target it, and its function-plus-Depends style is easy to learn quickly. Avoid it if a large codebase needs enforced structure and your team won't build that convention itself.

Choose Litestar when you want the framework to supply structure: class-based controllers, dependencies declared at app, router, controller or handler level, DTOs that control which fields are exposed, and more built-in features. Its msgspec-first serialization also helps payload-heavy services. Avoid it if your team relies on integrations that exist only for FastAPI, or if nobody can own the work of answering questions the community hasn't answered yet.

There are two other options. Plain Starlette works when you want a minimal core and are willing to handle validation and OpenAPI yourself. FastAPI with msgspec on a few hot endpoints keeps your existing stack and speeds up the routes that actually show up in profiles.

Condition Recommendation
New team, tight deadline, many third-party integrations FastAPI
Large service needing enforced layering and DTOs Litestar
Serialization dominates CPU in profiles Litestar, or FastAPI with msgspec on hot paths
Minimal internal service, few endpoints Starlette
Existing FastAPI service, no measured problem Stay

Migrate an existing FastAPI service only for a measured bottleneck or a structural pain point. The cost is easy to underestimate because routing, dependencies, middleware, exception handlers, test clients and OpenAPI output all change. A rewrite done for performance alone rarely pays back that effort.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to fastapi vs litestar, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.