
When we build a backend application, getting an API to work is usually the easy part. The real challenge starts when more users begin hitting the same endpoints, database queries become expensive, request payloads get larger, and the application needs to handle multiple operations without slowing down.
I've worked with Node.js and Express, where building a REST API is straightforward. You define routes, add middleware, connect your database, and return JSON responses. Python offers a similar experience with FastAPI, but what makes it interesting is how much functionality it provides without forcing you to write a lot of boilerplate code.
FastAPI combines Python type hints, asynchronous request handling, automatic API documentation, and Pydantic validation. With Pydantic v2, data validation and serialization are also designed to be efficient.
In this guide, we'll build a practical REST API using FastAPI and Pydantic v2, explore how asynchronous endpoints work, connect the API to a database, and discuss the changes that actually matter when performance becomes important.
The goal isn't to chase impressive benchmark numbers. It's to understand how to build an API that remains responsive, maintainable, and reliable as the application grows.
1. Why Choose FastAPI for REST API Development?
Python has several popular backend frameworks, including Django, Flask, and FastAPI. Each solves a slightly different problem.
Django is a good choice when you need a full-featured framework with an ORM, authentication components, an admin interface, and a structured application architecture.
Flask gives you a lightweight foundation and lets you choose the components you need.
FastAPI is particularly useful when you're building APIs that benefit from type hints, request validation, asynchronous I/O, and automatic documentation.
Consider a typical endpoint in a Python API. It needs to accept JSON, validate the request, execute business logic, and return a response.
Without a structured validation layer, you might find yourself checking individual fields manually:
def create_user(data):
if "name" not in data:
raise ValueError("Name is required")
if "email" not in data:
raise ValueError("Email is required")
# More validation...This becomes difficult to maintain when the request contains nested objects, optional fields, dates, lists, and values with specific constraints.
FastAPI and Pydantic let us define the expected data structure once and reuse it throughout the application.
For example:
from pydantic import BaseModel, EmailStr, Field
class CreateUserRequest(BaseModel):
name: str = Field(min_length=2, max_length=100)
email: EmailStr
age: int = Field(ge=18, le=120)FastAPI can use this model to validate incoming requests automatically.
If the email is invalid or the age falls outside the permitted range, the framework returns a validation error instead of allowing invalid data to reach the business logic.
This is one of the biggest benefits of using FastAPI: less repetitive code and a clearer contract between the client and the server.
2. Setting Up the Project
Let's start with a small project that manages products.
We'll use:
Python for the application logic.
FastAPI for routing and request handling.
Pydantic v2 for validation and serialization.
Uvicorn as the ASGI server.
SQLAlchemy for database access.
PostgreSQL as the production database.
You don't need to install PostgreSQL immediately to follow the initial examples. We'll begin with the API structure and introduce database integration later.
First, create the project:
mkdir fastapi-performance
cd fastapi-performanceCreate a virtual environment:
python3 -m venv .venvActivate it on macOS or Linux:
source .venv/bin/activateOn Windows, use:
.venv\Scripts\activateInstall the required packages:
pip install "fastapi>=0.115,<1.0" "pydantic>=2.0,<3.0" "uvicorn[standard]" email-validatorThese version ranges are examples for a Pydantic v2-based project, not a substitute for a tested dependency lockfile. For production, select compatible versions, test them together, and lock the exact versions you deploy.
Create this initial structure:
fastapi-performance/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── schemas.py
│ └── routes.py
├── requirements.txt
└── .venv/You can generate a requirements file after installing your dependencies:
pip freeze > requirements.txtFor a real project, consider using a dependency manager such as uv or Poetry to make dependency resolution and reproducible installations easier.
3. Creating Our First FastAPI Application
Let's start with the main application file.
app/main.py
from fastapi import FastAPI
app = FastAPI(
title="Product API",
description="A REST API built with FastAPI and Pydantic v2",
version="1.0.0",
)
@app.get("/health")
async def health_check():
return {
"status": "ok",
"message": "API is running",
}Start the development server:
uvicorn app.main:app --reloadThe API will normally be available at:
http://127.0.0.1:8000Open the following paths in your browser:
/health— checks whether the application is responding./docs— provides interactive Swagger documentation./redoc— displays an alternative API documentation interface.
One useful detail here is that you don't need to maintain a separate API specification manually for basic endpoints. FastAPI generates an OpenAPI schema from your routes, type annotations, and Pydantic models.
This becomes especially useful when your frontend and backend are developed separately. Frontend developers can inspect the available endpoints, required parameters, request bodies, and response structures without repeatedly asking how each endpoint works.
4. Using Pydantic v2 for Request Validation
Request validation is more important than it might appear at first.
Imagine a product creation endpoint that accepts this request:
{
"name": "Mechanical Keyboard",
"price": 2499.99,
"stock": 20
}Everything looks fine. But what happens if someone sends a negative price, an empty product name, or a string instead of a valid number?
We need a consistent way to validate these values before processing them.
That's where Pydantic models come in.
Create the following file.
app/schemas.py
from pydantic import BaseModel, ConfigDict, Field
class ProductCreate(BaseModel):
name: str = Field(min_length=3, max_length=150)
description: str | None = Field(default=None, max_length=1000)
price: float = Field(gt=0, allow_inf_nan=False)
stock: int = Field(default=0, ge=0)
class ProductResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
description: str | None
price: float
stock: intLet's understand what these models are doing.
Field constraints
The Field() function lets us define rules for individual fields.
name: str = Field(min_length=3, max_length=150)This prevents product names from being shorter than three characters or longer than 150 characters.
Similarly:
price: float = Field(gt=0, allow_inf_nan=False)This requires a positive, finite price.
And:
stock: int = Field(default=0, ge=0)This ensures the stock count is not negative.
For monetary values in a real financial application, consider using Decimal with an appropriate database column rather than binary floating-point numbers. Floating-point arithmetic can introduce precision problems when calculating currency amounts.
Why separate request and response models?
You might wonder why we have ProductCreate and ProductResponse instead of using a single model everywhere.
The reason is simple: clients should not control fields that belong to the server.
When a user creates a product, they shouldn't be able to choose its database ID or change internal audit fields through the request body.
A creation model defines what the client is allowed to submit. A response model defines what the API returns.
This separation also makes it easier to change internal database structures without unnecessarily changing the public API.
Pydantic v2 and model_validate()
Pydantic v2 introduced an updated API for model validation and serialization.
For example:
product_data = {
"name": "Mechanical Keyboard",
"price": 2499.99,
"stock": 20,
}
product = ProductCreate.model_validate(product_data)
print(product.name)
print(product.model_dump())You can also serialize a model into JSON:
json_data = product.model_dump_json()These methods are useful when you need explicit validation or serialization outside FastAPI's automatic request handling.
Another important change is the use of model_config rather than the old Pydantic v1 class Config pattern.
When working with Pydantic v2, avoid copying older examples without checking whether they use deprecated or incompatible APIs.
5. Building the Product CRUD Endpoints
Now let's connect the models to our API.
For this first implementation, we'll use an in-memory dictionary to keep the example focused on routing and validation.
This is only a teaching example. Data stored in memory disappears when the application restarts, and multiple worker processes won't share the same dictionary.
app/routes.py
from fastapi import APIRouter, HTTPException, status
from app.schemas import ProductCreate, ProductResponse
router = APIRouter(prefix="/products", tags=["Products"])
products: dict[int, dict] = {}
next_product_id = 1
@router.post(
"/",
response_model=ProductResponse,
status_code=status.HTTP_201_CREATED,
)
async def create_product(payload: ProductCreate):
global next_product_id
product = {
"id": next_product_id,
**payload.model_dump(),
}
products[next_product_id] = product
next_product_id += 1
return product
@router.get("/", response_model=list[ProductResponse])
async def list_products():
return list(products.values())
@router.get("/{product_id}", response_model=ProductResponse)
async def get_product(product_id: int):
product = products.get(product_id)
if product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
return product
@router.delete("/{product_id}")
async def delete_product(product_id: int):
product = products.pop(product_id, None)
if product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
return {"message": "Product deleted successfully"}Now register the router in the application.
app/main.py
from fastapi import FastAPI
from app.routes import router as product_router
app = FastAPI(
title="Product API",
version="1.0.0",
)
app.include_router(product_router)
@app.get("/health")
async def health_check():
return {"status": "ok"}Restart the server if needed and open /docs.
You'll see the product endpoints documented automatically.
You can create a product, retrieve all products, fetch a product by ID, and delete a product.
Testing the API
You can test the creation endpoint using curl:
curl -X POST "http://127.0.0.1:8000/products/" \
-H "Content-Type: application/json" \
-d '{
"name": "Mechanical Keyboard",
"description": "A compact mechanical keyboard",
"price": 2499.99,
"stock": 20
}'The API should return a response containing the newly created product and an HTTP 201 Created status.
Now try sending a negative price:
{
"name": "Mechanical Keyboard",
"price": -100,
"stock": 20
}FastAPI will reject the request with a validation error.
Notice that we didn't write a manual validation function inside the endpoint. Pydantic handles the field constraints before the endpoint processes the request.
That's one of the practical advantages of this approach.
6. Understanding Asynchronous Programming in FastAPI
This is where many developers get confused.
FastAPI supports both regular def endpoints and asynchronous async def endpoints. However, using async def everywhere does not automatically make an application faster.
To understand why, we need to look at what happens when an API receives a request.
Suppose an endpoint needs to:
Receive a request.
Query a database.
Call an external payment service.
Return the response.
If these operations involve waiting for network responses, the application spends part of its time waiting rather than performing CPU calculations.
Asynchronous programming allows the application to work on other tasks while an asynchronous operation is waiting for I/O.
For example:
import asyncio
from fastapi import FastAPI
app = FastAPI()
async def fetch_user_data():
await asyncio.sleep(1)
return {"user": "Manjeet"}
@app.get("/user")
async def get_user():
user = await fetch_user_data()
return userHere, asyncio.sleep() is used only to demonstrate asynchronous waiting. In a real application, the wait might come from an asynchronous database query or an HTTP request to another service.
While this coroutine is waiting, the event loop can run other tasks.
When should you use async def?
Use asynchronous endpoints when the operations they perform use compatible asynchronous libraries and spend significant time waiting for I/O.
For example:
Calling an external API with an asynchronous HTTP client.
Running queries through an asynchronous database driver.
Reading from an asynchronous message stream.
Waiting for an asynchronous Redis operation.
But consider this endpoint:
@app.get("/report")
async def generate_report():
result = expensive_cpu_calculation()
return {"result": result}If expensive_cpu_calculation() performs a long, CPU-intensive operation synchronously, it blocks the event loop while running.
Other requests handled by that event loop may be delayed.
For CPU-heavy work, consider moving the computation to a process pool, a separate worker service, or a task queue. The right solution depends on the workload and deployment architecture.
What about regular def endpoints?
FastAPI runs ordinary synchronous path operations in a thread pool rather than directly executing them on the event loop.
This is useful when you need to call a synchronous library that would otherwise block asynchronous request handling.
However, it doesn't mean that all synchronous work becomes inexpensive. Thread pools have limits, and excessive blocking work can still reduce throughput.
The practical rule: Choose the endpoint style based on the libraries and operations you're using, not simply because asynchronous code looks more modern.
7. Connecting FastAPI to PostgreSQL
An in-memory dictionary is useful for a quick demonstration, but a production API needs persistent storage.
Let's introduce SQLAlchemy 2.x with an asynchronous PostgreSQL driver.
Install the database dependencies:
pip install "sqlalchemy>=2.0,<3.0" asyncpgFor production, lock the exact versions you test.
Create a database module.
app/database.py
import os
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
DATABASE_URL = os.environ["DATABASE_URL"]
engine = create_async_engine(
DATABASE_URL,
pool_pre_ping=True,
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
async def get_db():
async with AsyncSessionLocal() as session:
yield sessionConfigure the database URL through an environment variable:
export DATABASE_URL="postgresql+asyncpg://user:password@localhost:5432/products"Use a local development database for this example. In production, load credentials from your deployment platform's secret manager or environment configuration rather than hardcoding them into source code.
The engine manages database connections through a connection pool. Instead of creating a new database connection for every request, the application can reuse available connections.
The pool_pre_ping=True option checks connections before using them, helping the pool detect certain stale connections.
It does not eliminate every possible connection failure, so application code still needs appropriate error handling.
Why connection pooling matters
Imagine that your API receives hundreds of concurrent requests, and every request opens a separate database connection.
This can exhaust database connection limits and increase resource consumption.
A connection pool helps control how many connections the application uses.
However, the pool size needs to be planned carefully. If you run multiple application workers, each worker may maintain its own pool.
For example, four workers with a pool size of ten can potentially use around forty pooled connections, excluding overflow and other connections.
Your total connection budget must account for all application instances, workers, background jobs, and administrative connections.
8. Making Database Queries Efficient
As an application grows, database queries often become more important to overall API performance than the web framework itself.
Consider an endpoint that returns every product in the database.
products = await session.scalars(
select(Product)
)If the table contains a few dozen records, this might be fine. If it contains hundreds of thousands of records, returning everything in one response can create unnecessary database work, memory usage, serialization time, and network traffic.
A better approach is to support pagination.
For example:
from fastapi import Query
@app.get("/products")
async def list_products(
limit: int = Query(default=20, ge=1, le=100),
offset: int = Query(default=0, ge=0),
):
# Use limit and offset in the database query.
...The example above defines validated pagination parameters. The database query itself should apply the limit and offset rather than fetching every record and slicing the result in Python.
For a SQLAlchemy query, that could look like:
from sqlalchemy import select
statement = (
select(Product)
.order_by(Product.id)
.offset(offset)
.limit(limit)
)
result = await session.scalars(statement)
products = result.all()This is an illustrative query fragment; it assumes that Product is a mapped SQLAlchemy model and that session is an active AsyncSession.
For large datasets, offset-based pagination can become expensive because the database may need to scan and skip many rows. Cursor-based pagination is often a better choice when clients move through large, frequently changing collections.
Add indexes where they make sense
Suppose users frequently search products by SKU.
Without an appropriate index, the database might need to scan a large portion of the table.
An index can make lookups more efficient:
CREATE UNIQUE INDEX idx_products_sku
ON products (sku);This example assumes SKU values must be unique. If your business rules allow duplicate SKUs, use a non-unique index instead.
Indexes aren't free. They consume storage and add work to inserts, updates, and deletes.
Before adding indexes, inspect actual query patterns and use the database's query-analysis tools to determine where they help.
Avoid the N+1 query problem
Another common performance issue occurs when the application executes one query to fetch a list and then executes an additional query for each item.
For example, fetching 100 orders and then individually querying each order's customer could result in approximately 101 queries.
Depending on the ORM model and relationships, eager-loading strategies or joins can reduce this overhead.
The important thing is to inspect the actual SQL being executed rather than assuming that a short Python expression always translates into an efficient database operation.
9. Pydantic v2 Serialization and Response Models
Validation is only one part of the process. The API also needs to convert its results into JSON.
FastAPI response models help define the public structure of an endpoint's output.
Consider:
from pydantic import BaseModel
class UserResponse(BaseModel):
id: int
name: str
email: strYou can apply this model to an endpoint:
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
return {
"id": user_id,
"name": "Alex",
"email": "alex@example.com",
"internal_note": "This should not be public",
}FastAPI uses the response model to validate and serialize the output. Fields that are not part of the declared response model are excluded from the normal response representation.
This is useful for more than performance. It helps prevent accidental exposure of internal fields.
For example, a database model might contain:
Password hashes.
Internal administrative notes.
Billing metadata.
Audit information.
Internal processing flags.
You generally shouldn't return an entire database object directly to the client when the public API needs only a few fields.
Create explicit response schemas that contain only the information clients are allowed to receive.
Can Pydantic v2 make serialization faster?
Pydantic v2 uses a redesigned validation and serialization architecture, including its Rust-based pydantic-core component.
That can improve performance for many validation and serialization workloads compared with Pydantic v1.
But the actual improvement depends on your models, data sizes, validation rules, and application workload.
If an endpoint spends most of its time waiting for a slow database query, changing the response model may have little impact on its overall latency.
It's worth measuring validation and serialization time when profiling identifies them as significant costs.
10. Improving Performance with Redis Caching
Suppose your application has a product listing endpoint that returns popular products.
The database query is moderately expensive, but the data changes only occasionally. Hundreds of clients request the same information every minute.
Executing the same query for every request may be unnecessary.
Caching can help.
A cache stores the result of an operation so that future requests can reuse it instead of repeating the original work.
Redis is a common option for this because it provides fast in-memory data access and supports expiration policies.
A simplified caching flow looks like this:
The client requests a product.
The API checks Redis for the cached result.
If the result exists, the API returns it.
If it doesn't exist, the API queries the database.
The API stores the result in Redis with an expiration time.
Later requests can reuse the cached result.
An illustrative asynchronous Redis example:
import json
from redis.asyncio import Redis
redis = Redis.from_url(
"redis://localhost:6379",
decode_responses=True,
)
async def get_cached_product(product_id: int):
cache_key = f"product:{product_id}"
cached_product = await redis.get(cache_key)
if cached_product is not None:
return json.loads(cached_product)
# Replace this with a real database query.
product = {
"id": product_id,
"name": "Mechanical Keyboard",
"price": 2499.99,
}
await redis.set(
cache_key,
json.dumps(product),
ex=300,
)
return productInstall the Redis client if you want to run this example:
pip install redisThe ex=300 setting gives the cached entry a five-minute lifetime.
This example demonstrates the basic idea, but it does not include database integration, cache invalidation, connection lifecycle management, or production error handling. Those pieces need to be added before using the pattern in a real service.
What should you cache?
Caching works best when the data is expensive to retrieve and is requested frequently enough to justify storing it.
Good candidates can include:
Public product information.
Frequently requested configuration.
Read-heavy category listings.
Expensive calculations.
Certain aggregated statistics.
Be more careful with personalized responses, permissions, account balances, and frequently changing information.
For personalized data, cache keys must correctly account for the user and relevant authorization context. Otherwise, one user could receive data cached for another user.
Cache invalidation matters
Imagine that a product's price changes in PostgreSQL, but Redis still contains the old value.
The API might continue returning the outdated price until the cached value expires.
For data that must remain fresh, invalidate or update the relevant cache entry when the underlying data changes.
For example:
await redis.delete(f"product:{product_id}")This removes the specified cached entry.
The larger lesson is that caching introduces another layer of state into your application. It can improve response times, but it also introduces consistency and invalidation problems that you need to plan for.
11. Handling Errors Properly
A reliable API should return predictable errors instead of exposing internal exception details.
FastAPI provides HTTPException for common HTTP errors.
from fastapi import HTTPException, status
def get_product_or_404(product_id: int):
product = products.get(product_id)
if product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
return productThis produces a structured error response that clients can handle.
You should also distinguish between different kinds of failures.
For example:
Invalid request data should produce a validation response.
A missing resource should produce
404 Not Found.An unauthenticated request should produce
401 Unauthorizedwhen appropriate.An authenticated user without permission should generally receive
403 Forbidden.Unexpected internal failures should produce a generic server error rather than exposing database credentials or stack traces.
Avoid catching every exception and returning a successful response.
This is a particularly dangerous pattern:
try:
# Perform business logic
...
except Exception:
return {"message": "Something went wrong"}It hides the distinction between successful and failed requests and may accidentally return HTTP 200 OK.
Instead, log unexpected exceptions through your application's logging system and allow appropriate error handling to produce the correct HTTP status.
Don't include passwords, authentication tokens, or sensitive request data in your logs.
12. Adding Timeouts to External API Calls
A backend often depends on other services.
For example, an order API might call a payment provider, or an AI application might call a model API before returning a response.
If an external service becomes slow, your API can accumulate requests waiting for it.
Always consider explicit timeouts.
Here's an example using httpx:
import httpx
from fastapi import FastAPI, HTTPException
app = FastAPI()
client = httpx.AsyncClient(
timeout=httpx.Timeout(5.0)
)
@app.get("/external-data")
async def get_external_data():
try:
response = await client.get(
"https://api.example.com/data"
)
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
raise HTTPException(
status_code=504,
detail="External service timed out",
)
except httpx.HTTPError:
raise HTTPException(
status_code=502,
detail="External service request failed",
)Install the HTTP client:
pip install httpxThis is a simplified example. In a production application, create and close the HTTP client through the application's lifespan so connections can be reused and released cleanly.
Also consider the external service's error responses, retry rules, rate limits, and idempotency requirements.
Retries should be used carefully. Retrying every failed request immediately can make an overloaded service even less responsive.
For operations that change data, such as charging a payment method, retrying without an idempotency strategy can cause duplicate actions.
13. Rate Limiting and Request Protection
A fast API can still become unreliable if one client sends too many requests.
Rate limiting restricts how frequently a client can call an endpoint.
For example, a login endpoint may need stricter limits than a public product listing endpoint.
Rate limits can help reduce accidental overload and certain forms of abuse. They are not a replacement for authentication, authorization, or broader security controls.
A production implementation should consider:
Limits based on the client, user, API key, or route.
Shared storage when running multiple application instances.
Correct handling of proxy headers.
Different limits for sensitive operations.
Responses that communicate when a client can retry.
Monitoring for repeated rejected requests.
Avoid relying solely on an in-memory counter if your application runs across multiple workers or instances. Each worker may maintain a separate counter, making the effective limit inconsistent.
A shared store such as Redis is often used to coordinate rate limits across instances.
Also validate input sizes and set appropriate request limits at the application or reverse-proxy layer. Pydantic validation doesn't prevent every resource-exhaustion problem, especially if the server must first receive a very large request body.
14. Measuring API Performance Instead of Guessing
One mistake developers make is optimizing code before identifying the actual bottleneck.
Suppose an endpoint takes 600 milliseconds to respond.
Where is that time going?
It could be:
350 milliseconds waiting for a database query.
150 milliseconds waiting for an external API.
50 milliseconds validating and serializing data.
50 milliseconds in other application work.
These numbers are only an illustration, but they show why measurement matters.
If the database query consumes most of the time, rewriting a small Python function is unlikely to produce a major improvement.
Start by measuring:
Total request latency.
Database query duration.
External API duration.
Error rate.
Request throughput.
CPU and memory consumption.
Connection pool usage.
Cache hit and miss rates.
You can use structured logging, metrics, tracing, and load testing to understand what happens under realistic traffic.
For local testing, a basic request timing measurement can help:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def measure_request_time(
request: Request,
call_next,
):
start_time = time.perf_counter()
response = await call_next(request)
duration = time.perf_counter() - start_time
response.headers["X-Process-Time"] = (
f"{duration:.4f}"
)
return responseThis middleware adds an X-Process-Time response header containing the elapsed time measured around the request pipeline.
It is useful for basic diagnostics, but it doesn't replace proper production metrics or distributed tracing. It also measures application-side elapsed time around the middleware call, not the complete end-to-end time experienced by the client.
Avoid exposing internal timing details publicly if they reveal information you don't want clients to see.
Test with realistic traffic
An endpoint that works well with one request may behave differently when hundreds of requests arrive simultaneously.
Use a load-testing tool such as Locust or k6 to simulate realistic request patterns.
Don't test only the happy path. Include:
Valid requests.
Invalid payloads.
Large responses.
Database-intensive queries.
Cache misses.
External service delays.
Concurrent requests.
Rate-limited traffic.
Measure latency percentiles, not just average response time. A good average can hide a small percentage of very slow requests.
For example, p95 latency tells you the response time at or below which approximately 95% of measured requests completed. It is often more useful for understanding user experience than an average alone.
15. Running FastAPI in Production
Development and production environments have different requirements.
During development, this command is convenient:
uvicorn app.main:app --reloadThe reload option watches files and restarts the application when code changes. It's intended for development, not normal production deployment.
For a simple production launch, you can run:
uvicorn app.main:app --host 0.0.0.0 --port 8000The exact deployment setup depends on your hosting platform, traffic, and operational requirements.
Before deploying, consider the following checklist.
Environment variables
Keep secrets out of source code.
Configure database URLs, API keys, and other sensitive settings through environment variables or a secret manager.
Never commit production credentials to Git.
Database migrations
Use a migration tool such as Alembic to manage database schema changes.
Manually modifying production tables can create inconsistencies between environments and make deployments difficult to reproduce.
Application lifecycle
Initialize long-lived resources such as database engines and HTTP clients using FastAPI's lifespan mechanism. Close them when the application shuts down.
This makes resource ownership clearer and helps prevent connections from being created and discarded unnecessarily.
Worker configuration
Multiple workers can improve throughput when the workload benefits from parallel request handling, but each worker consumes resources and may create its own connection pools.
Don't choose a worker count solely from a rule of thumb. Test the configuration on your deployment environment and account for CPU, memory, database connections, and the nature of your workload.
HTTPS and proxy configuration
Production APIs should use HTTPS and be configured correctly behind their reverse proxy or load balancer.
Trust forwarded headers only from known proxies. Incorrect proxy configuration can affect client IP detection, secure URL generation, and rate limiting.
Monitoring and logging
Collect application errors, latency metrics, and resource usage. Set up alerts for issues that require action.
A deployment isn't complete just because the health endpoint returns 200 OK. You also need to know when database connections are exhausted, external dependencies fail, or latency rises unexpectedly.
16. Common Performance Mistakes to Avoid
Even with FastAPI and Pydantic v2, it's possible to build a slow API.
Here are some mistakes worth watching for.
Mistake | Why it causes problems | Better approach |
|---|---|---|
Using | Blocks the event loop | Use asynchronous libraries or appropriate worker execution |
Returning entire database tables | Increases database, memory, and network costs | Add pagination and field selection |
Running queries inside loops | Creates excessive database round trips | Use joins or suitable eager-loading strategies |
Opening a new connection for every operation | Adds overhead and can exhaust connection limits | Use managed connection pools |
Caching without invalidation | Returns stale data | Define expiration and invalidation rules |
Returning database objects directly | Risks leaking internal fields | Use explicit response schemas |
Adding indexes without measuring | Consumes storage and slows writes unnecessarily | Inspect query plans and real workloads |
Retrying every failure | Can amplify overload | Use bounded retries, backoff, and idempotency where appropriate |
Running CPU-heavy tasks on the event loop | Delays unrelated requests | Move expensive computations to suitable workers |
Optimizing without load testing | Focuses effort on the wrong bottleneck | Measure realistic traffic and latency percentiles |
One more thing: don't add Redis, queues, multiple workers, and complex caching to every small application just because they are common in high-performance systems.
Start with a clear implementation. Measure its behavior. Introduce extra infrastructure when you have a reason to do so.
17. A Practical Architecture for a Growing API
For a small application, keeping everything in one file can be convenient. As the codebase grows, separating responsibilities becomes more useful.
A possible project structure is:
app/
├── main.py
├── core/
│ ├── config.py
│ └── security.py
├── api/
│ ├── routes/
│ │ ├── products.py
│ │ └── users.py
│ └── dependencies.py
├── schemas/
│ ├── product.py
│ └── user.py
├── models/
│ ├── product.py
│ └── user.py
├── services/
│ ├── product_service.py
│ └── user_service.py
├── repositories/
│ ├── product_repository.py
│ └── user_repository.py
└── database.pyEach layer has a different responsibility.
Routes handle HTTP concerns, such as parameters, status codes, and response models.
Schemas define the input and output structures.
Services contain business rules, such as deciding whether a product can be purchased.
Repositories can isolate database operations when that separation makes the application easier to test and maintain.
Models define database entities.
You don't necessarily need every layer for every project. The important thing is to avoid mixing HTTP handling, business logic, and complicated database operations into one enormous endpoint function.
For example, a product service could expose a function such as create_product() that applies business rules and coordinates persistence. The route then becomes responsible for translating the HTTP request into a service call and returning the appropriate response.
This structure also makes testing easier because you can test business rules separately from HTTP behavior.
18. Testing FastAPI Endpoints
A high-performance API still needs to return correct results.
FastAPI provides TestClient for testing endpoints without starting a separate server process.
Install the testing dependencies:
pip install pytest httpxCreate a test file:
tests/test_health.py
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_health_check():
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}Run the tests:
pytestThis is a simple starting point. A more complete test suite should cover validation failures, missing resources, authentication, authorization, database behavior, and unexpected dependency failures.
For database tests, use an isolated test database or a carefully controlled test setup. Avoid running destructive test operations against production data.
For performance-sensitive endpoints, add load tests separately from ordinary functional tests. A test that verifies a response is correct doesn't prove that the endpoint remains responsive under heavy concurrency.
Conclusion
Building a high-performance REST API isn't just about choosing a fast framework. It's about making good decisions throughout the request lifecycle.
FastAPI gives us a strong foundation with type hints, automatic documentation, asynchronous request handling, and a clean routing system. Pydantic v2 makes it easier to validate incoming data and define predictable response structures.
But those tools are only part of the picture.
Database queries, connection pooling, pagination, caching, external service timeouts, error handling, and deployment configuration all influence how an API behaves under real traffic.
If you're starting a new project, begin with a clear set of endpoints, well-defined Pydantic models, and a sensible database design. Keep your code straightforward and test it properly.
Then measure the application.
If database queries are slow, optimize the queries. If external services dominate response times, investigate those dependencies. If CPU-intensive operations block the event loop, move them to an appropriate execution model. If repeated reads are expensive, consider caching and define how cached data will stay consistent.
The goal is not to make every endpoint as complicated as possible. The goal is to make the application fast enough, reliable enough, and easy enough to maintain for the problem it needs to solve.
That's what makes a REST API production-ready.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


