Chapter 3 · Production FastAPI
Databases with SQLAlchemy and Alembic
- Page 10 of 22
- 28 min read
Until now the Prompt Library kept its data in a Python dictionary, which vanishes when the process restarts and is not shared between workers. A real AI backend stores prompts, users, conversations, evaluation results and usage records in a database, and changes the shape of that database every few weeks while the product is live. This page connects FastAPI to PostgreSQL with SQLAlchemy 2 (the ORM you met in SQL and Data Handling for AI: Advanced) and manages schema changes with Alembic, the migration tool from the same authors.
You will rebuild the prompt service on a database: models with relationships and constraints, one session per request, a repository, migrations you can apply and undo, honest error handling (a duplicate name is a 409, not a crash), pagination and filtering, and a separate test database.
What you will learn
- SQLAlchemy 2 models with foreign keys, relationships and database constraints, and why constraints beat "check first, then insert".
- One engine for the process, one session per request (a dependency), and a repository and service that own the transaction boundary.
- Alembic:
init,revision --autogenerate,upgrade,downgrade, and what autogenerate cannot see. - Rollbacks,
IntegrityErrorto409, the N+1 query problem, keyset pagination, filtering, connection pooling, sync versus async access. - A separate test database, PostgreSQL in deployment, and recaps of SQL injection and backups.
Set up: a project and two databases
This page uses PostgreSQL because that is what most production AI backends run (and what the Docker Compose page uses). Every example below runs against a real server. If you have none, start one with Docker:
docker run -d --name bitbyte-pg -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:18Then create the project. psycopg is the PostgreSQL driver (version 3); the [binary] extra bundles the C library it needs:
mkdir -p ~/projects/prompt-db/app ~/projects/prompt-db/tests
cd ~/projects/prompt-db
uv init --bare -q
uv add -q "fastapi[standard]" sqlalchemy alembic "psycopg[binary]"
uv add -q --dev pytest httpx2
# with pip: python -m venv .venv && source .venv/bin/activate && pip install -q "fastapi[standard]" sqlalchemy alembic "psycopg[binary]" pytest httpx2
touch app/__init__.py
cat >> pyproject.toml <<'EOF'
[tool.fastapi]
entrypoint = "app.main:app"
EOF
export DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/p10_prompts
echo okokThe last line exports the connection string the app will read (postgresql+psycopg:// selects the SQLAlchemy dialect and the psycopg 3 driver). On Windows PowerShell use $env:DATABASE_URL = "...". You need two databases: one for development and one that tests may wreck. The script drops and recreates both so you can repeat this page from the top (database names cannot be bound as parameters, so the script formats them into the SQL; that is safe only because the names are constants in your own code):
import psycopg
with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres", autocommit=True) as conn:
for name in ("p10_prompts", "p10_prompts_test"):
conn.execute(f"DROP DATABASE IF EXISTS {name} WITH (FORCE)")
conn.execute(f"CREATE DATABASE {name}")
rows = conn.execute("SELECT datname FROM pg_database WHERE datname LIKE 'p10%' ORDER BY 1")
print([row[0] for row in rows])['p10_prompts', 'p10_prompts_test']autocommit=True is needed because CREATE DATABASE cannot run inside a transaction.
Engine, session and models
Three objects do the work. The engine owns the connection pool and is created once per process. A session is a short-lived unit of work: it borrows a connection, tracks the objects you load and change, and sends SQL when you flush or commit. The models map Python classes to tables.
# file: app/db.py
"""Engine, session factory and the declarative base."""
import os
from collections.abc import Iterator
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
DATABASE_URL = os.environ["DATABASE_URL"] # no default: a missing setting should fail loudly
# Named constraints make migrations predictable and let us map errors to messages.
NAMING = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_N_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING)
engine = create_engine(DATABASE_URL, pool_size=5, max_overflow=5, pool_pre_ping=True)
SessionLocal = sessionmaker(engine, expire_on_commit=False)
def get_session() -> Iterator[Session]:
"""FastAPI dependency: one session per request, always closed, rolled back if not committed."""
with SessionLocal() as session:
yield session- The URL has the form
dialect+driver://user:password@host:port/database. Read it from the environment so the same code runs on your laptop, in CI and in production (the Settings class from the previous page is its tidy home). expire_on_commit=Falsekeeps loaded objects usable after a commit. By default SQLAlchemy expires them, and the next attribute access would silently run another query, which is surprising inside a response model.get_sessionis ayielddependency, like the ones from Dependencies, Lifespan, Middleware and Settings: leaving thewithblock closes the session and returns its connection to the pool. An uncommitted transaction is rolled back at that point, so a forgotten commit loses data but never leaves a half-finished change.
Now the data model. A prompt has many versions, and each version belongs to exactly one prompt:
# file: app/models.py
"""Tables: prompts (one row per name) and prompt_versions (one row per saved version)."""
from datetime import datetime
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db import Base
class Prompt(Base):
__tablename__ = "prompts"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(60), unique=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
versions: Mapped[list["PromptVersion"]] = relationship(
back_populates="prompt", order_by="PromptVersion.version",
cascade="all, delete-orphan", passive_deletes=True,
)
class PromptVersion(Base):
__tablename__ = "prompt_versions"
__table_args__ = (
UniqueConstraint("prompt_id", "version"),
CheckConstraint("temperature BETWEEN 0 AND 2", name="temperature_range"),
)
id: Mapped[int] = mapped_column(primary_key=True)
prompt_id: Mapped[int] = mapped_column(ForeignKey("prompts.id", ondelete="CASCADE"), index=True)
version: Mapped[int]
template: Mapped[str] = mapped_column(Text)
temperature: Mapped[float] = mapped_column(server_default="0.2")
prompt: Mapped[Prompt] = relationship(back_populates="versions")Notes on the choices:
Mapped[int]meansNOT NULL;Mapped[int | None]would be nullable. The annotation is the schema.- The foreign key
prompt_idmakes the database refuse a version that points at a missing prompt.ondelete="CASCADE"lets PostgreSQL delete a prompt's versions with it, andpassive_deletes=Truetells SQLAlchemy to trust that instead of loading every version first. - PostgreSQL does not index foreign keys automatically;
index=Truedoes, which makes "all versions of prompt 7" fast. - The
UNIQUEandCHECKconstraints hold whatever code writes the data: your API, a script, a colleague inpsql.
SQLModel combines Pydantic and SQLAlchemy in one class. This course keeps the ORM model (storage) and the Pydantic schema (API contract) apart: they change for different reasons, and the API should never expose a column by accident.
Alembic: the schema as code
Base.metadata.create_all() creates missing tables, but it never alters an existing one. The first time you add a column you need migrations: small, ordered, versioned scripts that move a database from one schema to the next, kept in Git next to the code. Alembic records the current version in a table called alembic_version.
uv run alembic init migrations > /dev/null
ls
ls migrationsalembic.ini
app
migrations
pyproject.toml
tests
uv.lock
README
env.py
script.py.mako
versionsEdit only migrations/env.py. It must know your models (so autogenerate can compare them with the database) and your database URL. Replace its contents with this shorter version:
# file: migrations/env.py
from logging.config import fileConfig
from alembic import context
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from app import models # noqa: F401 (importing registers the tables on Base.metadata)
from app.db import DATABASE_URL, Base
config = context.config
fileConfig(config.config_file_name, disable_existing_loggers=False)
engine = create_engine(DATABASE_URL, poolclass=NullPool)
with engine.connect() as connection:
context.configure(connection=connection, target_metadata=Base.metadata, compare_type=True)
with context.begin_transaction():
context.run_migrations()Now generate the first migration by comparing the (empty) database with your models:
export QUIET='Context impl|transactional DDL|autogenerate plugin|Detected sequence'
uv run alembic revision --autogenerate -m "create prompts and versions" --rev-id 0001 2>&1 | grep -vE "$QUIET"
sed -n '/^def upgrade/,/^def downgrade/{/^def downgrade/!p}' migrations/versions/0001_*.pyINFO [alembic.autogenerate.compare.tables] Detected added table 'prompts'
INFO [alembic.autogenerate.compare.tables] Detected added table 'prompt_versions'
INFO [alembic.autogenerate.compare.constraints] Detected added index 'ix_prompt_versions_prompt_id' on '('prompt_id',)'
Generating /home/nadia/projects/prompt-db/migrations/versions/0001_create_prompts_and_versions.py ... done
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('prompts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=60), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_prompts')),
sa.UniqueConstraint('name', name=op.f('uq_prompts_name'))
)
op.create_table('prompt_versions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('prompt_id', sa.Integer(), nullable=False),
sa.Column('version', sa.Integer(), nullable=False),
sa.Column('template', sa.Text(), nullable=False),
sa.Column('temperature', sa.Double(), server_default='0.2', nullable=False),
sa.CheckConstraint('temperature BETWEEN 0 AND 2', name=op.f('ck_prompt_versions_temperature_range')),
sa.ForeignKeyConstraint(['prompt_id'], ['prompts.id'], name=op.f('fk_prompt_versions_prompt_id_prompts'), ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_prompt_versions')),
sa.UniqueConstraint('prompt_id', 'version', name=op.f('uq_prompt_versions_prompt_id_version'))
)
op.create_index(op.f('ix_prompt_versions_prompt_id'), 'prompt_versions', ['prompt_id'], unique=False)
# ### end Alembic commands ###Alembic logs through Python's logging module to stderr, which is why the command line has 2>&1; the grep only hides startup chatter that differs between Alembic versions. Always read the generated file before you run it. Autogenerate is a draft written by a program, not a promise. It detects added and dropped tables and columns, changed types (because of compare_type=True), nullability, constraints and indexes. It does not detect a renamed column or table (it sees a drop plus an add, which would destroy data), and it knows nothing about data. For those, edit the migration by hand (op.alter_column(..., new_column_name=...), op.execute("UPDATE ...")).
uv run alembic upgrade head 2>&1 | grep -vE "$QUIET"
uv run alembic current 2>&1 | grep -vE "$QUIET"INFO [alembic.runtime.migration] Running upgrade -> 0001, create prompts and versions
0001 (head)Schemas change. Add an owner column to prompts, with a server default so existing rows stay valid, and let Alembic notice:
sed -i '/created_at: Mapped/a\ owner: Mapped[str] = mapped_column(String(60), server_default="team")' app/models.py
uv run alembic revision --autogenerate -m "add prompt owner" --rev-id 0002 2>&1 | grep -vE "$QUIET"
grep -h 'op\.' migrations/versions/0002_*.pyINFO [alembic.autogenerate.compare.tables] Detected added column 'prompts.owner'
Generating /home/nadia/projects/prompt-db/migrations/versions/0002_add_prompt_owner.py ... done
op.add_column('prompts', sa.Column('owner', sa.String(length=60), server_default='team', nullable=False))
op.drop_column('prompts', 'owner')Migrations are reversible. Apply it, roll back one step, look around, and go forward again:
uv run alembic upgrade head 2>&1 | grep -vE "$QUIET"
uv run alembic downgrade -1 2>&1 | grep -vE "$QUIET"
uv run alembic current 2>&1 | grep -vE "$QUIET"
uv run alembic upgrade head 2>&1 | grep -vE "$QUIET"
uv run alembic history 2>&1 | grep -vE "$QUIET"INFO [alembic.runtime.migration] Running upgrade 0001 -> 0002, add prompt owner
INFO [alembic.runtime.migration] Running downgrade 0002 -> 0001, add prompt owner
0001
INFO [alembic.runtime.migration] Running upgrade 0001 -> 0002, add prompt owner
0001 -> 0002 (head), add prompt owner
<base> -> 0001, create prompts and versionsThe commands you will use daily: revision --autogenerate -m "..." writes a draft, upgrade head applies everything pending (run it at every deploy), downgrade -1 undoes the last step, current and history show where you are, and upgrade head --sql prints the SQL for review instead of running it (it needs an offline branch in env.py).
Rules that save careers: never edit a migration that has already been applied anywhere shared (add a new one); commit migrations together with the model change that needs them; and treat downgrade as a convenience for development, because a production rollback that drops a column also drops its data. Adding a NOT NULL column to a big table needs a default or a multi-step migration (add nullable, backfill, then set NOT NULL).
Schemas, repository and service
The API contract stays in Pydantic, as in FastAPI Architecture: Routers, Schemas and Error Handling. A from_prompt constructor turns an ORM object into the public shape:
# file: app/schemas.py
from pydantic import BaseModel, ConfigDict, Field
from app.models import Prompt
class PromptIn(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
name: str = Field(min_length=3, max_length=60, pattern=r"^[a-z0-9-]+$")
template: str = Field(min_length=1, max_length=4000)
temperature: float = Field(default=0.2, ge=0, le=2)
class PromptOut(BaseModel):
id: int
name: str
version: int
template: str
temperature: float
@classmethod
def from_prompt(cls, prompt: Prompt) -> "PromptOut":
latest = prompt.versions[-1]
return cls(id=prompt.id, name=prompt.name, version=latest.version,
template=latest.template, temperature=latest.temperature)
class PromptPage(BaseModel):
items: list[PromptOut]
next_cursor: int | NoneThe repository is the only code that writes queries. It never commits: it stages changes with flush(), which sends the SQL (so constraint errors appear now, and generated ids are filled in) but keeps the transaction open:
# file: app/repository.py
from collections.abc import Sequence
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload
from app.models import Prompt, PromptVersion
class PromptRepository:
def __init__(self, session: Session) -> None:
self.session = session
def get(self, prompt_id: int) -> Prompt | None:
return self.session.get(Prompt, prompt_id)
def add(self, name: str, template: str, temperature: float) -> Prompt:
prompt = Prompt(name=name, versions=[PromptVersion(version=1, template=template, temperature=temperature)])
self.session.add(prompt)
self.session.flush()
return prompt
def add_version(self, prompt: Prompt, template: str, temperature: float) -> PromptVersion:
version = PromptVersion(version=prompt.versions[-1].version + 1, template=template, temperature=temperature)
prompt.versions.append(version)
self.session.flush()
return version
def list(self, *, q: str | None = None, after_id: int = 0, limit: int = 20) -> Sequence[Prompt]:
stmt = (select(Prompt).options(selectinload(Prompt.versions))
.where(Prompt.id > after_id).order_by(Prompt.id).limit(limit))
if q:
stmt = stmt.where(Prompt.name.icontains(q, autoescape=True))
return self.session.scalars(stmt).all()
The service owns the transaction: it decides when to commit() and what to do when the database says no. It raises the same kind of AppErrors as the architecture page, defined here in miniature:
# file: app/service.py
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.models import Prompt
from app.repository import PromptRepository
from app.schemas import PromptIn
class AppError(Exception):
status_code = 400
code = "bad_request"
class NotFound(AppError):
status_code = 404
code = "not_found"
class Conflict(AppError):
status_code = 409
code = "conflict"
CONFLICTS = {
"uq_prompts_name": "A prompt with this name already exists",
"uq_prompt_versions_prompt_id_version": "Another request saved a new version first; reload and try again",
}
def conflict_message(exc: IntegrityError) -> str:
constraint = getattr(getattr(exc.orig, "diag", None), "constraint_name", None)
return CONFLICTS.get(constraint, "The change conflicts with existing data")
class PromptService:
def __init__(self, session: Session) -> None:
self.session = session
self.repo = PromptRepository(session)
def get(self, prompt_id: int) -> Prompt:
prompt = self.repo.get(prompt_id)
if prompt is None:
raise NotFound(f"Prompt {prompt_id} not found")
return prompt
def create(self, data: PromptIn) -> Prompt:
try:
prompt = self.repo.add(data.name, data.template, data.temperature)
self.session.commit()
except IntegrityError as exc:
self.session.rollback()
raise Conflict(conflict_message(exc)) from exc
return prompt
def new_version(self, prompt_id: int, data: PromptIn) -> Prompt:
prompt = self.get(prompt_id)
if data.name != prompt.name:
raise Conflict("The name of a prompt cannot change; create a new prompt instead")
try:
self.repo.add_version(prompt, data.template, data.temperature)
self.session.commit()
except IntegrityError as exc:
self.session.rollback()
raise Conflict(conflict_message(exc)) from exc
return prompt
def list(self, *, q: str | None, cursor: int, limit: int) -> tuple[list[Prompt], int | None]:
rows = list(self.repo.list(q=q, after_id=cursor, limit=limit + 1))
page = rows[:limit]
return page, (page[-1].id if len(rows) > limit else None)Note the order: try the write, let the database reject it, translate the error. The tempting alternative, "check whether the name exists, then insert", has a race: two requests can both see "no such name" and both insert. Only the unique constraint is race-proof, so keep the constraint and treat any application-level check as a nicety.
Finally the routes, thin as before. The service comes from a dependency that depends on the session dependency, so the whole chain is built per request and can be replaced in tests:
# file: app/main.py
from typing import Annotated
from fastapi import Depends, FastAPI, Path, Query, Request, status
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from app.db import get_session
from app.schemas import PromptIn, PromptOut, PromptPage
from app.service import AppError, PromptService
SessionDep = Annotated[Session, Depends(get_session)]
def get_service(session: SessionDep) -> PromptService:
return PromptService(session)
ServiceDep = Annotated[PromptService, Depends(get_service)]
PromptId = Annotated[int, Path(ge=1)]
def create_app() -> FastAPI:
app = FastAPI(title="BitByte Prompt Library (database edition)")
@app.exception_handler(AppError)
async def handle_app_error(request: Request, exc: AppError) -> JSONResponse:
body = {"error": {"code": exc.code, "message": str(exc), "details": None}}
return JSONResponse(body, status_code=exc.status_code)
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok"}
@app.get("/v1/prompts")
def list_prompts(
service: ServiceDep,
q: Annotated[str | None, Query(max_length=60, description="Name contains this text")] = None,
cursor: Annotated[int, Query(ge=0, description="next_cursor from the previous page")] = 0,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
) -> PromptPage:
rows, next_cursor = service.list(q=q, cursor=cursor, limit=limit)
return PromptPage(items=[PromptOut.from_prompt(row) for row in rows], next_cursor=next_cursor)
@app.post("/v1/prompts", status_code=status.HTTP_201_CREATED)
def create_prompt(data: PromptIn, service: ServiceDep) -> PromptOut:
return PromptOut.from_prompt(service.create(data))
@app.get("/v1/prompts/{prompt_id}")
def get_prompt(prompt_id: PromptId, service: ServiceDep) -> PromptOut:
return PromptOut.from_prompt(service.get(prompt_id))
@app.put("/v1/prompts/{prompt_id}", summary="Save a new version of a prompt")
def update_prompt(prompt_id: PromptId, data: PromptIn, service: ServiceDep) -> PromptOut:
return PromptOut.from_prompt(service.new_version(prompt_id, data))
return app
app = create_app()The route functions are plain def: SQLAlchemy's synchronous API blocks while it waits for PostgreSQL, so FastAPI runs them in its thread pool, which is exactly right (more in the sync-versus-async section below).
Transactions and rollbacks
A transaction makes several statements succeed or fail together. A session starts one automatically when it first talks to the database; commit() makes the changes permanent and rollback() throws them away. Watch it with two separate sessions, because another connection can only see committed data:
from sqlalchemy import func, select
from app.db import SessionLocal
from app.models import Prompt, PromptVersion
def count(session):
return session.scalar(select(func.count()).select_from(Prompt))
with SessionLocal() as session, SessionLocal() as observer:
session.add(Prompt(name="draft", versions=[PromptVersion(version=1, template="Draft: {input}")]))
session.flush() # INSERT is sent, the transaction is still open
print("writer sees:", count(session), "| observer sees:", count(observer))
session.rollback()
print("after rollback:", count(session))writer sees: 1 | observer sees: 0
after rollback: 0That "all or nothing" property is why a prompt and its first version are saved together. Make the second half fail on purpose, with a temperature that violates the database CHECK, and see that the first half disappears too:
from sqlalchemy.exc import IntegrityError
with SessionLocal() as session:
try:
session.add(Prompt(name="atomic", versions=[
PromptVersion(version=1, template="fine {input}", temperature=0.2),
PromptVersion(version=2, template="broken {input}", temperature=9),
]))
session.commit()
except IntegrityError as exc:
session.rollback()
print(type(exc.orig).__name__, "-", exc.orig.diag.constraint_name)
print("prompts saved:", count(session))CheckViolation - ck_prompt_versions_temperature_range
prompts saved: 0- After an error the session is in a failed state: call
rollback()before using it again. Thewithblock does that on exit, and the service does it explicitly before re-raising. - Keep transactions short. Never call an LLM or an external API between the first write and the commit: you would hold row locks and a pooled connection for seconds.
with session.begin():commits on success and rolls back on an exception;session.begin_nested()makes a savepoint so one part can fail alone.- Failed inserts still consume sequence numbers. Ids are unique, not gap-free; never treat them as a count or promise a client they are consecutive.
Constraints and the 409
Pydantic validates what the API receives; database constraints protect the data from every writer and from races. Use both. Here a duplicate name hits UNIQUE, and two writers racing to save the next version hit the (prompt_id, version) constraint:
with SessionLocal() as session:
first = Prompt(name="support-answer", versions=[PromptVersion(version=1, template="Answer: {input}")])
second = Prompt(name="summarise", versions=[PromptVersion(version=1, template="Summarise: {input}")])
session.add_all([first, second])
session.commit()
prompt_id = first.id
with SessionLocal() as session:
session.add(Prompt(name="support-answer"))
try:
session.commit()
except IntegrityError as exc:
session.rollback()
print("duplicate name:", exc.orig.sqlstate, exc.orig.diag.constraint_name)
with SessionLocal() as a, SessionLocal() as b:
next_a = len(a.get(Prompt, prompt_id).versions) + 1 # both writers read "version 1 is the latest"
next_b = len(b.get(Prompt, prompt_id).versions) + 1
a.add(PromptVersion(prompt_id=prompt_id, version=next_a, template="A saves first {input}"))
a.commit()
b.add(PromptVersion(prompt_id=prompt_id, version=next_b, template="B arrives late {input}"))
try:
b.commit()
except IntegrityError as exc:
b.rollback()
print("second writer:", exc.orig.sqlstate, exc.orig.diag.constraint_name)duplicate name: 23505 uq_prompts_name
second writer: 23505 uq_prompt_versions_prompt_id_versionSQLSTATE 23505 is "unique violation", 23503 "foreign key violation", 23502 "not null violation" and 23514 "check violation": stable codes you can branch on, unlike message text. The service maps constraint names to friendly messages and raises Conflict, which the handler turns into 409. A 409 Conflict means "your request is valid, but it clashes with the current state". Malformed input stays a 422 (from Pydantic) and a missing row a 404; an IntegrityError you did not expect should become a logged 500, not a leaked database message.
Relationships and the N+1 problem
prompt.versions looks like a plain list, but the first access runs a query (lazy loading). Loop over 50 prompts and touch .versions on each, and you run 1 query for the prompts plus 50 more: the N+1 problem, the most common ORM performance bug. Count the statements with an event listener:
from sqlalchemy import event
from sqlalchemy.orm import selectinload
from app.db import engine
statements = []
@event.listens_for(engine, "before_cursor_execute")
def record(conn, cursor, statement, parameters, context, executemany):
statements.append(statement)
def load(*options):
statements.clear()
with SessionLocal() as session:
prompts = session.scalars(select(Prompt).options(*options)).all()
versions = sum(len(prompt.versions) for prompt in prompts)
return f"{len(prompts)} prompts, {versions} versions, {len(statements)} statements"
print("lazy: ", load())
print("selectinload:", load(selectinload(Prompt.versions)))lazy: 2 prompts, 3 versions, 3 statements
selectinload: 2 prompts, 3 versions, 2 statementsselectinload fetches the versions of all loaded prompts in one extra query (WHERE prompt_id IN (...)), so the count stays at 2 however many prompts there are. The repository's list already uses it. For a many-to-one link (a version's prompt) joinedload does the same with a JOIN. Decide the loading strategy in the repository query, where you know what the caller needs, not by accident in a serializer.
Run it
uv run fastapi run --port 8000 > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status":"ok"}support-answer and summarise were created by the scripts above, so the server already sees them. Create another, then provoke the errors (the -w option prints the status code after each body):
curl -s -w ' %{http_code}\n' -X POST http://localhost:8000/v1/prompts -H 'Content-Type: application/json' \
-d '{"name": "classify-ticket", "template": "Classify this ticket: {input}", "temperature": 0}'
curl -s -w ' %{http_code}\n' -X POST http://localhost:8000/v1/prompts -H 'Content-Type: application/json' \
-d '{"name": "summarise", "template": "Another summariser"}'
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8000/v1/prompts -H 'Content-Type: application/json' \
-d '{"name": "bad-temp", "template": "x", "temperature": 5}'
curl -s -w ' %{http_code}\n' -X PUT http://localhost:8000/v1/prompts/3 -H 'Content-Type: application/json' \
-d '{"name": "support-answer", "template": "Answer politely: {input}"}'
curl -s -w ' %{http_code}\n' http://localhost:8000/v1/prompts/999{"id":6,"name":"classify-ticket","version":1,"template":"Classify this ticket: {input}","temperature":0.0} 201
{"error":{"code":"conflict","message":"A prompt with this name already exists","details":null}} 409
422
{"id":3,"name":"support-answer","version":3,"template":"Answer politely: {input}","temperature":0.2} 200
{"error":{"code":"not_found","message":"Prompt 999 not found","details":null}} 404The PUT produced version 3 because the race demo above already saved version 2. Look at the id of classify-ticket: the failed and rolled-back inserts earlier used up ids, so support-answer is 3 and the new prompt is 6. Note also that the out-of-range temperature was stopped by Pydantic (422) before reaching the database. The CHECK constraint is the second line of defence for every other writer.
Pagination and filtering
LIMIT 20 OFFSET 100000 makes PostgreSQL read and discard 100,000 rows, and shifts whenever rows are inserted. The route uses keyset (cursor) pagination instead, the better design from Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning: WHERE id > :cursor ORDER BY id LIMIT :n jumps straight to the right place using the primary-key index. Fetching limit + 1 rows tells us whether another page exists without a second COUNT query. Filters are optional WHERE clauses added to the same statement:
curl -s 'http://localhost:8000/v1/prompts?limit=2' | python -m json.tool | grep -E '"(name|version|next_cursor)"'
echo ---
curl -s 'http://localhost:8000/v1/prompts?limit=2&cursor=4' | python -m json.tool | grep -E '"(name|version|next_cursor)"'
echo ---
curl -s 'http://localhost:8000/v1/prompts?q=SUM' | python -c "import sys, json; print([p['name'] for p in json.load(sys.stdin)['items']])" "name": "support-answer",
"version": 3,
"name": "summarise",
"version": 1,
"next_cursor": 4
---
"name": "classify-ticket",
"version": 1,
"next_cursor": null
---
['summarise']The name filter is case-insensitive (icontains becomes ILIKE) and uses autoescape=True, so a user who types % or _ searches for those characters instead of getting wildcards. To page by something other than id (newest first, a score), order by that column plus id as a tie-breaker and encode both in an opaque cursor.
kill "$SERVER_PID"Connection pooling
Opening a PostgreSQL connection costs milliseconds and a server process; doing it per request would be slow and would exhaust the server. The engine keeps a pool of open connections and lends one to each session. Three settings matter: pool_size (connections kept open), max_overflow (extra connections allowed under load) and pool_timeout (how long a request waits for a free one). Make the limit visible with a tiny pool:
from sqlalchemy import create_engine, text
from sqlalchemy.exc import TimeoutError as PoolTimeout
from app.db import DATABASE_URL
small = create_engine(DATABASE_URL, pool_size=2, max_overflow=0, pool_timeout=1)
first, second = small.connect(), small.connect()
print(small.pool.status())
try:
small.connect()
except PoolTimeout as exc:
print(str(exc).split(" (")[0])
first.close()
with small.connect() as connection: # a connection was returned, so this works
print(connection.execute(text("SELECT 'served'")).scalar())
second.close()
small.dispose()Pool size: 2 Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 2
QueuePool limit of size 2 overflow 0 reached, connection timed out, timeout 1.00
served- PostgreSQL allows a limited number of connections (100 by default). Every API process has its own pool, so the worst case is
workers x (pool_size + max_overflow)across all instances. Keep it below the server limit, or put PgBouncer in front. pool_pre_ping=Truetests a connection before lending it, so a database restart does not cost one error per pooled connection.pool_recycle=1800replaces connections that firewalls close silently.
Sync or async?
Everything above is synchronous, and that is a sensible default: simple, well documented and fast enough for most services. Choose async SQLAlchemy when routes also await other things (LLM calls, HTTP clients, Redis) and one process should hold thousands of waiting requests. With psycopg 3 the same URL works for both; create_async_engine picks the async flavour:
import asyncio
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
async def main() -> None:
async_engine = create_async_engine(DATABASE_URL)
async_session = async_sessionmaker(async_engine, expire_on_commit=False)
async with async_session() as session:
stmt = select(Prompt).options(selectinload(Prompt.versions)).order_by(Prompt.id)
prompts = (await session.scalars(stmt)).all()
print([(prompt.name, len(prompt.versions)) for prompt in prompts])
await async_engine.dispose()
asyncio.run(main())[('support-answer', 3), ('summarise', 1), ('classify-ticket', 1)]This prints each prompt name with its number of versions. Async SQLAlchemy needs the greenlet package, so install "sqlalchemy[asyncio]" to try it. The rules change in three ways. Every database call is awaited. Lazy loading is impossible (an attribute access cannot be awaited), so load relationships up front with selectinload, as above, or SQLAlchemy raises MissingGreenlet. And never run the sync API inside an async def route, because that blocks the event loop for everyone. Do not mix styles within one service: a sync engine with def routes, or an async engine with async def routes.
A separate test database
Tests that delete and recreate rows must never touch your development data, and certainly not production. Use a second database (you created p10_prompts_test above), point the app at it through the DATABASE_URL environment variable when you start pytest, build its schema with the real migrations (so the migrations are tested too), and empty the tables after each test. Add a guard that refuses to run against anything not named _test:
# file: tests/conftest.py
import os
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from sqlalchemy import text
from app.db import DATABASE_URL, engine
from app.main import create_app
assert DATABASE_URL.endswith("_test"), "refusing to run tests against a non-test database"
@pytest.fixture(scope="session", autouse=True)
def schema():
command.upgrade(Config("alembic.ini"), "head") # the real migrations build the test schema
yield
engine.dispose()
@pytest.fixture(autouse=True)
def empty_tables():
yield
with engine.begin() as connection:
connection.execute(text("TRUNCATE prompts RESTART IDENTITY CASCADE"))
@pytest.fixture
def client():
with TestClient(create_app()) as test_client:
yield test_client# file: tests/test_prompts.py
BODY = {"name": "support-answer", "template": "Answer: {input}"}
def test_duplicate_name_is_a_409(client):
assert client.post("/v1/prompts", json=BODY).status_code == 201
duplicate = client.post("/v1/prompts", json=BODY)
assert duplicate.status_code == 409
assert duplicate.json()["error"]["code"] == "conflict"
def test_cursor_pagination_and_clean_state(client):
for number in range(3):
client.post("/v1/prompts", json={**BODY, "name": f"prompt-{number}"})
page = client.get("/v1/prompts?limit=2").json()
assert [item["id"] for item in page["items"]] == [1, 2] # ids restart: the tables were emptied
assert page["next_cursor"] == 2
assert client.get("/v1/prompts?limit=2&cursor=2").json()["next_cursor"] is NoneDATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/p10_prompts_test uv run python -m pytest -q 2>&1 | tail -3.. [100%]
2 passed in 0.21sTruncating tables after every test is simple but slow for large suites. Testing Professional APIs shows the faster pattern: run each test inside a transaction (or savepoint) and roll it back, and replace get_session with app.dependency_overrides.
SQL injection: a recap
The ORM and Core build queries with bound parameters, so user input is always data, never SQL. The danger returns when you build SQL text yourself. Compare a hostile search term against the rows now in the development database:
from sqlalchemy import text
evil = "x' OR '1'='1"
with engine.connect() as connection:
unsafe = connection.execute(text(f"SELECT name FROM prompts WHERE name = '{evil}'")).all()
safe = connection.execute(text("SELECT name FROM prompts WHERE name = :name"), {"name": evil}).all()
orm = connection.execute(select(Prompt.name).where(Prompt.name == evil)).all()
print("f-string:", len(unsafe), "rows | bound parameter:", len(safe), "rows | ORM:", len(orm), "rows")f-string: 3 rows | bound parameter: 0 rows | ORM: 0 rowsThe f-string version returned every prompt: the quote closed the string and OR '1'='1' became part of the query. Rules: never format user input into text(), execute() or raw SQL (use :name parameters); identifiers such as table or column names cannot be bound, so choose them from an allow-list; and give the application's database user only the rights it needs. SQL and Data Handling for AI: Advanced covers this in depth, and API Security and the OWASP API Top 10 returns to it.
PostgreSQL in deployment
SQLite is perfect for a single-process script. A deployed API with several workers or containers needs a real server, and the one you have been using here is the engine to deploy on:
| Concern | What to do |
|---|---|
| Connection string | One DATABASE_URL environment variable from the host's secret store. Hosts often give postgres://... or postgresql://...; SQLAlchemy needs postgresql+psycopg://..., so rewrite the prefix in your settings code. |
| Migrations | Run alembic upgrade head once per deploy, as a release step or a one-off container before the new version starts, never from every worker at startup (they would race). |
| Pool size | Add up the pools of every process and keep the total under max_connections; small managed plans allow only a few dozen. |
| Compatibility | Ship migrations that the old code can still run against (add a column before using it, drop it one release later) so a rolling deploy never breaks. |
| Free tiers | Free managed Postgres is time-limited at several hosts (Render's expires after 30 days). Check current limits. |
The Docker Compose page runs this API next to a PostgreSQL container with a health-checked start order, and the deployment page applies migrations on deploy.
Backups: a recap
A database without a tested restore is a hope, not a backup. The tools from SQL and Data Handling for AI: Advanced apply unchanged: a logical dump with pg_dump for small databases and moves between servers, and the host's automatic snapshots with point-in-time recovery for production.
pg_dump --format=custom --file=prompts.dump "$DATABASE_URL" # back up (use a plain postgresql:// URL here)
createdb prompts_restore_check
pg_restore --dbname=prompts_restore_check prompts.dump # restore into a scratch database, then look insideSchedule it, keep copies away from the database server, and rehearse the restore.
Where this shows up in AI work
- Conversation and usage storage: messages, token counts and costs per user are rows in tables like these, with foreign keys to users and indexes on the columns you filter by.
- Evaluation results: a unique constraint on
(prompt_version_id, dataset_id)means re-running an evaluation cannot double-count. - Job and ingestion state: "document 42 is embedded" lives in PostgreSQL, and with the
pgvectorextension the vectors can too.
Common mistakes
- One global session shared by all requests. Sessions are not thread-safe and keep a transaction open for ever. Create one per request through a dependency.
- Check-then-insert instead of a constraint. Two concurrent requests both pass the check. Add the
UNIQUEconstraint and handleIntegrityError. - Editing the database by hand, or calling
create_all()in production. Environments drift apart. Change the models, generate a migration, review it, apply it. - Running an LLM call inside a transaction. Locks and connections are held for seconds and the pool runs dry. Call the model first, then write the result in a short transaction.
- N+1 queries and unbounded lists. Load relationships with
selectinload, always paginate with a maximumlimit, and index the columns you filter and join on.
Try it yourself
- Easy: with one SQLAlchemy query, print each prompt's name and how many versions it has (use a
JOINandGROUP BY). - Medium: add a service method
restore(prompt_id, version)that saves an old version's template as a new latest version. RaiseNotFoundif that version does not exist. Check it with a short Python script. - Hard: write a test that sends
?q=%25(a literal%) and proves the filter does not treat it as a wildcard, then run it on the test database.
Answers
# 1. Easy
with SessionLocal() as session:
stmt = (select(Prompt.name, func.count(PromptVersion.id))
.join(PromptVersion).group_by(Prompt.name).order_by(Prompt.name))
for name, versions in session.execute(stmt):
print(name, versions)
# 2. Medium
from app.schemas import PromptIn
from app.service import NotFound, PromptService
def restore(service: PromptService, prompt_id: int, version: int):
prompt = service.get(prompt_id)
old = next((v for v in prompt.versions if v.version == version), None)
if old is None:
raise NotFound(f"Prompt {prompt_id} has no version {version}")
return service.new_version(prompt_id, PromptIn(name=prompt.name, template=old.template,
temperature=old.temperature))
with SessionLocal() as session:
service = PromptService(session)
restored = restore(service, prompt_id, 1)
print([(v.version, v.template) for v in restored.versions])
try:
restore(service, prompt_id, 9)
except NotFound as exc:
print("NotFound:", exc)classify-ticket 1
summarise 1
support-answer 3
[(1, 'Answer: {input}'), (2, 'A saves first {input}'), (3, 'Answer politely: {input}'), (4, 'Answer: {input}')]
NotFound: Prompt 3 has no version 9# file: tests/test_filter.py
def test_percent_is_not_a_wildcard(client):
client.post("/v1/prompts", json={"name": "support-answer", "template": "x {input}"})
assert client.get("/v1/prompts?q=%25").json()["items"] == []
assert len(client.get("/v1/prompts?q=SUPPORT").json()["items"]) == 1DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/p10_prompts_test uv run python -m pytest -q 2>&1 | tail -3... [100%]
3 passed in 0.40sWhen you are finished, drop the practice databases with DROP DATABASE p10_prompts WITH (FORCE) (and the same for p10_prompts_test).
Summary
- Create one engine per process and one session per request through a
yielddependency; keep queries in a repository and the commit/rollback decision in a service. - Model relationships with foreign keys and let the database enforce
UNIQUE,CHECKandNOT NULL; translateIntegrityErrorinto409instead of check-then-insert. - Manage schema changes with Alembic: autogenerate, read, apply with
upgrade headon every deploy, and remember it cannot see renames. - Avoid N+1 with
selectinload, paginate with keyset cursors, escape filters, size the pool against the server's connection limit, and keep one style (sync or async) per service. - Test on a separate database built by the real migrations, always use bound parameters, and rehearse restoring a backup.
Next: Authentication and Authorisation adds users to this database: password hashing, JWT access and refresh tokens, protected routes and permissions.

