Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 25 min · revision 3

Sessions, Pools and Async Engines in a Web App

Give a FastAPI service its database backbone: one async engine and pool per process, one session per request behind a dependency, and a repository layer that keeps SQL out of the routes.

Contentsand lesson path

What you will learn

  • Scope sessions, transactions and pooled connections per request in a sync or async service, keeping data access behind a repository or service layer.

Prerequisites: SQL Fundamentals

01. Why it matters

The reading-list API now has models and queries; what it lacks is a lifetime policy for its database objects. When does the engine start? How long does a session live? Who returns connections to the pool? In a script the answers do not matter — everything ends with the process. In a web service, requests arrive concurrently on an event loop, workers share one database, and a wrong answer shows up as cross-request state leaks or a pool that runs dry under load.

This lesson assembles the data layer of the practice project: an engine created once per process, a session per request provided by a yield dependency, and a repository that keeps every SQL statement out of the route functions. All of it runs against the same lab PostgreSQL with the asyncpg driver — which is also where this skill's two classic async traps live, so we walk into both on purpose.

02. One engine, one pool, per process

The engine is the expensive, shared thing: it holds the dialect, the connection pool and the logger. Creating it does not connect — the first checkout does. One engine per process is the rule, at module level or in a lifespan handler; pool_size is how many connections it keeps warm, max_overflow how many extra it may open briefly before refusing to hand out more. On install, pull in the asyncio extra, which brings greenlet: the async engine needs it and a plain sqlalchemy install leaves it out. In the uv environment from the N+1 lab, add the async driver and the web stack: uv pip install "sqlalchemy[asyncio]==2.1.9" asyncpg==0.32.0 fastapi==0.165.0 pydantic==2.14.4 uvicorn==0.54.0 (the versions this lesson ran with).

Python · db.py
from sqlalchemy.ext.asyncio import (
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

DB_URL = "postgresql+asyncpg://postgres:lab@localhost:55433/lab"

# One engine per process: it owns the connection pool.
engine = create_async_engine(DB_URL, pool_size=5, max_overflow=5)

# expire_on_commit=False: attribute reads after commit must not
# turn into implicit I/O, which an async session cannot do.
SessionMaker = async_sessionmaker(engine, expire_on_commit=False)

The postgresql+asyncpg:// URL picks the async driver the same way postgresql+psycopg:// picked the sync one in earlier lessons. Sessions come from an async_sessionmaker, a factory you configure once; expire_on_commit=False is the usual async setting, and the reason arrives with the first trap below.

03. A session per request, behind a dependency

A session is a unit of work: it tracks the objects one piece of work loaded and changed, and flushing it is one transaction. "One piece of work" in a web service is one request. A session shared across requests would let one handler's half-finished changes leak into another's commit — and with concurrent handlers, into a race. FastAPI's dependency injection gives the pattern a home: the dependency yields a session, and the async with block closes it whether the handler succeeds or raises.

Python · deps.py
from collections.abc import AsyncIterator

from sqlalchemy.ext.asyncio import AsyncSession

from db import SessionMaker


async def get_session() -> AsyncIterator[AsyncSession]:
    """One session per request: one transaction boundary, always closed."""
    async with SessionMaker() as session:
        yield session

Routes declare the session with an Annotated type alias, the form FastAPI recommends for dependencies, and immediately hand it to a repository. main.py below is the whole service: the Pydantic models for requests and responses, the repository, and two routes, using the Author and Book models from the typed models lesson. The repository is the seam from the practice: every select, insert and text() lives in one class, routes never import SQLAlchemy, and a test can fake the whole data layer by standing in for one interface.

Python · main.py (API models, repository and routes)
from typing import Annotated

from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from deps import get_session
from models import Author, Book

app = FastAPI()


class BookIn(BaseModel):
    title: str
    author: str
    pages: int


class BookOut(BookIn):
    id: int


class AuthorOut(BaseModel):
    author: str
    books: list[str]


class BookRepository:
    """All SQL lives here; routes depend on the interface only."""

    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def add_book(self, data: BookIn) -> BookOut:
        author = (
            await self.session.scalars(
                select(Author)
                .options(selectinload(Author.books))  # eager: no lazy load
                .where(Author.name == data.author)
            )
        ).first()
        if author is None:
            author = Author(name=data.author)
            self.session.add(author)
        book = Book(title=data.title, pages=data.pages)
        author.books.append(book)
        await self.session.commit()
        return BookOut(id=book.id, **data.model_dump())

    async def list_authors(self) -> list[AuthorOut]:
        authors = await self.session.scalars(
            select(Author).options(selectinload(Author.books)).order_by(Author.id)
        )
        return [
            AuthorOut(author=a.name, books=[b.title for b in a.books])
            for a in authors
        ]


SessionDep = Annotated[AsyncSession, Depends(get_session)]


@app.post("/books", status_code=201)
async def create_book(data: BookIn, session: SessionDep) -> BookOut:
    return await BookRepository(session).add_book(data)


@app.get("/authors")
async def list_authors(session: SessionDep) -> list[AuthorOut]:
    return await BookRepository(session).list_authors()

The eager .options(selectinload(...)) is not decoration. The first version of exactly this method omitted it, and adding a second book to an existing author failed with MissingGreenlet: appending to author.books needs the collection loaded, an AsyncSession cannot run I/O implicitly on attribute access, so the lazy load that quietly worked in the sync lessons is an error here. Eager loading where you will touch the relationship is the fix — the same lesson the N+1 lab taught, enforced by the async runtime.

To get the ids shown below, start from empty tables: the N+1 lab left 24 seeded authors behind, so first run TRUNCATE books, authors RESTART IDENTITY; in psql against the lab database.

Terminal · start the service, then post two books to one author
# terminal 1: start the service (it keeps running; stop it with Ctrl+C)
uvicorn main:app --port 8123

# terminal 2: two POSTs, then the author list (-w adds a newline)
curl -s -w '\n' -X POST localhost:8123/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Dune","author":"Frank Herbert","pages":412}'
curl -s -w '\n' -X POST localhost:8123/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Dune Messiah","author":"Frank Herbert","pages":256}'
curl -s -w '\n' localhost:8123/authors
Expected output · terminal 2, starting from empty tables
{"title":"Dune","author":"Frank Herbert","pages":412,"id":1}
{"title":"Dune Messiah","author":"Frank Herbert","pages":256,"id":2}
[{"author":"Frank Herbert","books":["Dune","Dune Messiah"]}]

04. The second async trap: reading after commit

By default a session expires its objects on commit: the next attribute read must check the database, in case another transaction changed the row. In a sync session that read is a quiet extra query. In an async session a plain attribute read cannot run a query, so the read fails loudly instead. You can watch both settings in one small script:

Python · expire_demo.py
import asyncio

from sqlalchemy import select
from sqlalchemy.exc import MissingGreenlet
from sqlalchemy.ext.asyncio import async_sessionmaker

from db import engine
from models import Author

default_maker = async_sessionmaker(engine)  # expire_on_commit=True
safe_maker = async_sessionmaker(engine, expire_on_commit=False)


async def first_author_name(maker) -> str:
    async with maker() as session:
        author = (await session.scalars(
            select(Author).limit(1)
        )).one()
        await session.commit()
        return author.name  # attribute access after commit


async def main() -> None:
    try:
        await first_author_name(default_maker)
    except MissingGreenlet as err:  # raised by the read after commit
        print("default sessionmaker ->", type(err).__name__)
    print("expire_on_commit=False ->", await first_author_name(safe_maker))
    await engine.dispose()


asyncio.run(main())
Expected output
default sessionmaker -> MissingGreenlet
expire_on_commit=False -> Frank Herbert

The async_sessionmaker(engine, expire_on_commit=False) from db.py makes the second line the behaviour everywhere. If you truly need fresh values after a commit, await session.refresh(obj) reloads them explicitly. Treat the exception itself as useful: it fires exactly where a hidden query would have fired, so it points at either a missing eager load or a read that belongs before the commit.

05. What an exhausted pool looks like

Sessions check a connection out of the engine's pool and return it when they close. Three workers, a pool of two, max_overflow=0, and a query that holds its connection for three seconds — the third worker waits one second for a checkout and then fails:

Python · pool_demo.py
import asyncio

from sqlalchemy import text
from sqlalchemy.exc import TimeoutError as SATimeoutError
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

from db import DB_URL

engine = create_async_engine(DB_URL, pool_size=2,
                             max_overflow=0, pool_timeout=1)
maker = async_sessionmaker(engine, expire_on_commit=False)


async def hold_connection(n: int) -> None:
    async with maker() as session:
        await session.execute(text("SELECT pg_sleep(3)"))
    print(f"worker {n}: connection returned to the pool")


async def main() -> None:
    tasks = [asyncio.create_task(hold_connection(n)) for n in range(3)]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    for n, result in enumerate(results):
        if isinstance(result, SATimeoutError):
            print(f"worker {n} failed: {result}")
    await engine.dispose()


asyncio.run(main())
Expected output · workers 0 and 1 may finish in either order (long line wrapped)
worker 0: connection returned to the pool
worker 1: connection returned to the pool
worker 2 failed: QueuePool limit of size 2 overflow 0 reached,
  connection timed out, timeout 1.00 (Background on this error at:
  https://sqlalche.me/e/21/3o7r)

The message names the pool's numbers and points at SQLAlchemy's own error page — a better clue than a generic timeout. When you meet it in production, the cause is usually not a pool that is too small but sessions that live too long. A session-per-request dependency returns connections within milliseconds; a session stored on a long-lived object, or a handler that awaits a slow external API mid-transaction, holds one for seconds, and enough of those exhaust any pool. Keep the unit of work short, let the dependency close the session, and size the pool to what the database can bear — every worker process gets its own pool, so pool_size=5, max_overflow=5 from db.py across eight workers is up to 40 connections kept open between requests and up to 80 at peak. Size against the peak: it is the number to compare with the server's max_connections.

06. Check your understanding

Practice check · 3 questions

Lifetimes and failures

Apply the lifetime rules to three situations.

Q1. A teammate moves create_async_engine inside the request dependency, disposing the engine after each request. What breaks first?
Q2. A handler raises halfway through, after the session has pending changes. What does the async with in get_session guarantee?
Q3. What does putting all SQL in BookRepository buy the service?
Practice only: not graded, not saved, not evidence.

07. Apply it

This lesson is the backbone of the practice task. Replace the reading-list API's in-memory store: create the async engine and sessionmaker at startup, provide sessions through the yield dependency, move every query into a repository, and add the report method as parameterised text() from the queries lesson. Finish with the guard from the N+1 lab: a test that exercises the list endpoint and asserts a constant number of queries, now against the async engine with the same before_cursor_execute listener.

08. Review prompt

Without looking back: what does the engine own, and how many of them should a process have? Why is a session per request the right unit of work, and what does the async with in the dependency promise when a handler raises? Explain both async traps — the missing eager load and the read-after-commit — and why expire_on_commit=False plus explicit refresh() covers the second. Finally, name two ways a service exhausts its pool even when pool_size looks generous.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check