Connect FastAPI to PostgreSQL with async sessions
Model users, documents, conversations and jobs in PostgreSQL with async sessions, transactions and Alembic migrations.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 14 minutes to read.
In short
The document Q&A service keeps its users, documents, conversations and ingestion jobs in PostgreSQL. FastAPI talks to it through SQLAlchemy 2.0 async sessions: each request gets one session, does its reads and writes inside one transaction, and either commits everything or rolls everything back. Alembic migrations change the schema in small, reviewed, reversible steps.
Think of it like this: A session is a shopping basket: you add and remove items while you shop, and nothing is paid for until you check out, or you put it all back.
Explained simply
Until now the document Q&A service forgot everything when it restarted. A database fixes that. PostgreSQL stores rows in tables, keeps them safe on disk and lets many requests read and write at the same time without corrupting each other. We need four kinds of rows: users, documents, conversations and ingestion jobs.
Python talks to PostgreSQL through a driver. For async FastAPI code we use asyncpg as the driver and SQLAlchemy 2.0 on top of it. SQLAlchemy lets you describe tables as Python classes and write queries with Python objects, while still showing you the SQL it runs.
Opening a database connection is slow, so the app keeps a small set of open connections called a pool. Each request borrows one connection through a session, does its work and hands it back. If all connections are busy, the next request waits for a free one rather than opening more.
A transaction groups changes so they all happen or none do. When a user uploads a file, we create a document row and a job row. If saving the job fails, we do not want an orphaned document, so both writes sit in one transaction. That group of changes is called a unit of work.
Tables change as the product grows. Alembic is a migration tool: each change to the schema is a small Python script with an upgrade step and a downgrade step, stored in Git. Every environment runs the same scripts in the same order, so the schema never drifts.
Press Play on a diagram to walk through it one step at a time.
- 1Request arrives
Route depends on get_session
- 2Borrow a connection
From the bounded engine pool
- 3Begin transaction
async with session.begin()
- 4Read and write rows
Document, job and audit rows together
- 5Commit or roll back
All changes land, or none do
- 6Return the connection
Session closes, pool reuses it
- users
- id, tenant_id, email
- unique (tenant_id, email)
- documents
- id, tenant_id, owner_id
- title, storage_key, status
- conversations
- id, tenant_id, user_id
- messages: role, content, created_at
- jobs
- id, tenant_id, document_id
- state, attempts, last_error
- 1Route
Validates input, calls a service
- 2Service
Owns the transaction boundary
- 3Repository
Queries, always filtered by tenant
- 4AsyncSession
Tracks objects, one per request
- 5AsyncEngine and pool
One per process, created in lifespan
- 6PostgreSQL
Schema owned by Alembic revisions
In depth
Modelling the core tables
Start with the questions the API must answer: list my documents, show this job, continue this conversation. Each table gets a UUID primary key so IDs are hard to guess and safe to generate before the insert. Every tenant-owned table carries tenant_id, even when it could be reached through a join, because the API filters by tenant on every query and a direct column keeps that filter simple and indexable.
Use SQLAlchemy 2.0 typed models: a DeclarativeBase subclass, Mapped[...] annotations and mapped_column(). Store status values such as queued, running, done and failed as text with a CHECK constraint or a PostgreSQL enum, and add created_at and updated_at columns with server defaults. Keep large data out of rows: the file lives in object storage and the row holds its storage_key.
- UUID primary keys, generated in Python or with gen_random_uuid()
- tenant_id NOT NULL on every tenant-owned table
- Foreign keys with ON DELETE rules you chose on purpose
- Unique (tenant_id, email) rather than a global unique email
- File bytes in object storage, only the key in PostgreSQL
One session per request, one transaction per unit of work
Create the engine in the lifespan handler and dispose of it on shutdown with await engine.dispose(). Create an async_sessionmaker with expire_on_commit=False. Without that setting, every attribute of an object is expired after commit, and reading one later would need another query, which async code cannot do implicitly and so raises an error.
A dependency with yield opens a session for the request and closes it afterwards. Inside the route or a service function, wrap the writes in async with session.begin(). If the block finishes, SQLAlchemy commits; if any exception escapes, it rolls back. Commit before you return the response, so a client never sees 201 Created for a row that later failed to commit. Never share a session across concurrent tasks, such as several coroutines started with asyncio.gather; give each its own session.
- Client to Route: POST /documents1POST /documents
- Route to AsyncSession: session.begin()2session.begin()
- AsyncSession to PostgreSQL: BEGIN3BEGIN
- Route to AsyncSession: add(document), add(job)4add(document), add(job)
- AsyncSession to PostgreSQL: INSERT documents; INSERT jobs5INSERT documents; INSERT jobs
- AsyncSession to PostgreSQL: COMMIT (or ROLLBACK on error)6COMMIT (or ROLLBACK on error)
- Route to Client: 202 with job_id, only after COMMIT7202 with job_id, only after COMMIT
Sizing the connection pool
SQLAlchemy's default pool keeps up to pool_size connections open (default 5) and may open max_overflow extra ones under load (default 10). When all are in use, a request waits up to pool_timeout seconds (default 30) and then fails. Each Uvicorn worker process has its own pool, and so does each ingestion worker, so the real total is processes times (pool_size plus max_overflow).
PostgreSQL's max_connections defaults to 100, and some is reserved for superusers and tools. Add up every process before you choose numbers. A smaller pool with a short pool_timeout, such as 5 seconds, often behaves better than a big one: requests fail fast with a clear error instead of piling up. Set pool_pre_ping=True so a connection dropped by a restart or firewall is replaced before use. On managed databases with a connection pooler in front, such as PgBouncer, follow that pooler's guidance on prepared statements.
- Total connections = processes x (pool_size + max_overflow)
- Keep the total well under max_connections
- Short pool_timeout makes overload visible quickly
- pool_pre_ping replaces dead connections
Indexes that match your queries
An index is a sorted copy of some columns that lets PostgreSQL find rows without scanning the whole table. The service's common queries are list documents for a tenant, newest first, and find queued jobs. Matching indexes are (tenant_id, created_at DESC) on documents and a partial index on jobs (state) WHERE state = 'queued'. Foreign key columns are not indexed automatically in PostgreSQL, so add indexes on columns such as conversation_id in messages when you join or delete by them.
Check your guess with EXPLAIN ANALYZE on realistic data. If you see Seq Scan on a large table for a selective query, the index is missing or does not match the filter order. Each index slows writes a little and takes disk, so add the ones your queries use, not every column.
Alembic migrations you can trust
Run alembic init -t async migrations to get an env.py that works with an async engine. Point target_metadata at your Base.metadata so alembic revision --autogenerate -m "add jobs table" can compare models with the live schema and draft a script. Always read the draft: autogenerate cannot detect a column rename (it sees a drop and an add), and it does not notice every change to constraints or server defaults.
Apply with alembic upgrade head and step back with alembic downgrade -1. On a busy table, prefer additive steps: add a nullable column, backfill in batches, then add NOT NULL in a later release. Build large indexes with CREATE INDEX CONCURRENTLY, which cannot run inside a transaction; in Alembic, wrap it in op.get_context().autocommit_block() and pass postgresql_concurrently=True to op.create_index. Run migrations as a separate release step, not from every app instance at startup.
- alembic init -t async migrations
- alembic revision --autogenerate -m "message"
- alembic upgrade head, alembic downgrade -1
- alembic current and alembic history to see where you are
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Model the core tables~50m
- 2Use one async session per request~50m
- 3Commit or roll back as a unit~50m
- 4Bound the connection pool~50m
- 5Add indexes and Alembic migrations~50m
Key points
- Create the async engine once in the lifespan handler and share it; create a new AsyncSession per request.
- Wrap each unit of work in one transaction so a document row never exists without its ingestion job.
- Set pool_size and max_overflow on purpose: every worker process opens its own pool against the same database limit.
- Put tenant_id on every tenant-owned table and lead your composite indexes with it.
- Change the schema only through Alembic revisions that you review, test on a copy and can downgrade.
Key terms
Tap a card to flip it. 0/6 known
Examples
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
engine = create_async_engine(
"postgresql+asyncpg://app:app@localhost:5432/ragsvc",
pool_size=5, max_overflow=5, pool_pre_ping=True,
)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session():
async with SessionLocal() as session:
yield session
# in a route or service:
# async with session.begin():
# session.add_all([doc, job]) # committed together, or rolled back togetherOne engine per process, one session per request, one transaction per unit of work.
Run PostgreSQL locally and apply the first migration
Prerequisites: Docker, Python 3.11 or newer, and a venv with sqlalchemy, asyncpg and alembic installed. Step 1: start PostgreSQL in a container with a throwaway password. Step 2: create the Alembic folder with the async template and set sqlalchemy.url in alembic.ini to the same URL. Step 3: generate a revision from your models, read it, then upgrade. Evidence: psql lists the tables and alembic current prints the revision ID marked head. Cleanup: alembic downgrade base removes the tables, and docker rm -f ragsvc-db removes the database.
docker run -d --name ragsvc-db -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app \
-e POSTGRES_DB=ragsvc -p 5432:5432 postgres:16
alembic init -t async migrations
# set sqlalchemy.url = postgresql+asyncpg://app:app@localhost:5432/ragsvc
alembic revision --autogenerate -m "core tables"
alembic upgrade head
alembic current
docker exec -it ragsvc-db psql -U app -d ragsvc -c "\dt"
# cleanup
alembic downgrade base && docker rm -f ragsvc-dbCreate a document and its job in one transaction
The upload endpoint must never leave a document without a job. Step 1: the route gets a session from the dependency. Step 2: inside session.begin(), it adds both rows. Step 3: if the job insert fails, for example because of a constraint, the exception leaves the block and SQLAlchemy rolls back the document too. Step 4: only after the commit does the route return 202 with the job ID. Test it by forcing a failure, such as an invalid state value, and confirming that no document row was left behind.
@router.post("/documents", status_code=202)
async def create_document(
body: DocumentIn,
user: User = Depends(current_user),
session: AsyncSession = Depends(get_session),
):
doc = Document(tenant_id=user.tenant_id, owner_id=user.id, title=body.title)
job = Job(tenant_id=user.tenant_id, document=doc, state="queued")
async with session.begin():
session.add_all([doc, job])
return {"document_id": doc.id, "job_id": job.id}Quick reference
- Driver URL: postgresql+asyncpg://user:pass@host:5432/db
- async_sessionmaker(engine, expire_on_commit=False) for async code
- async with session.begin(): commits on success, rolls back on exception
- Pool defaults: pool_size=5, max_overflow=10, pool_timeout=30 seconds
- Connections = processes x (pool_size + max_overflow); keep under max_connections
- Use selectinload() for relationships; lazy loading raises in async code
- alembic revision --autogenerate -m "msg" drafts; you still review it
- CREATE INDEX CONCURRENTLY cannot run inside a transaction block
Common mistakes
- Sharing one AsyncSession between concurrent tasks; a session is not safe for concurrent use.
- Touching a lazy-loaded relationship after commit in async code, which raises an error instead of quietly loading; load what you need with selectinload.
- Running alembic revision --autogenerate and applying it without reading it; autogenerate misses some changes and can drop things you renamed.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a get_session dependency and a GET /documents route that lists the current tenant's documents, newest first, limited to 20.
- Exercise 2medium
Your database allows 100 connections and reserves 10 for admin. You run 4 API processes and 3 workers. Choose pool_size and max_overflow, and set a pool_timeout that makes overload visible.
- Exercise 3hard
Write an Alembic migration that adds a partial index on jobs (created_at) for queued jobs without locking the table against writes.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use SQLAlchemy, SQLModel or raw asyncpg?
- SQLAlchemy 2.0 gives typed models, transactions and Alembic migrations in one well-documented stack, which is why this path uses it. SQLModel builds on SQLAlchemy and Pydantic. Raw asyncpg is fastest but you write and maintain all SQL and migrations yourself.
- Why do I get MissingGreenlet errors?
- Something tried to run SQL implicitly, usually a lazy-loaded relationship or an expired attribute accessed after commit. Load relationships up front with selectinload, or set expire_on_commit=False.
- Should the app run alembic upgrade head when it starts?
- Not when several instances start at once, because they race each other. Run migrations once as a release step before the new version receives traffic, and keep the previous version compatible with the new schema.
- Can I use SQLite for local development instead?
- You can for quick experiments, but the course relies on PostgreSQL features such as partial indexes, SKIP LOCKED and pgvector. Run PostgreSQL in Docker locally so tests match production.