Python Backend
Patterns for building production Python backends with asyncio, FastAPI, SQLAlchemy 2.0, and connection pooling. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category |
Rules |
Impact |
When to Use |
| Asyncio |
3 |
HIGH |
TaskGroup, structured concurrency, cancellation handling |
| FastAPI |
3 |
HIGH |
Dependencies, middleware, background tasks |
| SQLAlchemy |
3 |
HIGH |
Async sessions, relationships, migrations |
| Pooling |
3 |
MEDIUM |
Database pools, HTTP sessions, tuning |
Total: 12 rules across 4 categories. House decisions rescued from thinned files live in references/ork-delta.md; vendor material is linked, not restated (see Upstream coverage).
Quick Start
# FastAPI + SQLAlchemy async session
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
# Reusable dependency alias (FastAPI's recommended Annotated form)
SessionDep = Annotated[AsyncSession, Depends(get_db)]
@router.get("/users/{user_id}")
async def get_user(user_id: UUID, db: SessionDep):
result = await db.execute(select(User).where(User.id == user_id))
return result.scalar_one_or_none()
# Asyncio TaskGroup with timeout
async def fetch_all(urls: list[str]) -> list[dict]:
async with asyncio.timeout(30):
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch_url(url)) for url in urls]
return [t.result() for t in tasks]
Asyncio
Modern Python asyncio patterns using structured concurrency, TaskGroup, and Python 3.11+ features.
Key Patterns
- TaskGroup replaces
gather() with structured concurrency and auto-cancellation
asyncio.timeout() context manager for composable timeouts
- Semaphore for concurrency limiting (rate-limit HTTP requests)
except* with ExceptionGroup for handling multiple task failures
asyncio.to_thread() for bridging sync code to async
Key Decisions
| Decision |
Recommendation |
| Task spawning |
TaskGroup not gather() |
| Timeouts |
asyncio.timeout() context manager |
| Concurrency limit |
asyncio.Semaphore |
| Sync bridge |
asyncio.to_thread() |
| Cancellation |
Always re-raise CancelledError |
FastAPI
Production-ready FastAPI patterns for lifespan, dependencies, middleware, and settings.
Key Patterns
- Lifespan with
asynccontextmanager for startup/shutdown resource management
- Dependency injection with class-based services and
Depends()
- Middleware stack: CORS -> RequestID -> Timing -> Logging
- Pydantic Settings with
.env and field validation
- Exception handlers wired to RFC 9457 Problem Details bodies (the body format itself is
ork:api-design)
Key Decisions
| Decision |
Recommendation |
| Lifespan |
asynccontextmanager (not events) |
| Dependencies |
Class-based services with DI |
| Settings |
Pydantic Settings with .env |
| Response |
ORJSONResponse for performance |
| Health |
Check all critical dependencies |
SQLAlchemy
Async database patterns with SQLAlchemy 2.0, AsyncSession, and FastAPI integration.
Key Patterns
- One AsyncSession per request with
expire_on_commit=False
lazy="raise" on relationships to prevent accidental N+1 queries
selectinload for eager loading collections
- Repository pattern with generic async CRUD
- Bulk inserts chunked 1000-10000 rows for memory management
Key Decisions
| Decision |
Recommendation |
| Session scope |
One AsyncSession per request |
| Lazy loading |
lazy="raise" + explicit loads |
| Eager loading |
selectinload for collections |
| expire_on_commit |
False (prevents lazy load errors) |
| Pool |
pool_pre_ping=True |
Pooling
Database and HTTP connection pooling for high-performance async Python applications.
Key Patterns
- SQLAlchemy pool with
pool_size, max_overflow, pool_pre_ping
- Direct asyncpg pool with
min_size/max_size and connection lifecycle
- aiohttp session with
TCPConnector limits and DNS caching
- FastAPI lifespan creating and closing pools at startup/shutdown
- Pool monitoring with Prometheus metrics
Pool Sizing Formula
pool_size = (concurrent_requests / avg_queries_per_request) * 1.5
That formula sizes one process. The fleet-level cap against the server's
max_connections, and the pool alert thresholds, are in references/ork-delta.md.
Anti-Patterns (FORBIDDEN)
# NEVER use gather() for new code - no structured concurrency
# NEVER swallow CancelledError - breaks TaskGroup and timeout
# NEVER block the event loop with sync calls (time.sleep, requests.get)
# NEVER use global mutable state for db sessions
# NEVER skip dependency injection (create sessions in routes)
# NEVER share AsyncSession across tasks (race condition)
# NEVER use sync Session in async code (blocks event loop)
# NEVER create engine/pool per request
# NEVER forget to close pools on shutdown
Upstream coverage (do not restate)
Topics removed in the 2026-07-31 wrap-plus-delta thinning. Consult the first-party source; only the ork delta (house policy, scars, working config) belongs in this skill. Where a row says a house subset stays in a rules/ file, that file is still the authority for the OrchestKit position and the link only covers the vendor surface around it.
| Topic |
First-party source |
asyncio task API reference: TaskGroup vs gather(), asyncio.timeout(), ExceptionGroup and except*, to_thread(). House subset stays in rules/asyncio-taskgroup.md and rules/asyncio-cancellation.md. |
https://docs.python.org/3/library/asyncio-task.html |
asyncio.Semaphore, Lock, Event, Queue semantics. House subset stays in rules/asyncio-structured.md; the create-once-plus-timeout rule is in references/ork-delta.md. |
https://docs.python.org/3/library/asyncio-sync.html |
Event-loop debug mode, slow_callback_duration, detecting blocking calls (the house 100 ms threshold is in references/ork-delta.md) |
https://docs.python.org/3/library/asyncio-dev.html |
FastAPI project scaffolding: app layout, APIRouter composition, Pydantic Settings wiring, uvicorn entry point |
https://fastapi.tiangolo.com/tutorial/bigger-applications/ |
FastAPI lifespan API and startup/shutdown mechanics. House subset stays in rules/fastapi-background.md; the reverse-order teardown rule is in references/ork-delta.md. |
https://fastapi.tiangolo.com/advanced/events/ |
Starlette/FastAPI middleware API, BaseHTTPMiddleware, call_next, CORS options. House subset stays in rules/fastapi-middleware.md and references/fastapi-app-boilerplate.md; the middleware-vs-dependency split is in references/ork-delta.md. |
https://fastapi.tiangolo.com/tutorial/middleware/ |
SQLAlchemy 2.0 asyncio API: create_async_engine, async_sessionmaker, expire_on_commit, Mapped/mapped_column, with_for_update, bulk insert and update. House subset stays in rules/sqlalchemy-sessions.md, rules/sqlalchemy-relationships.md, rules/sqlalchemy-migrations.md, and references/eager-loading.md. |
https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html |
SQLAlchemy pool implementations and options (pool_size, max_overflow, pool_pre_ping, pool_recycle, pool_timeout). House subset stays in rules/pooling-database.md. |
https://docs.sqlalchemy.org/en/20/core/pooling.html |
SQLAlchemy pool events (checkout, checkin, connect) for instrumentation. House subset stays in rules/pooling-tuning.md; the alert thresholds are in references/ork-delta.md. |
https://docs.sqlalchemy.org/en/20/core/events.html |
asyncpg pool API: create_pool, min_size/max_size, max_inactive_connection_lifetime, setup hook, type codecs |
https://magicstack.github.io/asyncpg/current/api/index.html |
aiohttp client reference: ClientSession, TCPConnector limits, keep-alive, DNS caching, ClientTimeout. House subset stays in rules/pooling-http.md. |
https://docs.aiohttp.org/en/stable/client_reference.html |
PostgreSQL server-side connection limits (max_connections, superuser_reserved_connections) |
https://www.postgresql.org/docs/current/runtime-config-connection.html |
| pytest-asyncio fixtures and async test setup |
https://pytest-asyncio.readthedocs.io/en/stable/reference/fixtures/index.html |
| Container and Kubernetes packaging, readiness/liveness probes, resource limits |
https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ |
| Auth flows, password hashing, token expiry policy, security headers |
Owned by ork:security-patterns (src/skills/security-patterns/); the FastAPI Depends() auth chain stays in rules/fastapi-dependencies.md |
| RFC 9457 problem-details body format, API versioning, SSE and WebSocket wire contracts |
Owned by ork:api-design (src/skills/api-design/); the FastAPI exception-handler wiring stays in rules/fastapi-background.md and references/fastapi-app-boilerplate.md |
| Production checklists for FastAPI, asyncio, SQLAlchemy, and pooling |
Derivable from the sources above; no checklist restatement kept |
Related Skills
ork:architecture-patterns - Clean architecture and layer separation
ork-extras:async-jobs - Celery/ARQ for background processing
ork:api-design - Wire contract, RFC 9457 errors, SSE/WebSocket streaming
ork:database-patterns - Database schema design
ork:security-patterns - Auth, password hashing, token policy
ork:testing-integration - pytest-asyncio and httpx ASGI test setup
ork:devops-deployment - Docker and Kubernetes packaging
1---2name: python-backend3license: MIT4compatibility: "Claude Code 2.1.277+."5description: "Async Python: asyncio TaskGroup, FastAPI dependencies and middleware, SQLAlchemy 2.0 async sessions, pool tuning. Not for the API contract (use api-design)."6user-invocable: false7disable-model-invocation: false8targets:9 - library: fastapi10 version: ">=0.142.2"11 - library: sqlalchemy12 version: ">=2.1.1"13metadata:14 source: https://skillmd.com/skills/yonatangross/python-backend15 owner-agent: "backend-system-architect"16 category: document-asset-creation17 version: "2.0.0"18 author: "OrchestKit"19 complexity: "medium"20 tags: "python, asyncio, fastapi, sqlalchemy, connection-pooling, async, postgresql"21allowed-tools: "Read Glob Grep WebFetch WebSearch"22path_patterns: ["*.py", "**/requirements*.txt", "**/pyproject.toml", "**/Pipfile"]23---2425<!-- directive-density: intentional (teaches asyncio/SQLAlchemy anti-patterns; NEVER markers describe real event-loop/race-condition bugs, not aspirational guidance) -->2627# Python Backend2829Patterns for building production Python backends with asyncio, FastAPI, SQLAlchemy 2.0, and connection pooling. Each category has individual rule files in `rules/` loaded on-demand.3031## Quick Reference3233| Category | Rules | Impact | When to Use |34|----------|-------|--------|-------------|35| [Asyncio](#asyncio) | 3 | HIGH | TaskGroup, structured concurrency, cancellation handling |36| [FastAPI](#fastapi) | 3 | HIGH | Dependencies, middleware, background tasks |37| [SQLAlchemy](#sqlalchemy) | 3 | HIGH | Async sessions, relationships, migrations |38| [Pooling](#pooling) | 3 | MEDIUM | Database pools, HTTP sessions, tuning |3940**Total: 12 rules across 4 categories.** House decisions rescued from thinned files live in `references/ork-delta.md`; vendor material is linked, not restated (see [Upstream coverage](#upstream-coverage-do-not-restate)).4142## Quick Start4344```python45# FastAPI + SQLAlchemy async session46async def get_db() -> AsyncGenerator[AsyncSession, None]:47 async with async_session_factory() as session:48 try:49 yield session50 await session.commit()51 except Exception:52 await session.rollback()53 raise5455# Reusable dependency alias (FastAPI's recommended Annotated form)56SessionDep = Annotated[AsyncSession, Depends(get_db)]5758@router.get("/users/{user_id}")59async def get_user(user_id: UUID, db: SessionDep):60 result = await db.execute(select(User).where(User.id == user_id))61 return result.scalar_one_or_none()62```6364```python65# Asyncio TaskGroup with timeout66async def fetch_all(urls: list[str]) -> list[dict]:67 async with asyncio.timeout(30):68 async with asyncio.TaskGroup() as tg:69 tasks = [tg.create_task(fetch_url(url)) for url in urls]70 return [t.result() for t in tasks]71```7273## Asyncio7475Modern Python asyncio patterns using structured concurrency, TaskGroup, and Python 3.11+ features.7677### Key Patterns7879- **TaskGroup** replaces `gather()` with structured concurrency and auto-cancellation80- **`asyncio.timeout()`** context manager for composable timeouts81- **Semaphore** for concurrency limiting (rate-limit HTTP requests)82- **`except*`** with ExceptionGroup for handling multiple task failures83- **`asyncio.to_thread()`** for bridging sync code to async8485### Key Decisions8687| Decision | Recommendation |88|----------|----------------|89| Task spawning | TaskGroup not gather() |90| Timeouts | asyncio.timeout() context manager |91| Concurrency limit | asyncio.Semaphore |92| Sync bridge | asyncio.to_thread() |93| Cancellation | Always re-raise CancelledError |9495## FastAPI9697Production-ready FastAPI patterns for lifespan, dependencies, middleware, and settings.9899### Key Patterns100101- **Lifespan** with `asynccontextmanager` for startup/shutdown resource management102- **Dependency injection** with class-based services and `Depends()`103- **Middleware stack**: CORS -> RequestID -> Timing -> Logging104- **Pydantic Settings** with `.env` and field validation105- **Exception handlers** wired to RFC 9457 Problem Details bodies (the body format itself is `ork:api-design`)106107### Key Decisions108109| Decision | Recommendation |110|----------|----------------|111| Lifespan | asynccontextmanager (not events) |112| Dependencies | Class-based services with DI |113| Settings | Pydantic Settings with .env |114| Response | ORJSONResponse for performance |115| Health | Check all critical dependencies |116117## SQLAlchemy118119Async database patterns with SQLAlchemy 2.0, AsyncSession, and FastAPI integration.120121### Key Patterns122123- **One AsyncSession per request** with `expire_on_commit=False`124- **`lazy="raise"`** on relationships to prevent accidental N+1 queries125- **`selectinload`** for eager loading collections126- **Repository pattern** with generic async CRUD127- **Bulk inserts** chunked 1000-10000 rows for memory management128129### Key Decisions130131| Decision | Recommendation |132|----------|----------------|133| Session scope | One AsyncSession per request |134| Lazy loading | lazy="raise" + explicit loads |135| Eager loading | selectinload for collections |136| expire_on_commit | False (prevents lazy load errors) |137| Pool | pool_pre_ping=True |138139## Pooling140141Database and HTTP connection pooling for high-performance async Python applications.142143### Key Patterns144145- **SQLAlchemy pool** with `pool_size`, `max_overflow`, `pool_pre_ping`146- **Direct asyncpg pool** with `min_size`/`max_size` and connection lifecycle147- **aiohttp session** with `TCPConnector` limits and DNS caching148- **FastAPI lifespan** creating and closing pools at startup/shutdown149- **Pool monitoring** with Prometheus metrics150151### Pool Sizing Formula152153```154pool_size = (concurrent_requests / avg_queries_per_request) * 1.5155```156157That formula sizes one process. The fleet-level cap against the server's158`max_connections`, and the pool alert thresholds, are in `references/ork-delta.md`.159160## Anti-Patterns (FORBIDDEN)161162```python163# NEVER use gather() for new code - no structured concurrency164# NEVER swallow CancelledError - breaks TaskGroup and timeout165# NEVER block the event loop with sync calls (time.sleep, requests.get)166# NEVER use global mutable state for db sessions167# NEVER skip dependency injection (create sessions in routes)168# NEVER share AsyncSession across tasks (race condition)169# NEVER use sync Session in async code (blocks event loop)170# NEVER create engine/pool per request171# NEVER forget to close pools on shutdown172```173174## Upstream coverage (do not restate)175176Topics removed in the 2026-07-31 wrap-plus-delta thinning. Consult the first-party source; only the ork delta (house policy, scars, working config) belongs in this skill. Where a row says a house subset stays in a `rules/` file, that file is still the authority for the OrchestKit position and the link only covers the vendor surface around it.177178| Topic | First-party source |179|-------|--------------------|180| asyncio task API reference: TaskGroup vs `gather()`, `asyncio.timeout()`, `ExceptionGroup` and `except*`, `to_thread()`. House subset stays in `rules/asyncio-taskgroup.md` and `rules/asyncio-cancellation.md`. | https://docs.python.org/3/library/asyncio-task.html |181| `asyncio.Semaphore`, `Lock`, `Event`, `Queue` semantics. House subset stays in `rules/asyncio-structured.md`; the create-once-plus-timeout rule is in `references/ork-delta.md`. | https://docs.python.org/3/library/asyncio-sync.html |182| Event-loop debug mode, `slow_callback_duration`, detecting blocking calls (the house 100 ms threshold is in `references/ork-delta.md`) | https://docs.python.org/3/library/asyncio-dev.html |183| FastAPI project scaffolding: app layout, `APIRouter` composition, Pydantic Settings wiring, uvicorn entry point | https://fastapi.tiangolo.com/tutorial/bigger-applications/ |184| FastAPI lifespan API and startup/shutdown mechanics. House subset stays in `rules/fastapi-background.md`; the reverse-order teardown rule is in `references/ork-delta.md`. | https://fastapi.tiangolo.com/advanced/events/ |185| Starlette/FastAPI middleware API, `BaseHTTPMiddleware`, `call_next`, CORS options. House subset stays in `rules/fastapi-middleware.md` and `references/fastapi-app-boilerplate.md`; the middleware-vs-dependency split is in `references/ork-delta.md`. | https://fastapi.tiangolo.com/tutorial/middleware/ |186| SQLAlchemy 2.0 asyncio API: `create_async_engine`, `async_sessionmaker`, `expire_on_commit`, `Mapped`/`mapped_column`, `with_for_update`, bulk insert and update. House subset stays in `rules/sqlalchemy-sessions.md`, `rules/sqlalchemy-relationships.md`, `rules/sqlalchemy-migrations.md`, and `references/eager-loading.md`. | https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html |187| SQLAlchemy pool implementations and options (`pool_size`, `max_overflow`, `pool_pre_ping`, `pool_recycle`, `pool_timeout`). House subset stays in `rules/pooling-database.md`. | https://docs.sqlalchemy.org/en/20/core/pooling.html |188| SQLAlchemy pool events (`checkout`, `checkin`, `connect`) for instrumentation. House subset stays in `rules/pooling-tuning.md`; the alert thresholds are in `references/ork-delta.md`. | https://docs.sqlalchemy.org/en/20/core/events.html |189| asyncpg pool API: `create_pool`, `min_size`/`max_size`, `max_inactive_connection_lifetime`, `setup` hook, type codecs | https://magicstack.github.io/asyncpg/current/api/index.html |190| aiohttp client reference: `ClientSession`, `TCPConnector` limits, keep-alive, DNS caching, `ClientTimeout`. House subset stays in `rules/pooling-http.md`. | https://docs.aiohttp.org/en/stable/client_reference.html |191| PostgreSQL server-side connection limits (`max_connections`, `superuser_reserved_connections`) | https://www.postgresql.org/docs/current/runtime-config-connection.html |192| pytest-asyncio fixtures and async test setup | https://pytest-asyncio.readthedocs.io/en/stable/reference/fixtures/index.html |193| Container and Kubernetes packaging, readiness/liveness probes, resource limits | https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ |194| Auth flows, password hashing, token expiry policy, security headers | Owned by `ork:security-patterns` (`src/skills/security-patterns/`); the FastAPI `Depends()` auth chain stays in `rules/fastapi-dependencies.md` |195| RFC 9457 problem-details body format, API versioning, SSE and WebSocket wire contracts | Owned by `ork:api-design` (`src/skills/api-design/`); the FastAPI exception-handler wiring stays in `rules/fastapi-background.md` and `references/fastapi-app-boilerplate.md` |196| Production checklists for FastAPI, asyncio, SQLAlchemy, and pooling | Derivable from the sources above; no checklist restatement kept |197198## Related Skills199200- `ork:architecture-patterns` - Clean architecture and layer separation201- `ork-extras:async-jobs` - Celery/ARQ for background processing202- `ork:api-design` - Wire contract, RFC 9457 errors, SSE/WebSocket streaming203- `ork:database-patterns` - Database schema design204- `ork:security-patterns` - Auth, password hashing, token policy205- `ork:testing-integration` - pytest-asyncio and httpx ASGI test setup206- `ork:devops-deployment` - Docker and Kubernetes packaging