Skip to content
A single stream of light particles splitting into four separate lanes, one per API resource, each ending in a glowing node.
FastAPI

Structuring FastAPI Services That Survive Past the Prototype

By Faraz ShahJul 25, 20262 min read

FastAPI's pitch is real: type hints become validation, a Pydantic model becomes a request schema, and an OpenAPI doc appears for free. The part nobody warns you about is that this same speed makes it just as easy to end up with forty routes crammed into one main.py file.

Routers per resource, not one giant app instance

Splitting endpoints into an APIRouter per resource — users, orders, auth — and mounting each with app.include_router() keeps route files short enough to actually hold in your head. It also means two people can add endpoints to different resources without touching the same file.

Pydantic schemas are not your database models

Reusing a single Pydantic model for the database layer, the request body, and the response body works right up until you need a field that's writable on create but read-only on response — like an id or created_at. Separate Create, Update, and Read schemas per resource cost a bit of duplication but remove an entire category of accidental data leaks.

Dependency injection in FastAPI isn't just for auth checks — it's the cleanest place to put anything a route needs but shouldn't construct itself: a db session, a current user, a feature flag lookup.

Async all the way down, or not at all

Mixing a synchronous database driver into async def route handlers blocks the entire event loop on every query, which quietly erases the concurrency FastAPI is supposed to give you. Either commit to an async driver (asyncpg, motor) end to end, or use regular def routes and let FastAPI run them in a thread pool — but don't mix the two inside the same handler.

Background tasks aren't a job queue

FastAPI's BackgroundTasks is great for fire-and-forget work that can tolerate being lost on a server restart, like sending a confirmation email. Anything that needs retries, scheduling, or guaranteed delivery — payment webhooks, report generation — belongs in a real task queue like Celery or arq, not bolted onto the request/response cycle.

Keep reading

Related posts.

Rows of glowing lime dots on a dark background, with one dot left unlit below a threshold line.
RAG

6 min read

Your RAG Demo Needs a Failing Test

A new chunk size or prompt can quietly make answers worse, and nothing turns red. Here's how to make answer quality a merge check, with the harness from my open-source agent.

Read post
A glowing lime central node connected by thin lines to smaller nodes on a dark background.
AI Agents

6 min read

Your Agent Is Only as Safe as Its Tools

Model output is untrusted input. Lessons from building agent tool layers for legal and trading products: validation, scoping, step limits and citations you can trust.

Read post