Chapter 6 · Practice and Capstone
Capstone Project, Cheat Sheet and What's Next
- Page 22 of 22
- 18 min read
You now have every piece of a production AI backend: Git and GitHub for teamwork, HTTP and API design, async clients, a layered FastAPI service with a database, authentication, caching and limits, tests, a model and an LLM behind it, security, Docker, CI/CD and a deployment. What you do not have yet is the proof that you can put them together without a tutorial holding your hand. That proof is the capstone: one project, built in small milestones, that you can show to an employer or a client.
This page has three parts: the capstone brief with milestones and an acceptance checklist, a cheat sheet for the whole advanced tutorial, and a map of what to learn next on the BitByte AI path.
What you will learn
- How to scope a capstone so that you finish it, and how to split it into milestones that each leave the project working.
- The acceptance checklist a production-ready AI backend has to pass.
- A cheat sheet of the commands, rules and numbers from the 21 pages before this one.
- What comes next: Prompt Engineering, then the AI Engineer path (LLM APIs, RAG, agents, MCP, evals and LLMOps).
The capstone brief: a Study Assistant API
Build the backend of a Study Assistant, a service that students use to ask questions about their course notes. The product idea is only a vehicle; if you prefer another domain (a support-ticket triager, a recipe assistant, a document Q&A tool for your own work), keep the same shape. What matters is that your project has all of these:
| Area | Requirement |
|---|---|
| Accounts | Register and log in with Argon2id password hashing, JWT access tokens and rotating refresh tokens. Every note and every question belongs to one user, and nobody can read another user's data. |
| Database | PostgreSQL with SQLAlchemy 2 and Alembic migrations: users, notes, questions and a usage table. Constraints in the database, 409 on duplicates, keyset pagination on lists. |
| ML endpoint | A small scikit-learn model (for example classifying a note's topic) saved with joblib, loaded once in lifespan, validated input, and a model_version in every response. |
| LLM endpoint | An /v1/ask endpoint behind a provider adapter (complete, stream, ping). A fake provider is the default and a real one is chosen by settings. Answers stream over Server-Sent Events. |
| Limits and cost | Per-user rate limit in Redis (429 with Retry-After), a daily token budget, timeouts on every outside call, and a log of tokens and cost per request, never of prompts. |
| Tests | pytest with a mocked provider and fake clock; tests for the wrong user, validation errors, limits, a streamed answer and a failing provider; a contract snapshot of openapi.json. |
| Security | A written review against the OWASP API Security Top 10 (2023), with a fix and a test for every finding, secret scanning and dependency scanning in CI. |
| Packaging and CI | A multi-stage Dockerfile running as non-root, a compose.yaml with API, PostgreSQL and Redis, health checks, and a GitHub Actions workflow that tests and builds on every push. |
| Deployment | Live on a host you chose, from a tagged release, with migrations on deploy, a smoke test, structured logs, a health and readiness endpoint, and a rehearsed rollback. |
| Docs | A README (what it is, how to run it, how to deploy it, the architecture in one picture), an API reference from OpenAPI, and a short runbook. |
Out of scope on purpose: a front end, payments, email, real-time chat, and anything that needs a paid account. A fake provider is enough to earn full marks; the architecture, not the vendor, is what you are showing.
Milestones
Each milestone ends with a working project on its own branch, merged through a pull request, with CI green. If you run out of time, a project that stops after M6 and works is better than one that attempts M8 and does not run.
| # | Milestone | Done when | Revisit |
|---|---|---|---|
| M1 | Skeleton and repository | /health and /ready answer, settings come from the environment, .gitignore and .env.example exist, one test passes in CI | Dependencies, Lifespan, Middleware and Settings |
| M2 | Data and accounts | Migrations create the schema, register/login work, a user can create and list only their own notes | Databases with SQLAlchemy and Alembic, Authentication and Authorisation |
| M3 | The AI endpoints | /v1/predict returns a label and model_version; /v1/ask streams a fake answer; both reject bad input with 422 | Serving an ML Model, Building an LLM Backend with Streaming |
| M4 | Limits, cache and cost | The 11th request in a minute gets 429; over-budget users are refused before streaming; every request logs tokens and cost | Caching, Rate Limiting and Reliability with Redis |
| M5 | Professional tests | All failure paths covered, no real network in tests, the suite runs in under a minute, coverage reported | Testing Professional APIs |
| M6 | Security review | Ten findings written up (even "not applicable, because…"), each with a fix and a test; pip-audit and a secret scan run in CI | API Security and the OWASP API Top 10 |
| M7 | Containers | docker compose up gives a working stack from a clean clone; migrations run as a one-shot service | Docker: Packaging Your API, Docker Compose: API, PostgreSQL and Redis Together |
| M8 | Ship it | Tag a release, CI builds and deploys it, the smoke test passes, you roll back once on purpose, the README has a live URL | CI/CD with GitHub Actions, Deployment and Production Readiness |
Start the repository
A layout that follows FastAPI Architecture keeps routes thin and logic testable. Create the folders, add the first commit and open the branch for M1:
mkdir -p ~/projects/study-assistant/{app/routers,app/services,app/repositories,app/schemas,tests,migrations,deploy,docs}
cd ~/projects/study-assistant
for d in app/routers app/services app/repositories app/schemas tests migrations deploy docs; do touch $d/.gitkeep; done
touch app/__init__.py app/main.py
printf '# Study Assistant API\n\nWhat it is, how to run it, how to deploy it.\n' > README.md
git init -q
git add .
git commit -q -m "Start the capstone"
git switch -q -c milestone/1-skeleton
git log --oneline --decorate53e48b6 (HEAD -> milestone/1-skeleton, main) Start the capstoneKeep branch names, commit messages and pull requests as you learned them: one milestone per branch, small commits with clear messages, a PR description that says what changed and how you tested it, and a squash merge. The finished layout looks like this:
study-assistant/
├── app/
│ ├── main.py # create_app(), lifespan, middleware, exception handlers
│ ├── settings.py # pydantic-settings, secrets as SecretStr
│ ├── routers/ # thin HTTP layer: auth, notes, predict, ask, health
│ ├── services/ # rules: auth, quota, provider adapters, model loading
│ ├── repositories/ # SQLAlchemy queries only
│ └── schemas/ # Pydantic request and response models
├── migrations/ # Alembic
├── tests/ # unit, API, and a few marked integration tests
├── deploy/ # render.yaml or Cloud Run notes, smoke_test.py
├── docs/ # architecture picture, runbook
├── Dockerfile
├── compose.yaml
├── .github/workflows/ # ci.yml, deploy.yml
├── .env.example
└── README.mdA Makefile gives you and your reviewers the same short commands (it needs make, which Linux and macOS have, and Windows has through WSL or Git Bash):
# file: Makefile
.PHONY: test lint up down smoke
test:
python -m pytest -q
lint:
ruff check .
up:
docker compose up -d --build
down:
docker compose down
smoke:
python smoke_test.py $(URL) $(VERSION)The acceptance checklist
Your capstone is done when a stranger can tick every row from your repository and your live URL alone. Write the evidence (a command, a file, a link) next to each tick in your README; "I think so" is not evidence.
| Check | Evidence |
|---|---|
A clean clone runs with docker compose up and a copied .env.example | The README commands, tried on a fresh machine or folder |
CI is green on main: lint, tests, dependency and secret scans, image build | The Actions run link |
| Tests need no network and no real key; failure paths are covered | Test names for wrong user, 422, 429, provider failure, stream error |
| Every route with an id checks ownership; 401, 403, 404 and 429 are used correctly | An auth test table in the tests |
| Migrations create the whole schema; the deploy runs them; they are backward compatible | alembic upgrade head on an empty database in CI |
| No secret in Git history, logs or the image; the secret setting is required | The secret-scan job; a startup test with the key missing |
| Limits exist for rate, request size, concurrency, time and daily spend | A test or a log line for each |
| Logs are JSON, carry a request ID, and show tokens and cost without prompts | Sample log lines in the docs |
| A deployed URL answers over HTTPS from a tagged release; the version is visible | The smoke test run against it |
| You rolled back on purpose once and the service recovered | Two tags and the revert commit in the history |
| The OWASP review lists all ten risks with a fix and a test, or a reason for "not applicable" | docs/security-review in the repository |
| The README explains the architecture, the trade-offs you made and what you would do next | One picture and one page of prose |
A simple grading scheme for yourself or for a mentor: must (M1 to M5 working, deployed once), should (M6 to M8, rollback rehearsed), stretch (a real LLM provider behind the adapter, a job queue for long work, OpenTelemetry traces, a staging environment, canary releases).
The advanced cheat sheet
Every row is something the tutorial ran and checked. When you are unsure, look it up here, then open the page named in the section title.
Git and GitHub (Advanced Git, Working as a Team on GitHub, Git for AI Projects)
| Need | Command or rule |
|---|---|
| Park unfinished work | git stash push -u -m "msg", then git stash pop (restores and drops) or apply (keeps) |
| Tidy a branch before review | git rebase -i <base> with fixup, squash, reword; --abort to back out |
| Copy one commit | git cherry-pick -x <sha> |
| Recover a "lost" commit | git reflog, then git switch -c rescue <sha> (committed work only) |
| Undo on shared history | git revert <sha> (adds an undo commit); never force-push shared branches |
| Rejected push | git pull --rebase, then push; on your own branch use --force-with-lease |
| Releases | git tag -a v1.2.0 -m "...", git push --tags; never re-use a tag |
| Forks | origin is your fork, upstream is the original; branch, then PR, review, squash merge |
| Big files | Git LFS (10 GiB free on GitHub) or DVC with your own storage; keep pointers in Git |
| Reproducible Python | Commit uv.lock; install with uv sync --locked |
| A secret was committed | Rotate the key first, then git filter-repo, then enable push protection and a scan |
HTTP and API design (HTTP in Depth, Designing Robust APIs, Webhooks and Streaming)
| Topic | Rule |
|---|---|
| Safe and idempotent | Safe: GET, HEAD, OPTIONS. Idempotent: those plus PUT and DELETE. POST is neither, so retry it only with an Idempotency-Key. |
| What a status code asks the client to do | 4xx fix the request; 401 authenticate; 403 or 404 give up; 429 wait (Retry-After); 502, 503, 504 retry |
| Caching | Cache-Control for freshness; ETag with If-None-Match gives 304; If-Match with 412 stops lost updates |
| Pagination | Cursor (keyset) on a unique, indexed key; opaque cursors, a capped limit, and next_cursor: null at the end |
| Retries | Only transient failures; exponential backoff with full jitter; honour Retry-After; a maximum number of attempts and a retry budget |
| Long work | Answer 202 with a Location status URL; the client polls with a deadline |
| Versioning | Prefer additive changes; otherwise /v2, with Deprecation and Sunset headers |
| OAuth 2.0 | Authorization code + PKCE for users; client credentials for services; never the password grant for third parties (RFC 9700) |
| Webhooks | Sign timestamp + "." + raw body with HMAC-SHA256; compare with hmac.compare_digest; reject old timestamps; deduplicate by event id; answer 2xx fast |
| SSE | data:, event:, id: and retry: fields, a blank line between events; FastAPI: EventSourceResponse and ServerSentEvent |
Clients, FastAPI, databases and auth (Professional API Clients to Authentication and Authorisation)
| Topic | Rule |
|---|---|
| httpx | One shared Client or AsyncClient per upstream; explicit connect and read timeouts; gather with a Semaphore; respx in tests (httpx2 is the maintained fork) |
| Layers | Routers (HTTP), services (rules), repositories (SQL), schemas (shapes); imports flow one way |
| Dependencies and lifespan | Annotated[X, Depends(f)]; create shared resources in lifespan, keep them on app.state; tests use app.dependency_overrides |
def or async def | async def only when everything inside is awaited; blocking code goes in plain def (threadpool) |
| Background work | BackgroundTasks for small, losable jobs; durable or heavy work needs a queue |
| Probes | /health is cheap liveness; /ready checks dependencies and returns 503 |
| Database | One engine per process, one session per request; IntegrityError becomes 409; avoid N+1 with selectinload; test on a separate database built by the real migrations |
| Alembic | alembic revision --autogenerate -m "msg", read it, alembic upgrade head on every deploy, alembic downgrade -1, alembic current; it cannot see renames |
| Passwords and tokens | Argon2id with pwdlib; PyJWT with pinned algorithms; check iss, exp and token type; short access tokens and rotating refresh tokens |
| Authorisation | 401 = who are you; 403 or 404 = not yours; roles plus an ownership check on every object route (BOLA) |
Redis, testing and AI services (Caching… to Building an LLM Backend)
| Topic | Rule |
|---|---|
| Cache | Prefix, normalised identity and TTL on every key; invalidate by TTL, delete on write or versioned keys; cache LLM results only when deterministic, with model, prompt version and user scope in the key |
| Rate limits | Fixed window (simple), sliding window (exact), token bucket (bursts and token costs); answer 429 with Retry-After |
| Reliability | Timeouts and deadlines on everything; retry in one layer only; circuit breaker; planned degradation; a request ID on every log line |
| Test pyramid | Many fast unit and API tests with the world faked; a few marked integration tests; pytest.mark.parametrize and fixtures with the right scope; coverage finds gaps, it is not a goal |
| Mock the outside | respx or MockTransport for HTTP; a fake provider for LLMs; an injectable clock; an OpenAPI snapshot as the API contract |
| Serving a model | Train offline; save one pipeline with joblib; load all versions once in lifespan and warm up; validate features; return model_version; run it in a thread with a timeout |
| LLM backend | Provider adapter (complete, stream, ping); keys from settings; stream with SSE; record usage in finally; log tokens, cost, prompt and model version, never prompts; refuse over-limit users before the stream starts |
Security, containers, CI/CD and deployment (API Security to Deployment)
| Topic | Rule |
|---|---|
| OWASP API Top 10 (2023) | 1 broken object-level authorisation, 2 broken authentication, 3 broken object property-level authorisation, 4 unrestricted resource consumption, 5 broken function-level authorisation, 6 unrestricted access to sensitive business flows, 7 server-side request forgery, 8 security misconfiguration, 9 improper inventory management, 10 unsafe consumption of APIs |
| Always | Parameterised SQL; exact CORS origins (a browser rule, not authentication); size limits; secrets in the environment; pip-audit and a secret scan in CI; HTTPS; no personal data in logs |
| Dockerfile | python:3.14-slim; dependencies before code for caching; multi-stage build; non-root user; exec-form CMD; .dockerignore for .venv, .git, .env |
| Docker commands | docker build -t name:1.0.0 .; docker run --rm -p 8000:8000 --env-file .env name:1.0.0; docker logs; exit codes 137 (killed) and 143 (SIGTERM) |
| Compose | Services talk by service name; publish only the API; healthcheck plus depends_on: condition: service_healthy; migrations as a one-shot service; secrets at /run/secrets/<name>; docker compose config to check; down -v deletes data |
| GitHub Actions | Triggers push, pull_request, workflow_dispatch; permissions: contents: read; pin third-party actions to SHAs; never pull_request_target with PR code; deploy through an environment |
| Deployment | Same code, different config; $PORT; JSON logs to stdout; migrations before traffic; SIGTERM shutdown; smoke test after every deploy; roll back with the platform, a tag or git revert; budgets and caps; practise a restore |
What's next
You have finished Git, APIs and Backend for AI, topic 5 of Level 0 on the BitByte AI path. Here is where the road goes:
| Next stop | What you will do there | What from this tutorial it uses |
|---|---|---|
| Prompt Engineering (Level 0, topic 6) | Write prompts that give reliable, structured output; use system messages, examples, formats and evaluation by hand | The LLM adapter and request schemas, prompt versions in logs, /v1/chat-style calls |
| The AI Engineer path | LLM APIs in depth, retrieval-augmented generation (RAG), agents and tool use, MCP servers, evaluation, and LLMOps (tracing, cost, deployment of AI systems) | Everything: a RAG service is a FastAPI service with a database, a cache, auth, limits, tests and a deployment |
Ideas for the weeks after the capstone, in rough order of value: put the capstone link at the top of your CV and GitHub profile; ask someone to review your pull requests and review theirs; add a real provider behind your adapter and write down what the bill looks like; add tracing with OpenTelemetry and a job queue for a long task; read the changelogs of FastAPI, Pydantic and SQLAlchemy once a month, because the tools in this tutorial move fast; and learn Kubernetes or Terraform only when a real project needs them, not before.
Common mistakes
- Too big a scope. Ten features, none finished. Fix: do M1 to M5 fully before anything else, and cut features, not tests.
- Building the front end first. It looks like progress and hides the hard parts. Fix: drive the API with
curl, tests and/docsuntil M8. - Leaving deployment to the last evening. Port, secrets and migration problems appear only on a real host. Fix: deploy the skeleton in M1 or M2 and keep it deployed.
- A README that only says "run main.py". Nobody, including you in a month, can start it. Fix: write the README as you go and test it on a clean folder.
- Copying the tutorial without understanding. You cannot answer "why this status code?" in an interview. Fix: for every file, write one sentence on why it exists, and change one thing on purpose to see what breaks.
Try it yourself
- Easy. Mark the starting point of your capstone with an annotated tag
v0.1.0, go back tomainand list the tags and branches. - Medium. Design the smoke test for your capstone: list the requests it should make against the live service and say which of them must not change any data.
- Hard. Write the runbook entry for "the LLM bill doubled overnight": what you check first, in which order, and what limits or settings you would have added to prevent it.
Answers
Easy. A tag marks a release or a starting point, so you can always return to it:
git switch -q main
git tag -a v0.1.0 -m "Capstone skeleton"
git tag --list
git branchv0.1.0
* main
milestone/1-skeletonMedium. Read-only or self-cleaning requests only: GET /health (is it up, and which version?), GET /ready (is the database reachable?), a POST without a token that must give 401, a POST with a valid token and an invalid body that must give 422 (proves auth and validation without writing a row), a GET of a list with the smoke-test user's token, and a streamed /v1/ask against the fake provider (or a request with a tiny prompt and a budget that costs nothing). Anything that creates data uses a dedicated smoke-test user and cleans up after itself. Run it after every deploy and make the exit code decide whether the pipeline continues, exactly as on the deployment page.
Hard. A good runbook entry is a short, ordered list. First, stop the bleeding: lower the daily token budget or switch the provider setting to the cheaper model, and rotate the key if you suspect it leaked. Second, find the cause with the logs you built: group cost by user, endpoint, prompt_version and model_version for the last 24 hours, and look at request counts, retries and streams that were cut. Third, decide the cause: a prompt change that doubled the context, a retry loop on a non-idempotent call, one abusive user, or a leaked key. Fourth, fix and prevent: a per-user and global daily budget that refuses before the provider call, a spend limit at the provider, a budget alert at 50 and 80 percent, a retry budget, a test for the case, and a note in the post-mortem. Every item on that list is something you built in this tutorial.
Summary
- The capstone is a Study Assistant backend built in eight milestones, each ending with a working, merged, deployed-or-deployable project; finish M1 to M5 before anything optional.
- Acceptance is evidence, not opinion: a clean clone runs, CI is green, failure paths are tested, secrets are clean, limits and cost logs exist, a tagged release is live, and a rollback was rehearsed.
- The cheat sheet covers Git, HTTP and API design, clients, FastAPI, databases, auth, Redis, testing, AI services, security, containers, CI/CD and deployment in one place.
- The next stops are Prompt Engineering (Level 0, topic 6) and then the AI Engineer path: LLM APIs, RAG, agents, MCP, evals and LLMOps.
Next: Prompt Engineering, the next topic of Level 0 on the BitByte AI path, and after it the AI Engineer path. Congratulations on finishing Git, APIs and Backend for AI: Advanced.

