DEV Community

Cover image for FastAPI in production · 4. Databases: SQLAlchemy sessions and the async question
Amit chakraborty
Amit chakraborty

Posted on Originally published at amitchakraborty.dev

FastAPI in production · 4. Databases: SQLAlchemy sessions and the async question

FastAPI in production · Chapter 4 of 12 · Backend · new chapter every Wednesday night

By the end of this chapter: Talk to Postgres correctly, and decide about async on evidence.

The problem

Say you are a lead engineer with a deadline. Your FastAPI service for managing inventory has been running smoothly in staging with five users. You deploy to production, and within an hour, the service stops responding. The CPU usage is near zero, the memory is fine, but every request times out.

You check the logs and see sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached. You've exhausted your database connection pool. Worse, when you look at the PostgreSQL side using SELECT count(*) FROM pg_stat_activity;, you see hundreds of idle connections that never closed. Every time a request errored out during a validation step, the database session stayed open, leaking a connection until the database refused to talk to the API entirely.

This cost the team a full day of rollback and data cleanup. It happened because the team treated the database session like a global variable rather than a resource with a strict lifecycle. You need a pattern that guarantees every connection returns to the pool, even when the code crashes, and you need to decide if the complexity of an async database driver is actually worth the performance trade-off for your specific workload.

Before you start

You need a running PostgreSQL instance. If you have Docker installed, run:
docker run --name fastapi-db -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres:16

Ensure you have the following versions installed in your virtual environment:

  • Python 3.12+
  • FastAPI 0.115.0+
  • SQLAlchemy 2.0.35+
  • psycopg[binary] 3.2.1+ (the modern PostgreSQL adapter)

Verify your setup by running:

python -c "import sqlalchemy; import psycopg; print(sqlalchemy.__version__)"
# Output: 2.0.35 (or newer)
Enter fullscreen mode Exit fullscreen mode

Why SQLAlchemy 2.0 is the baseline

In earlier versions of SQLAlchemy, the "Object Relational Mapper" (ORM) felt like a magic layer that hid SQL. In 2.0, the library shifted to a "transparency first" model. You are expected to write queries that look like SQL, while the ORM handles the heavy lifting of mapping those results to Python objects.

For a production service, I recommend SQLAlchemy 2.0 because it provides PEP 484 type-hinting support natively. This means your IDE can catch a typo in a column name before you ever run the code.

The most important concept to master is the Session. A session is a "unit of work." It starts when a request begins, tracks changes to your objects, and either commits them all to the database or rolls them back if an error occurs. In production, the goal is to ensure the session lifecycle is tied directly to the HTTP request lifecycle.

The async question: Evidence over hype

FastAPI is built on anyio, making it naturally asynchronous. This leads many engineers to assume they must use an async database driver like asyncpg or the async mode of psycopg.

In my experience, you should only choose an async driver if you meet both of these criteria:

  1. Your API handles thousands of concurrent requests per second.
  2. Your database queries are slow (e.g., complex reporting) and would otherwise block the event loop.

For most CRUD (Create, Read, Update, Delete) applications, the overhead of managing an async loop in the database driver can actually make individual queries slightly slower. Furthermore, many mature Python libraries (like certain GIS tools or legacy extensions) do not support async.

SQLAlchemy 2.0 allows you to write your models once and choose between a sync or async "engine." We will build this using the sync psycopg driver, as it is the most stable path for production, but the structure we use allows for an easy swap later.

How to manage the session lifecycle

The "FastAPI way" to handle database sessions is through Dependency Injection. Instead of creating a session inside your route function, you define a dependency that yields a session.

FastAPI guarantees that if a function uses yield, the code after the yield will run even if the request finishes or errors out. This is where we put our session.close(). This pattern prevents the connection leaks described in the opening scenario.

Build it

We will build a robust database configuration that handles connection pooling and session management for a simple "Products" table.

1. Define the Database Configuration

Create a file named database.py. This sets up the Engine (the connectivity layer) and the SessionLocal (the factory for sessions).

from sqlalchemy import create_url, create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase

# Using psycopg (v3) as the driver
DATABASE_URL = "postgresql+psycopg://postgres:password@localhost:5432/postgres"

# pool_size: Number of permanent connections to keep open
# max_overflow: How many extra connections to allow during spikes
# pool_pre_ping: Checks if connection is alive before using it (prevents 500s after DB restarts)
engine = create_engine(
    DATABASE_URL,
    pool_size=10,
    max_overflow=20,
    pool_pre_ping=True,
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

class Base(DeclarativeBase):
    pass

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Enter fullscreen mode Exit fullscreen mode

Why: pool_pre_ping=True is vital for production. Without it, if your database restarts, the API will throw errors for every connection currently in its pool until they are all recycled.

2. Create the Model

Create models.py. We use the SQLAlchemy 2.0 Mapped and mapped_column syntax for full type safety.

from sqlalchemy.orm import Mapped, mapped_column
from .database import Base

class Product(Base):
    __tablename__ = "products"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(index=True)
    price: Mapped[float]
    in_stock: Mapped[bool] = mapped_column(default=True)
Enter fullscreen mode Exit fullscreen mode

3. Initialize the database and create a route

Create main.py. This ties the session to a FastAPI endpoint.

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import select
from .database import engine, Base, get_db
from .models import Product
from pydantic import BaseModel

# Create tables (In production, use Alembic - covered in Chapter 5)
Base.metadata.create_all(bind=engine)

app = FastAPI()

class ProductCreate(BaseModel):
    name: str
    price: float

@app.post("/products/")
def create_product(product_in: ProductCreate, db: Session = Depends(get_db)):
    new_product = Product(name=product_in.name, price=product_in.price)
    db.add(new_product)
    db.commit()
    db.refresh(new_product)
    return new_product

@app.get("/products/")
def list_products(db: Session = Depends(get_db)):
    # SQLAlchemy 2.0 style select
    query = select(Product).where(Product.in_stock == True)
    result = db.execute(query)
    return result.scalars().all()
Enter fullscreen mode Exit fullscreen mode

4. Confirm it works

Run the application:

fastapi dev main.py
Enter fullscreen mode Exit fullscreen mode

Use curl or the /docs UI to create a product:

curl -X 'POST' 'http://127.0.0.1:8000/products/' \
  -H 'Content-Type: application/json' \
  -d '{"name": "Mechanical Keyboard", "price": 150.0}'
Enter fullscreen mode Exit fullscreen mode

Check the database connections:

psql -h localhost -U postgres -c "SELECT count(*) FROM pg_stat_activity WHERE state='idle';"
Enter fullscreen mode Exit fullscreen mode

You should see a count corresponding to your pool_size. Refresh the endpoint multiple times; the count should remain stable, proving that sessions are being closed and returned to the pool.

When this breaks

1. The "MissingGreenlet" Error

Symptom: sqlalchemy.exc.MissingGreenlet: sqlalchemy.ext.asyncio.errors.MissingGreenlet: ...
Cause: You are using an async driver but tried to access a relationship attribute that hasn't been loaded yet (Lazy Loading).
Fix: In async mode, you must use selectinload or joinedload in your query to fetch related data explicitly. Async does not support lazy loading because it cannot trigger an I/O operation inside a property access.

2. The "Detached Instance" Error

Symptom: sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Product at ...> is not bound to a Session; attribute refresh operation cannot proceed
Cause: You tried to access a database object's attribute after the get_db dependency closed the session (e.g., inside a background task or after the response was sent).
Fix: Use db.refresh(obj) before the session closes, or set expire_on_commit=False in your sessionmaker.

3. Connection Pool Starvation

Symptom: Requests take exactly 30 seconds to fail with a TimeoutError.
Cause: Your pool_size is too small for your traffic, or you have a long-running non-database task (like an external API call) holding the database session open.
Fix: Increase pool_size or, better, move the non-database work outside the block where the db session is active.

What it costs

Using an ORM like SQLAlchemy adds a layer of abstraction that consumes more memory than raw psycopg results. In a high-memory-constrained environment (like a 256MB RAM Lambda function), this might be an issue.

The "Session per Request" pattern also means that even for routes that don't strictly need the database every time (like a conditional check), a connection is pulled from the pool as soon as the dependency is injected. This is a trade-off of convenience over absolute efficiency.

Finally, pool_pre_ping=True adds a tiny latency penalty to the first query of every request (usually < 1ms) because it issues a SELECT 1 to verify the connection. In production, this is almost always a price worth paying for stability.

In the interview

An interviewer will often ask: "Why use an ORM instead of writing optimized SQL?"

A weak answer focuses on "not having to learn SQL" or "speed of development." This suggests you don't understand the underlying technology.

A strong answer discusses Type Safety, Migration Management, and Identity Mapping. You should mention that SQLAlchemy 2.0 allows you to drop down to raw SQL easily when performance dictates, but the ORM provides a consistent way to handle the unit-of-work pattern (Sessions), ensuring that partial updates don't leave the database in an inconsistent state.

The follow-up is usually: "How do you prevent N+1 query problems in SQLAlchemy?"
You must be able to explain the difference between joinedload (SQL JOIN) and selectinload (two queries, one for the main object and one for the related objects using an IN clause). A senior candidate will know that selectinload is often faster for one-to-many relationships because it avoids the "cartesian product" bloat of a massive JOIN.

Your tasks

  1. The Health Check: Add a /health endpoint that doesn't just return "OK", but actually executes db.execute(text("SELECT 1")) to verify the database is reachable.
  2. The Leak Test: Intentionally break your code. Create a route that gets a db session but then raises an Exception before doing anything. Use pg_stat_activity to prove that the connection is still returned to the pool thanks to the finally block in get_db.
  3. The Relationship: Create a Category model. Link Product to Category with a many-to-one relationship. Write a query that fetches all products and their category names in exactly one SQL query using joinedload.
  4. The Slow Query: Use pg_sleep(5) in a raw SQL query through SQLAlchemy. Observe how this affects your FastAPI application's ability to handle other requests. This will help you understand when the "async question" becomes relevant.

Your tasks this week

Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.

Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.

FastAPI in production

Chapter 4 of 12. New chapter every Wednesday night.
Next: Migrations with Alembic.

· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe


Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.

Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Amit, the opening scenario is the part that earns the chapter: QueuePool limit of size 5 overflow 10 plus hundreds of idle connections is a leak wearing a capacity problem's clothes, and the fix is not a bigger pool. The diagnostic that separates the two is the one you hand the reader in step 4 — refresh the endpoint and watch pg_stat_activity: a stable idle count means the pool is healthy, a growing one means sessions are leaking. Task 2, the deliberate leak test, is the right proof of that finally block.

The async rule is the honest part — thousands of concurrent requests per second AND slow queries, both, before async is worth it. Most tutorials pick a side; you made it a test.

One question: the yield dependency closes the session in a finally, which is airtight in a sync def endpoint. But in an async def endpoint, the sync session's queries run on the event loop while they execute. Do you plan to cover that split in a later chapter — run_in_threadpool for the sync session, or the async engine swap — or does the series keep every route a sync def and sidestep it?