How to choose the backend stack (Django, FastAPI, or Go) from requirements, plus the tools, folder layouts, and commands for each. Architect recommends one and the user confirms. Engineers get the confirmed stack copied into docs/architecture.md. Change defaults here only.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Stack Defaults?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/sayeed1999-stack-defaults)
---
name: stack-defaults
description: How to choose the backend stack (Django, FastAPI, or Go) from requirements, plus the tools, folder layouts, and commands for each. Architect recommends one and the user confirms. Engineers get the confirmed stack copied into docs/architecture.md. Change defaults here only.
---
# stack-defaults
Edit this file to change the stack of every future project.
No backend stack is the default for all projects. Choose from the requirements.
## Choose the backend
### `django`
- Best for: data-heavy business apps (school or clinic management, CRM, inventory, CMS)
- Strength: built-in admin, auth, permissions, ORM, migrations
- Cost: heavier for a small API; weaker fit for many live connections
### `fastapi`
- Best for: AI and API-first services (AI assistant, document processing, integration API)
- Strength: Python AI libraries, streaming, typed schemas, small codebase
- Cost: admin, auth, and permissions are assembled by hand
### `go`
- Best for: high-traffic, concurrent, real-time apps (ride-sharing, dispatch, chat, live bidding, telemetry)
- Strength: cheap concurrency, low latency, small deployable binary
- Cost: more code per feature; no built-in admin or auth
### Signals
**`go`**
- 1,000 or more live connections at once (WebSocket, SSE)
- 500 or more requests per second, sustained
- Constant high-frequency writes, such as location updates
- Matching, dispatch, or fan-out with a latency limit under load
**`django`**
- Staff need a back office to manage records
- 10 or more related entities, mostly create, read, update, delete
- Several roles with different permissions per record type
- Accounts, content, approvals, or reports are most of the product
**`fastapi`**
- AI or data processing in Python is core to the product
- Mostly calls to external APIs, or streamed responses
- A small API with little or no back office
The numbers are starting thresholds, not benchmarks. Tune them from real projects.
### Rules, in order
1. The user named a stack: use it. If a requirement conflicts with it, say so once and ask.
2. Code already exists: keep its stack. Propose a switch only if it cannot meet a requirement.
3. AI runtime is `langgraph` or `langgraph+langchain` (AI runtime below): the backend must be Python. Recommend `fastapi`, or `django` with two or more `django` signals. If a `go` signal also exists, ask: Python only (recommended unless an R-ID needs the `go` load), or `go` plus a separate Python AI service (Repo layout: Several services, mixed languages).
4. Any `go` signal backed by a requirement or user answer: recommend `go`.
5. Otherwise, two or more `django` signals: recommend `django`. If Python AI work is also core, keep `django` and put the AI code in `api/ai/`.
6. Otherwise: recommend `fastapi`.
- Judge load by what the requirements say the product must reach, not by its category or by hope. A ride-sharing demo for one campus may not need `go`; say so.
- Changing backend language later is a rewrite. If a higher target is planned, weigh its load now.
- Team experience can outweigh a weak signal. Name that trade-off.
- One backend service per project by default. A second service needs an R-ID the first cannot meet, and user confirmation.
- Several services use one language. Mixed languages need an R-ID that one language cannot meet.
- Speed comes from the database and design too. Never claim a language alone meets a load target.
## Confirm with the user
Always confirm before writing design files. Ask one question:
- Recommended stack first, marked as recommended
- 1 or 2 other realistic options
- Per option: why it fits or not (cite R-IDs or answers) and what is given up
Skip only when there is no backend, or the stack is already confirmed in `docs/architecture.md` and no requirement or target changed it.
## Common to all stacks
- JSON field names: `snake_case`
- Every backend has `GET /health` returning `{"status": "ok"}`.
- Passwords: argon2id
- One place reads env. One place creates the logger.
- Feature folders do not import each other. Shared code goes in the shared folder. Exception: a `django` model may point to another app's model by its string label.
- Pin versions. Use the latest stable release that all chosen packages support. Commit the lock file.
- Never name a top-level Python module after a standard-library module or an installed package (`logger.py`, never `logging.py`).
## Repo layout
### One service (default)
- The backend lives flat in `api/`: wiring, config, logger, and database files at the top of `api/`. Features, migrations, external services, and MCP are folders.
- Never put backend files at the repo root. The root holds `web/`, `mobile/`, `docker-compose.yml`, `docs/`, `contracts/`, and `tests/`.
- The config file holds one struct (Python: one settings class) per infra dependency (database, redis) and per external service.
- Layouts: the `api/` trees of each stack below.
### Several services, same language
- Needs an R-ID the single service cannot meet, and the user's confirmation.
- Each service is a root folder named for its job, kebab-case (`orders-service/`).
- Shared code lives in a root `internal/`: `config/`, `logging/`, `database/`, `migrations/`, `seed/`, `auth/`, `httpx/` (Python: `errors`).
- `internal/config` holds one struct (Python: one settings class) per service, per external service, and per infra dependency.
- `external-services/`, `mcp-client/`, and `mcp-server/` sit at the repo root, shared by every service.
- A service folder holds only its entry point and its feature folders. Services never import each other.
- Exactly one service runs migrations and the seed. Name it in section 11. The others never migrate.
- `go`: one `go.mod` at the repo root (Go allows `internal/` imports only inside one module). Add `ignore ./web` and `ignore ./mobile` to it.
- Python: a uv workspace at the repo root, one `uv.lock`. Members: `internal`, each service, each `external-services/*`, `mcp-client`, `mcp-server`. Python does not enforce `internal/`; only services and shared packages import it, never external-services or MCP.
- Docker: every service builds with the repo root as context and `dockerfile: <service>/Dockerfile`. One root `.dockerignore`.
- `django`: stays one service.
```
go.mod # go: one module | pyproject.toml: Python: uv workspace root
internal/
config/ # only place that reads env; one struct per service, external service, infra dependency
logging/ # only place that creates a logger
database/ # data layer: pool or engine, session, migrate runner (go: queries/, gen/)
migrations/ # data layer
seed/ # data layer
auth/
httpx/ # Python: errors/
<service>/
main.go | main.py # wiring for this service only
<feature>/
Dockerfile
external-services/<name>/
mcp-client/
mcp-server/
web/
```
### Several services, mixed languages
- Only when an R-ID needs two languages, for example a `go` load signal plus `langgraph`. Recommend one language first.
- Services share no code. No root `internal/`.
- Each service uses the one-service layout of its stack inside its own folder, with its own manifest and lock file.
- A service calls another only through its HTTP API. The caller keeps the client in its own `external-services/<other-service>/`, built from that service's section in `contracts/api.md`.
## External services
- One folder per third-party API the backend calls: `external-services/<name>/`, kebab-case vendor or service name.
- Only when an R-ID needs the service to really work.
- Contents:
- `contract.md` (architect): base URL, auth method, every endpoint we call with request and response fields, error codes, rate limits, timeout, retry limit, env var names.
- Interface: the methods our code calls, in our own types.
- Config type: the fields the client needs. The package never reads env.
- Client: implements the interface with HTTP or the vendor SDK.
- Fake: implements the interface in memory for tests.
- `go` files: `contract.md`, `client.go` (interface, types, errors), `config.go`, `http.go` (`New(cfg Config, log *slog.Logger, hc *http.Client) Client`), `fake.go`. Package name: `<name>` without hyphens.
- Python files: `contract.md`, `pyproject.toml` (uv workspace member), `src/<name>_client/`: `__init__.py`, `client.py` (Protocol, models, errors), `config.py` (dataclass), `http.py` (`httpx` client), `fake.py`. The `_client` suffix keeps it from shadowing the vendor SDK.
- Rules:
- The package imports only the standard library, its HTTP client or vendor SDK, and nothing from `internal/`, services, `ai/`, or another external service. Copying the folder into another project must build.
- Config, logger, and HTTP client come in through the constructor. The wiring file builds it from the config file.
- Vendor SDK types and errors never leave the package. Map them to the package's own types and errors.
- Every call has a timeout (`go`: `context`). Retry only idempotent calls, up to the contract's limit.
- Feature code depends on the interface, never on `http.go`. Tests use the fake.
- A fake replaces a third-party service only. Never fake our own backend.
- Never log API keys, tokens, or request bodies that hold PII.
## MCP (only when an R-ID needs it)
- `mcp-client/`: connects our `ai/` code to an outside MCP server named in `contracts/ai.md`.
- `mcp-server/`: exposes our tools to outside agents.
- Location: inside `api/` for one service, at the repo root for several services.
- Each is self-contained. `go`: packages `mcpclient` and `mcpserver`. Python: uv workspace members with import packages `mcp_client` and `mcp_server` (never a folder named `mcp`, which shadows the SDK).
- Neither imports `internal/`, services, `ai/`, feature folders, or the database. Copying the folder into another project must build.
- Config (server URL or command, timeout), logger, and handlers come in through the constructor.
- `mcp-server/` defines a `ToolProvider` interface (list tools, call a tool). The service's wiring passes an implementation that calls the service layer.
- `mcp-client/` returns tools and results in its own types. `ai/` adapts them to the provider's tool format.
- Transport: `mcp-server/` mounts streamable HTTP at `/mcp` on the service, with the API's auth. It runs as its own service only when an R-ID needs that.
- Packages: Python `mcp`; `go` `github.com/modelcontextprotocol/go-sdk`.
## Backend: `django` (`api/`)
- Python 3.12 or later, Django, Django REST Framework
- Package manager: `uv`. Commit `uv.lock`.
- Database: Django ORM and Django migrations
- Config: `django-environ`
- Auth: `django.contrib.auth` with the Argon2 hasher. Web: session cookie with CSRF, web and API on the same site. Mobile: `djangorestframework-simplejwt`.
- Back office: Django admin, staff only. Never the end-user UI.
- Server: `gunicorn`; `whitenoise` for admin static files. In-memory state needs one worker process.
- Live updates: polling. If WebSockets are required, revisit the stack choice.
- Tests: `pytest` and `pytest-django`. Lint and format: `ruff`
```
api/
config/ # settings.py (only place that reads env), urls.py, wsgi.py
apps/
core/ # logging, permissions, contract error format
<feature>/ # serializers.py, services.py, views.py, urls.py, admin.py
models.py # data layer
migrations/ # data layer
seed/ # data layer: management/commands/seed.py
ai/ # only if AI features exist
external-services/ # only if an R-ID needs a third-party API (External services)
mcp-client/ # only if an R-ID needs MCP
mcp-server/ # only if an R-ID needs MCP
tests/
manage.py
pyproject.toml
Dockerfile
.env.example
AGENTS.md # architect writes it (architecture-spec, Project AGENTS.md)
```
## Backend: `fastapi` (`api/`)
- Python 3.12 or later, FastAPI, Pydantic v2
- Package manager: `uv`. Commit `uv.lock`.
- Database: SQLAlchemy 2 (sync) and Alembic migrations
- Config: `pydantic-settings`
- Auth: `pwdlib` (argon2), JWT (`PyJWT`)
- Tests: `pytest` and `httpx`. Lint and format: `ruff`
- Endpoints are plain `def`. Use `async def` only to call an async client (for example AI streaming).
```
api/
main.py # creates the app, includes routers, wiring
config.py # only place that reads env; one settings class per infra dependency and external service
logger.py # only place that creates a logger
database.py # data layer: engine, session, declarative base
security.py # hashing, tokens, auth dependency
errors.py # contract error format, exception handlers
models/ # data layer: one file per entity
migrations/ # data layer: Alembic env.py and versions/
seed/ # data layer: __main__.py
<feature>/ # router.py, service.py, schemas.py
ai/ # only if AI features exist
external-services/ # only if an R-ID needs a third-party API (External services)
mcp-client/ # only if an R-ID needs MCP
mcp-server/ # only if an R-ID needs MCP
tests/
alembic.ini # script_location = migrations
pyproject.toml
uv.lock
Dockerfile
.env.example
AGENTS.md # architect writes it (architecture-spec, Project AGENTS.md)
```
- `pyproject.toml`: `[tool.uv] package = false`; `[tool.uv.workspace] members` lists each `external-services/*`, `mcp-client`, `mcp-server` in use; pytest `pythonpath = ["."]`.
- Top-level modules import by plain name (`from config import settings`). Run every command from `api/`.
## Backend: `go` (`api/`)
- Go (latest stable), Echo v5 (`github.com/labstack/echo/v5`). Handlers take `*echo.Context`; do not copy v4 examples.
- No built-in admin: staff screens are routes in `web/`.
- Modules: commit `go.mod` and `go.sum`
- Database: PostgreSQL with `pgx/v5` pool (`pgxpool`). Prototype: SQLite with `modernc.org/sqlite`.
- Queries: `sqlc`, engine matching the database (`sql_package: "pgx/v5"` for PostgreSQL). Never edit generated code.
- Migrations: `golang-migrate`. `sqlc` reads the same `migrations/` folder.
- Config: standard library, read in one package
- Logging: `log/slog`
- Validation: `go-playground/validator`
- Auth: `alexedwards/argon2id`, JWT (`golang-jwt/jwt/v5`)
- WebSocket (only if required): `coder/websocket`
- Tests: `testing` and `httptest`; database tests use the target's engine (PostgreSQL in Docker for `mvp` and `production`). Lint: `golangci-lint`, `gofmt`
- Every database and network call takes a `context` with a timeout.
- No unbounded goroutines or channels. Shut down gracefully.
```
api/
main.go # wiring, subcommands serve | migrate | seed, graceful shutdown
config.go # only place that reads env; one struct per infra dependency and external service
logger.go # only place that creates the logger
database.go # data layer: pool and migrate runner
auth/ # hashing, tokens, middleware
httpx/ # contract error format, error handler
queries/ # .sql files (backend-engineer)
gen/ # sqlc output (backend-engineer)
migrations/ # data layer: NNNNNN_name.up.sql and .down.sql
seed/ # data layer: seed.Run(ctx, pool, mode)
<feature>/ # handler.go, service.go, types.go
ai/ # only if AI features exist
external-services/ # only if an R-ID needs a third-party API (External services)
mcp-client/ # only if an R-ID needs MCP
mcp-server/ # only if an R-ID needs MCP
sqlc.yaml
go.mod
Dockerfile
.env.example
AGENTS.md # architect writes it (architecture-spec, Project AGENTS.md)
```
- Package `main` cannot be imported. Feature packages get what they need through constructors (`*slog.Logger`, the pool, `*gen.Queries`, their own options struct). They never read env.
## Web (`web/`), all stacks
- Next.js (App Router), React, TypeScript
- Package manager: `pnpm`. Commit `pnpm-lock.yaml`.
- Styling: Tailwind CSS
- Lint: ESLint. Types: `tsc --noEmit`
- Server components by default. Add `"use client"` only where a screen needs state or browser APIs.
```
web/
src/
app/ # routes, one route per design screen
components/
lib/
api/ # one client, one function per contract endpoint; types.ts mirrors the contract
config.ts # only place that reads env
logger.ts # only place that logs
auth/
public/
next.config.ts # output: "standalone"
package.json
Dockerfile
.env.example
AGENTS.md # architect writes it (architecture-spec, Project AGENTS.md)
```
## Mobile (`mobile/`)
- React Native with Expo (Expo Router), TypeScript, `pnpm`
- Styling: NativeWind (Tailwind utility classes)
- Only when the PRD platform lists `android` or `ios`.
- Token stored in `expo-secure-store`.
- Not part of `docker-compose.yml`. It calls the API URL from env.
- Android build: Expo EAS, internal distribution (APK).
- If Metro cannot resolve packages under pnpm, add `node-linker=hoisted` to `mobile/.npmrc`.
```
mobile/
app/ # Expo Router screens
src/
components/
lib/ # same sub-folders as web/src/lib
package.json
.env.example
AGENTS.md # architect writes it (architecture-spec, Project AGENTS.md)
```
## Database
- `mvp` and `production`: PostgreSQL 18 in Docker with a named volume.
- `prototype`: SQLite for every stack, file in a Docker named volume. Browser storage when there is no backend.
- Moving a `go` prototype to `mvp` rewrites migrations and sqlc queries for PostgreSQL. Record it in the Upgrade path.
- Schema, keys, migrations, and seed rules: `skills/db-schema`.
- Data layer (owned by database-engineer): the paths marked `data layer` in the layouts above.
- UUIDv7 package: Python 3.14+ uses the standard library, earlier Python uses `uuid-utils`; Go uses `github.com/google/uuid`.
- `django` and `fastapi` models use portable column types, so API tests can run on SQLite. If a requirement needs a PostgreSQL feature, test on PostgreSQL.
- PostGIS only when an R-ID needs location queries.
- `pgvector` only when an R-ID needs vector embeddings or RAG retrieval. In SQLite (`prototype`), use `sqlite-vec` or in-memory cosine similarity.
## Containers
- Docker and Docker Compose. `docker-compose.yml` at the repo root. Details: `skills/docker-deploy`.
- One `docker-compose.yml` for every target, prototype included.
- Services: `db` (`mvp` and `production` only), `api`, `web`. Mobile is not containerized.
- Migrations, then the seed, run before `api` serves requests.
- Add `caddy` (HTTPS) only when the user hosts on their own server. A managed host gives HTTPS itself.
## AI runtime (only when a requirement needs AI)
Pick the smallest runtime that meets the stories. Record it and its R-IDs in `docs/architecture.md` and `contracts/ai.md`.
### `direct` (default)
- The provider's official SDK and our own short tool-calling loop. Works in every stack.
- Fits: Q&A bots that answer business questions from the database, a spreadsheet, or documents (`tool-call`, `rag`, `text-only`).
- Fits: one user message in, one answer out, with at most 5 tool calls in between.
- Chat history (stateless or a sliding window) does not need a framework.
- Spreadsheets: import them into the database in the seed or an ingest command, then use `tool-call`. Read the file directly only when it changes between requests.
- Documents: parse with a plain library (`pypdf`, `python-docx`, `openpyxl`). No LangChain.
- Packages: Python `openai`, `anthropic`, or `google-genai`; Go `github.com/openai/openai-go` or `github.com/anthropics/anthropic-sdk-go`.
### `langgraph`
Use it only when an approved story needs one of these. Name the R-ID.
- A workflow: several steps where later steps depend on earlier results, and the path branches or loops (triage, then collect missing info, then draft, then review, then send).
- Workflow state that must survive between user messages or a server restart, beyond chat history (a case that moves through stages).
- A human approves or edits mid-run, and the run resumes from that point.
- A run that outlives one HTTP request, or must retry one step without redoing earlier steps.
- Several specialised agents that hand work to each other.
- Not signals: picking a tool, RAG, chat history, streaming, a bounded tool loop.
- Python only. Packages: `langgraph`, plus `langgraph-checkpoint-postgres` (`mvp`, `production`) or `langgraph-checkpoint-sqlite` (`prototype`). The checkpointer uses the project database.
- Nodes call the provider SDK directly.
### `langgraph+langchain`
- `langgraph`, plus LangChain components the workflow needs and would otherwise rebuild.
- Fits: loaders for many document formats, text splitters, vector store retrievers, swapping providers behind one model interface, structured output parsing across providers.
- Packages: `langchain-core`, `langchain-text-splitters`, `langchain-<provider>` (`langchain-openai`, `langchain-anthropic`), and `langchain-community` only for a named loader or store.
- Never add LangChain only to call one model.
## AI features (every runtime)
- Call the AI provider from the backend only. Never from web or mobile.
- All AI code lives in the stack's `ai` folder. Nothing else imports the provider SDK.
- `ai/` reaches outside MCP servers only through `mcp-client/`.
- The key comes from env. Set a timeout and a retry limit.
- Document ingestion and vector indexing: run via a CLI script or on startup. Never ingest bulk documents inside a live chat request handler.
- Provider errors use the contract error format.
- Never log prompts or responses that can hold PII.
- The architect asks the user which provider and model (`skills/architecture-spec`).
## Commands
### `django` (run in `api/`)
- Install: `uv sync`
- Run: `uv run python manage.py runserver`
- Test: `uv run pytest`
- Lint: `uv run ruff check .` and `uv run ruff format --check .`
- New migration: `uv run python manage.py makemigrations`
- Apply migrations: `uv run python manage.py migrate`
- Seed: `uv run python manage.py seed`
### `fastapi` (run in `api/`)
- Install: `uv sync`
- Run: `uv run uvicorn main:app --reload`
- Test: `uv run pytest`
- Lint: `uv run ruff check .` and `uv run ruff format --check .`
- New migration: `uv run alembic revision --autogenerate -m "<message>"`
- Apply migrations: `uv run alembic upgrade head`
- Seed: `uv run python -m seed`
### `go` (run in `api/`; several services: run at the repo root with `./<service>` in place of `.`)
- Install: `go mod download`
- Generate queries: `sqlc generate`
- Run: `go run . serve`
- Test: `go test -race ./...`
- Lint: `golangci-lint run` and `gofmt -l .` (must print nothing)
- Build: `go build ./...`
- New migration: `migrate create -ext sql -dir migrations -seq <name>`
- Apply migrations: `go run . migrate`
- Seed: `go run . seed`
### Web (run in `web/`)
- Install: `pnpm install`
- Run: `pnpm dev`
- Lint: `pnpm lint`
- Types: `pnpm exec tsc --noEmit`
- Build: `pnpm build`
### Mobile (run in `mobile/`)
- Install: `pnpm install`
- Run: `pnpm expo start`
- Lint: `pnpm lint`
- Types: `pnpm exec tsc --noEmit`
### Whole stack (run at the repo root)
- Start: `docker compose up --build -d`
- Stop: `docker compose down`
- End-to-end tests (run in `tests/e2e/`): `pnpm exec playwright test`
## Env variable names
- api: `DATABASE_URL`, `SECRET_KEY`, `CORS_ORIGINS`, `SEED_MODE` (`demo`, `reference`, or `off`)
- api, admin-created accounts only: `ADMIN_EMAIL`, `ADMIN_PASSWORD`
- api, `django` only: `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`
- web: `NEXT_PUBLIC_API_URL`
- mobile: `EXPO_PUBLIC_API_URL`
## Other changes to the defaults
- No requirement needs an API: no `api/`, no database, no auth.
- PRD platform is `api-only`: no `web/`.
- PRD platform lists `android` or `ios`: add `mobile/`.
- Background jobs, first choice: `fastapi` uses `BackgroundTasks`; `go` uses a bounded worker pool; `django` runs short work in the request. Add Redis and a worker only if jobs must survive a restart or run outside a request. Name the R-ID.
- Redis for live shared state (for example driver positions) or several API instances: name the R-ID.
- `production` with a load target: add a load test that proves it.
- File uploads: a local Docker volume for `mvp`. Object storage only when more than one server runs.
- Anything not listed here: keep the default. Do not add a tool because it is popular.
## MUST
- Get the user's confirmation of the backend stack.
- Pick every layer from this file, or record why not.
- Copy only the confirmed stack's layout and commands into `docs/architecture.md`.
## NEVER
- Pick a stack because it is listed first, familiar, or popular.
- Add a cache, queue, or extra service without an R-ID that needs it.
- Mix two tools for one job (no `npm` next to `pnpm`).