Skip to content
Visual explainer 5h to learn 5 steps

Capstone: verify, release and hand over

Run tests and evals, demonstrate a failure and recovery, and deploy or document deployment with a teardown plan.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.

Topic 29 of 29

In short

The final milestone proves the service works and hands it over safely. You run the tests and the eval set, break something on purpose and show it recover, capture a redacted trace, write a migration and rollback checklist, and either deploy or document a deployment with a teardown plan. The result is a package another engineer could pick up and run without asking you questions.

Explained simply

A working demo is not yet a finished service. In this last step you prove it works, show how it behaves when something breaks, and leave everything another engineer needs to run, change or remove it.

Proving it means running the automated tests and the evaluation set and saving their real output. The tests check correctness, such as tenant isolation. The evaluation set checks quality, such as whether answers cite the right document.

Then you break something on purpose. For example, you make the fake model refuse the first two calls, or you stop the worker halfway through a job. You record what the user saw, what the logs and traces showed, and how the system recovered.

Finally, you write down how to upgrade the database safely and how to roll back, and you either deploy to the cloud or describe the deployment in enough detail to do it. Every deployment comes with a teardown list, so nothing keeps running and costing money by accident.

Press Play on a diagram to walk through it one step at a time.

FlowRelease pipeline for the capstone
  1. 1
    Tests

    pytest: unit, route, tenant and failure tests

  2. 2
    Evals

    Recall, citation accuracy, no-source handling, latency

  3. 3
    Failure drill

    Provider 429 and worker restart, then recovery

  4. 4
    Migrate

    alembic upgrade head as a release step

  5. 5
    Deploy

    New image behind readiness checks

  6. 6
    Hand over

    Runbook, results, rollback and teardown

MapThe handover package
Capstone deliverables
  • Design
    • Architecture and request sequence
    • Request and ingestion diagrams
    • State ownership table
  • Code and stack
    • Reproducible Compose stack
    • Seed script for two tenants
    • Deterministic fake model
  • Contract
    • Sample payloads
    • Sample SSE events
    • Error codes
  • Evidence
    • Test and eval output
    • Failure drill notes
    • Redacted trace
  • Operations
    • Migration and rollback checklist
    • Cloud deployment design
    • Teardown list

In depth

Running tests and the eval set

Run pytest against the Compose stack so database integration is real. Use dependency_overrides to swap auth for test users from each tenant and to inject the fake model with chosen failures. Use with TestClient(app) as client so the lifespan runs and pools open and close as in production.

The eval runner loads the JSON cases, calls the API as each case's tenant, and scores four things separately: retrieval recall (was the expected chunk in the top k), citation accuracy (do the cited chunks match), no-source correctness (did unanswerable questions get the fixed message), and canary leaks (must be zero). It also records latency percentiles and token usage. Save the output as JSON in the repo with the commit hash, so later changes can be compared.

  • pytest -q for correctness
  • Evals score retrieval, citations, no-source and leaks separately
  • Canary leaks must be exactly zero
  • Save results with the commit hash

Demonstrating a failure and recovery

Pick two drills. First, a retryable provider error: start the API with FAKE_MODEL_FAILURES=429,429 and send a chat request. Expect the retry wrapper to wait with jitter, succeed on the third attempt, and the trace to show three model spans. Then set three failures with a retry limit of two and expect an error event with retryable true and a message saved as failed.

Second, a worker crash: upload a document, then run docker compose kill worker while the job is running. The job stays running until its lease expires, the sweeper moves it back to queued, and when you start the worker again it finishes. Evidence: the job's attempts went from 1 to 2, the chunk count is the same as a clean run, and no duplicates exist.

SequenceWorker crash and recovery drill
Operator
Worker
Sweeper
Postgres
  1. 1Claim job: running, attempts 1
    Worker to Postgres: Claim job: running, attempts 1
  2. 2docker compose kill worker
    Operator to Worker: docker compose kill worker
  3. 3Lease expired: set queued
    Sweeper to Postgres: Lease expired: set queued
  4. 4docker compose start worker
    Operator to Worker: docker compose start worker
  5. 5Claim job: running, attempts 2
    Worker to Postgres: Claim job: running, attempts 2
  6. 6Upsert chunks; succeeded
    Worker to Postgres: Upsert chunks; succeeded

Capturing a redacted trace

Instrument the API and worker with OpenTelemetry so one chat request produces a trace with spans for auth, retrieval, each model attempt and the stream. Export locally to the console or to a Jaeger container. Before sharing, redact: keep span names, durations, status, request and job IDs, tenant ID, chunk IDs, token counts and attempt numbers; remove question and answer text, chunk text, user emails and any headers.

The safest redaction is never recording sensitive values in the first place. Set only safe attributes in your own spans, and turn off any instrumentation option that captures request bodies or headers. Then the trace you hand over is the same one production would keep.

Migration and rollback checklist

Treat each schema change as expand and contract. The expand release adds new tables, nullable columns or indexes that the old code ignores. Code that uses them ships next. Only a later release drops what is no longer used. That way the previous image can always run against the current schema, so rolling back is just redeploying the old image.

Run alembic upgrade head as a separate release step before the new version takes traffic. Create large indexes concurrently so writes are not blocked; in Alembic that means running the operation outside a transaction. Test every downgrade on a copy of the data, but plan to roll forward with a fix rather than downgrade a production database that already holds new data.

  • Back up or snapshot before migrating
  • Expand first, contract in a later release
  • alembic upgrade head as its own step
  • Readiness stays red until migrations succeed
  • Rollback = previous image, schema left in place

Cloud deployment design and teardown

A managed deployment usually costs money, so a written design is an acceptable deliverable. One mapping: the API and worker as containers on a managed container service such as Google Cloud Run or Azure Container Apps; managed PostgreSQL with pgvector, such as Cloud SQL for PostgreSQL or Azure Database for PostgreSQL flexible server; a managed Redis for the queue; object storage for uploads; secrets from the platform's secret manager. The worker must keep running to pull jobs, so check how your platform handles always-on background containers.

Write a teardown list in the reverse order of creation: services, database, Redis, bucket, secrets, service accounts and DNS records. Locally, docker compose down -v removes the containers and volumes. Afterwards, check the billing page for anything still running.

LayersOne managed deployment design
  1. 1
    Edge

    HTTPS load balancer or the platform's built-in TLS

  2. 2
    API containers

    Readiness on /readyz; scales on requests

  3. 3
    Worker containers

    Always running; scales on queue depth

  4. 4
    Data services

    Managed Postgres with pgvector, managed Redis, object storage

  5. 5
    Platform

    Secret manager, logs, traces, budget alerts

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Run tests and the eval set~1h
  2. 2
    Demonstrate a failure and recovery~1h
  3. 3
    Capture a redacted trace~1h
  4. 4
    Write the migration and rollback checklist~1h
  5. 5
    Deploy or document with teardown~1h

Key points

  • Record real output from tests and evals; a claim without evidence is not a result.
  • A failure demo shows the symptom, the signal that caught it, the recovery and the final state.
  • Traces you share must hide user content, tokens and personal data, but keep IDs and timings.
  • Migrations follow expand then contract, so the previous release can still run during a rollback.
  • Every resource you create has a matching teardown step, including cloud resources that cost money.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
docker compose up -d --build
docker compose run --rm api alembic upgrade head
docker compose run --rm api python -m app.seed --tenants contoso fabrikam
docker compose run --rm api pytest -q
docker compose run --rm api python -m evals.run --out evals/results.json
# teardown: stop containers and delete volumes
docker compose down -v

The whole local verification run, from a clean start to a clean teardown.

Reading the eval results

Step 1: run the eval runner after seeding both tenants. Step 2: read each metric on its own. Recall of 0.95 means one expected chunk was missed; inspect that case's chunking before touching prompts. Step 3: citation accuracy matches recall, so the fake model cites what it retrieves. Step 4: canary leaks are zero, which is the only acceptable value. Step 5: commit the file with the code version so the next change can be compared. The numbers below are example output from synthetic fixtures.

json
{
  "commit": "3f2a91c",
  "cases": 20,
  "retrieval_recall_at_5": 0.95,
  "citation_accuracy": 0.95,
  "no_source_correct": "6/6",
  "canary_leaks": 0,
  "latency_ms": {"p50": 42, "p95": 118},
  "tokens": {"input": 8120, "output": 1430},
  "failed_cases": ["contoso-07"]
}

A redacted trace of a retried chat request

Step 1: start the API with FAKE_MODEL_FAILURES=429 and console span export. Step 2: send one chat request as a contoso user. Step 3: read the trace. Retrieval took 9 ms and returned three chunks; the first model attempt failed with 429; the retry after a jittered back-off succeeded. Step 4: confirm the redaction: IDs, timings and counts are present, but no question text, chunk text or email appears.

text
trace 7c1e...  request_id=req_91b2  tenant=t_contoso  user=u_3f (hashed)
  POST /chat                     612 ms  OK
    auth.verify                    3 ms  OK
    retrieval.search               9 ms  OK   k=5 hits=3 embedding_version=fake-v1
    model.stream attempt=1         4 ms  ERROR provider.status=429 retryable=true
    retry.backoff                410 ms
    model.stream attempt=2       170 ms  OK   input_tokens=402 output_tokens=31
    sse.send                     178 ms  OK   events=citation:3 delta:31 complete:1

Quick reference

  • Use with TestClient(app) as client so lifespan startup and shutdown run in tests
  • app.dependency_overrides swaps auth and the model for test doubles
  • Score recall, citation accuracy, no-source handling and canary leaks separately
  • FAKE_MODEL_FAILURES=429,429 drives the retry drill; docker compose kill worker drives the crash drill
  • Trace attributes: IDs, timings, counts, status; never prompts, chunks or headers
  • Migrations: expand, deploy code, contract later; rollback = previous image
  • Run alembic upgrade head as its own release step
  • Teardown: docker compose down -v locally; reverse creation order in the cloud

Common mistakes

  • Dropping or renaming a column in the same release that stops using it, which makes rollback fail.
  • Sharing a trace export that still contains the prompt, retrieved chunks or an Authorization header.
  • Creating cloud resources for a demo and leaving them running with no teardown list.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why use with TestClient(app) as client in tests?

Question 2

2After killing the worker mid-job, what evidence shows a correct recovery?

Question 3

3Which change is safe to ship in the same release as the code that stops using a column?

Question 4

4What is the safest way to keep user content out of traces?

Question 5

5What must a deployment plan include besides the deploy steps?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the teardown checklist for both the local stack and a cloud deployment of the capstone.

  2. Exercise 2medium

    Write a pytest that sets the fake model to fail once with 429 and asserts the chat stream still ends with a complete event.

  3. Exercise 3hard

    Plan an expand and contract migration that renames documents.filename to original_name with no downtime and a safe rollback at every step.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I have to deploy to the cloud to finish the capstone?
No. A real deployment costs money, so a written design with the service mapping, secrets, probes, migrations and a teardown list is an acceptable deliverable.
What eval scores count as good enough?
Canary leaks must be zero and no-source cases should all pass. For recall and citations, set a baseline on your fixtures and treat any drop as a regression to investigate.
Should migrations run when the app starts?
Not in production. Several instances would race, and a failed migration should stop the release. Run them as a separate step before the new version takes traffic.
What should I do if a migration fails halfway?
Stop the release, keep the old version serving, and inspect the database state. Prefer a forward fix; downgrade only if you tested it and no new data depends on the change.

Go deeper

ShareXLinkedInWhatsApp