anantbhandarkar/make-it-right/mir-backend-python-fastapi
Claude Code and agent skill by anantbhandarkar/make-it-right
- community
Checking that the SKILL.md file is still in the repository.
Make It Right (FastAPI module). FastAPI + Starlette + Async SQLAlchemy 2.0 + Postgres + Alembic + Redis specific reliability augmentation. Use alongside the mir-backend skill when the target stack is FastAPI — it carries the mechanical footguns that the framework-agnostic skill deliberately omits: async session lifecycle and scope, engine creation in lifespan (on_event is deprecated), Pydantic v2 validation boundaries, Annotated[...]-based Depends() auth and object-level authorization, BackgroundTasks vs a real queue, async N+1 with selectinload, greenlet/sync-driver-in-async traps, Starlette threadpool saturation, Alembic migration safety on populated tables, Redis idempotency/locking patterns, and the 2026 Starlette advisory set (Host-header path poisoning, form-limit bypass, StaticFiles UNC). TRIGGER only when the Python backend stack is FastAPI — building, reviewing, or debugging a FastAPI endpoint, dependency, Starlette middleware, SQLAlchemy session, or Alembic migration. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-python (CPython runtime concerns: GIL, async/sync, fork-safety, cold start, packaging supply chain); this module only adds FastAPI/Starlette/SQLAlchemy library mechanics. SKIP for Django (mir-backend-python-django), Flask (mir-backend-python-flask), any other non-FastAPI stack, and non-Python runtimes.
Install
npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-python-fastapiSKILL.md
The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-python-fastapi.
/mir-backend-python-fastapi · Make It Right (FastAPI)
Bottom tier of the chain: mir-backend (generic gates) → mir-backend-python (CPython runtime model) → this (FastAPI/Starlette/SQLAlchemy library mechanics). Run the gates first; load the Python runtime tier for the concurrency/process model; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (GIL, async-vs-sync, blocking the event loop, fork-safe pools, cold start) live in `mir-backend-python` — not here.
Stack assumed, versions verified 13 Aug 2026: FastAPI 0.141.x (requires Python ≥3.10) · Starlette 1.6.x · Pydantic 2.13.x (there is no Pydantic v3) · SQLAlchemy 2.0.52 async (AsyncSession, asyncpg or psycopg 3) · PostgreSQL · Alembic 1.19.1 (requires Python ≥3.10) · Redis · Uvicorn 0.52.x. SQLAlchemy 2.1 is still in beta (2.1.0b3, June 2026) — 2.0.x is the production line; don't put a beta in a Gate 5 design without saying so. If the project uses sync SQLAlchemy or a different DB, note the divergence before applying these.
The FastAPI footguns AI walks into most
These are the stack-specific cousins of the failure-mode catalog. Each is something async-FastAPI code gets wrong even when the logic is right.
1. Async session lifecycle — the #1 source of mystery bugs
- One `AsyncSession` per request, via a `Depends` dependency. Never a module-level/global session — it's not concurrency-safe and you'll get cross-request data bleed or
InterfaceError. - Never share one session across `asyncio.gather` tasks. A session is a single connection's unit of work; concurrent use corrupts it. Give each task its own session from the factory.
- Commit/rollback boundary belongs in the dependency or service, explicitly — don't rely on autocommit.
expire_on_commit=Falseif you return ORM objects after commit, or you'll trigger lazy loads on detached instances. - The engine is per process, created in `lifespan`, disposed after `yield`. At import time it is built once per import, which under
gunicorn --preloadmeans the master builds the pool and every forked child inherits a corrupt copy.uvicorn --workersspawns rather than forks, so it escapes that specific bug — butlifespanis still the only place that gets the lifetime and thedispose()right. See the fork-safety table inmir-backend-python.
2. The async N+1 — worse than sync, because lazy loads raise
- In async SQLAlchemy, accessing an unloaded relationship outside a session raises
MissingGreenlet/DetachedInstanceError— it doesn't silently query. Eager-load withselectinload()/joinedload()in the query. AI routinely writesorder.itemsin a loop and ships an N+1 (or a crash). - Note for a 2.1 upgrade: greenlet becomes an optional dependency in SQLAlchemy 2.1. The failure mode does not go away; the exception you see on a missing async context may change.
3. Sync driver in the async path (the FastAPI face of a runtime rule)
- The general "don't block the event loop" rule lives in `mir-backend-python` (runtime tier). Here, the FastAPI/SQLAlchemy specifics: use an async driver —
postgresql+asyncpg://orpostgresql+psycopg://(psycopg 3, which also does sync) — withcreate_async_engine. Neverpsycopg2behind anasync def. Don't put a syncSessionbehind anasync defroute. - For unavoidable blocking work use Starlette's
run_in_threadpool, or define the route as plaindefso Starlette runs it in a threadpool automatically. - The threadpool is bounded. Starlette runs every plain-
defroute and everyrun_in_threadpoolcall on one AnyIO thread limiter (40 tokens by default). Convert a busy endpoint to plaindefand, past 40 concurrent calls, further requests queue on the limiter — the symptom is rising latency on unrelated sync endpoints with an idle CPU. Either keep hot paths async, or raise the limiter deliberately and size it against the DB pool.
4. Pydantic v2 is the boundary, not the security layer
- Validation ≠ authorization. A valid body can still be a request to mutate someone else's data.
- Mass assignment: never build an ORM object from
model_dump()blindly — use a separateCreate/Updateschema that excludesid,is_admin,tenant_id,role. Useresponse_model(or the route's return type annotation) to avoid leaking fields (password hashes, internal flags) on the way out. model_config = ConfigDict(extra="forbid")on input schemas to reject unexpected fields.extra="ignore"(the default) silently drops them, which hides a client bug until it becomes a data bug.
5. Depends() auth — get the chain right, and use the current syntax
- Authentication (
get_current_user) and authorization (does this user own this object?) are different dependencies. AI implements the first and forgets the second → IDOR. Object-level checks go in the path that loads the object, not just the route guard. - Current syntax is `Annotated`:
user: Annotated[User, Depends(get_current_user)], notuser=Depends(get_current_user). The default-argument form still works but is the pre-PEP-593 style;Annotatedlets you hoist a reusable alias (CurrentUser = Annotated[User, Depends(get_current_user)]) and keeps the signature honest for type checkers. Router- and app-leveldependencies=[...]lists still take a bareDepends(...). - Dependencies are cached per-request by default — fine, but don't put side effects in them expecting them to run twice.
6. BackgroundTasks is not a job queue
BackgroundTasksruns in the same process after the response; if the process dies, the work is lost — no retries, no durability. Fine for best-effort (a fire-and-forget log). Not fine for "send the receipt email" or anything that must happen. For durable/at-least-once work use a real queue (Celery/RQ/arq + Redis) with idempotent handlers. This is where the at-least-once/idempotency rule from the core skill lands in FastAPI.
7. Redis for idempotency & locking — the right primitives
- Idempotency key:
SET key result NX EX <ttl>—NXmakes "first writer wins" atomic. Store the result so a retry returns the same response, not a second side effect. - Distributed lock:
SET lock token NX EX <ttl>with a token you check before releasing (don't delete someone else's lock). Remember Redis locks are best-effort, not a correctness guarantee under failover — for money, prefer a DB row lock and use Redis only to reduce contention. - Cache stampede: on a cold popular key, N requests miss simultaneously → N DB hits. Use a short lock or
SET NXsentinel so one request rebuilds while others wait/serve stale.
8. Transactions in async SQLAlchemy
async with session.begin():for an explicit tx block. Irreversible external effects (charge, email) go after commit, guarded by the idempotency key — never inside the tx, because a rollback can't un-send an email.- Row lock for contended updates:
select(...).with_for_update()inside the tx. - Conditional UPDATE for state transitions:
update(Order).where(Order.id==id, Order.status=="PENDING").values(status="PAID")and checkrowcount— this makes concurrent transitions safe without a read-modify-write race.
9. Startup/shutdown: lifespan, not on_event
@app.on_event("startup"/"shutdown")is deprecated. Use an@asynccontextmanagerlifespan(app)passed asFastAPI(lifespan=lifespan): create the engine, Redis pool, and HTTP client beforeyield; dispose them after.- They are mutually exclusive and fail silently. If
lifespan=is set, everyon_eventhandler is ignored with no warning. A half-migrated app looks fine and never opens its Redis pool. Grep for both before you ship. lifespanruns only for the main app, not for sub-apps mounted withapp.mount(...). A mounted sub-app's resources never initialize.- Expose lifespan-created resources through a
Dependsprovider rather than reaching intorequest.statefrom route bodies — the dependency is testable and overridable.
10. Worker layout
gunicorn -k uvicorn.workers.UvicornWorkeris deprecated: theuvicorn.workersmodule moved out of Uvicorn. Install theuvicorn-workerpackage and useuvicorn_worker.UvicornWorker, or drop Gunicorn and runuvicorn --workers Nunder an orchestrator that already restarts processes.- Never set both. Passing
--workersto Uvicorn while it runs as a Gunicorn worker multiplies processes and quietly exhausts the DB pool. - Size the SQLAlchemy pool per worker process, not per service: total connections =
workers × (pool_size + max_overflow). This is the most common way a FastAPI service hits Postgresmax_connections.
Alembic migration safety
See references/alembic-migration-safety.md for the full expand/contract patterns. Headline rule: AI writes migrations as if the table is empty. It isn't. The migration-reviewer agent enforces this at Gate 7.
How this slots into the core pipeline
- Gate 5 (Design): when you state transaction boundaries and the idempotency mechanism, use the async-SQLAlchemy patterns above (session scope,
with_for_update, conditional UPDATE, Redis key shape). State the worker count and the resulting connection total. - Gate 6 (Implementation): code against
references/fastapi-gotchas.mdalongside the core codegen checklist. - Gate 7 (Review): the reliability-reviewer should additionally check items 1–10 here; the security-reviewer checks the Security section below; the migration-reviewer reads
references/alembic-migration-safety.md.
References
references/fastapi-gotchas.md— expanded code-level examples of the footguns above (right vs wrong).references/alembic-migration-safety.md— expand/contract, batched backfill,CONCURRENTLY,NOT VALIDthenVALIDATE, rolling-deploy compatibility.
Security
FastAPI/Starlette/SQLAlchemy mechanics. Runtime-level items (unsafe deserialization, archive extraction, shell arguments, packaging supply chain) are in mir-backend-python.
Current advisory set — pin Starlette yourself FastAPI 0.141.1's own metadata only requires starlette>=0.46.0. That floor is far below the patched releases, so a constraint anywhere else in the tree, or an old lockfile, silently gives you a vulnerable Starlette and nothing warns you. Put an explicit floor in your own requirements.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/mir-backend-python-fastapi/SKILL.md
Popularity
- Repository stars
- 15
- 7-day trend score
- 14
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-python-fastapi)