Skip to content
Visual explainer 4h to learn 4 steps

Reproducible deployment and recovery drills for a RAG agent

Run the API, database and fixture model reproducibly with Docker Compose and rehearse backup, restore and dependency-failure recovery.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 31 of 34

In short

A reproducible deployment means anyone can start the same API, PostgreSQL with pgvector and fixture model from one Compose file and get the same results. Recovery means you have practised restoring the database from a backup and know what the assistant does when a source is invalid or a dependency is down. Both are rehearsed locally first, and a hosted option is documented without being required.

Explained simply

Reproducible means that anyone on the team can start the same assistant on their laptop and get the same results. Three parts are needed: the API, PostgreSQL with the pgvector extension, and the fixture model, a stand-in that always gives the same reply. Docker Compose starts all three from one file with one command.

Things will break. The database disk fills up, a model provider has an outage, someone loads a document that cannot be parsed. Recovery is about knowing in advance what happens and how to fix it, and having tried it once when nothing was on fire.

The most important drill is restoring the database. A backup file you have never restored is a hope, not a backup. So you take a dump, restore it into a fresh database, and run a few golden test cases against it to prove it works.

You can also run the stack on a hosted platform. That usually costs money, so the local Compose stack stays the reference. Document the hosted option, but keep everything testable for free.

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

LayersThe local stack
  1. 1
    api

    FastAPI app, health and readiness endpoints

  2. 2
    fixture-model

    Deterministic stub with the model interface

  3. 3
    db

    PostgreSQL with pgvector, health checked

  4. 4
    Volumes

    Database data and backup folder

CycleRecovery drill
  1. 1
    Back up

    pg_dump custom format

  2. 2
    Break something

    Stop a dependency or load a bad source

  3. 3
    Observe

    Errors are user-safe; health reports it

  4. 4
    Restore

    pg_restore into a fresh database

  5. 5
    Verify

    Golden smoke cases pass again

  6. Back to step 1
MapFailure and expected behaviour
Dependency failures
  • Model unavailable
    • Readiness false
    • model_unavailable error
    • Optional fixed-RAG extract fallback
  • Database down
    • Readiness false
    • Service error with request ID
    • No model-only answers
  • Tool timeout
    • Partial answer or escalation
    • tool_timeout code in trace
  • Invalid source
    • Ingest marks it failed
    • Index unchanged

In depth

The Compose stack, step by step

Prerequisites: Docker with the Compose plugin, Git and the repository. The compose file defines db, api and, if the stub is a separate service, fixture-model. Pin image tags, including the pgvector image with its PostgreSQL version. Give the database a health check using pg_isready, and make the API depend on it with condition service_healthy. Put secrets in an untracked .env file and commit an .env.example with placeholders.

Steps: docker compose up -d --wait starts the stack and waits for health checks. Then run migrations, load the synthetic corpus, and call GET /health and a sample POST /ask. Evidence: healthy services in docker compose ps, a JSON answer with citation IDs and a request ID. Cleanup: docker compose down stops the stack; adding -v also deletes the database volume.

  • docker compose up -d --wait
  • docker compose ps shows healthy
  • Load fixtures, then call /health and /ask
  • docker compose down -v removes data too

The API container

FastAPI's container guide builds an image from a slim Python base, installs pinned requirements first to use the layer cache, then copies the app and starts it with the fastapi run command (or Uvicorn directly). Run one process per container and let the platform scale containers. The app reads DATABASE_URL and MODEL_MODE from environment variables, with fixture as the default so a fresh checkout never calls a paid model.

Expose two checks. Liveness (is the process up) returns 200 if the app can respond at all. Readiness (can it serve) checks the database connection, the active release and the model client. Keep them separate so a model outage marks the service not ready without the platform restarting a healthy process over and over.

Backup and restore with pg_dump

pg_dump writes a logical backup of one database; the custom format (-Fc) is compressed and lets pg_restore pick objects and run in parallel. pg_dump does not include roles or other cluster-wide settings; pg_dumpall --globals-only covers those. The dump includes the CREATE EXTENSION for pgvector, so the target server must have pgvector installed.

The drill: take a dump, create a fresh database, restore into it, then point a copy of the API at it and run smoke cases. Record the dump size, how long the restore took and whether smoke cases passed. That time is your realistic recovery time for this data size. Hosted databases usually add automated backups and point-in-time recovery; document what your chosen provider offers rather than assuming.

FlowRestore drill with evidence
  1. 1
    pg_dump -Fc

    Write kb.dump, note size

  2. 2
    createdb kb_restore

    Fresh empty database

  3. 3
    pg_restore

    Load dump, note duration

  4. 4
    Count rows

    documents, chunks, vectors match

  5. 5
    Smoke cases

    Golden subset passes

Drills for invalid sources and unavailable dependencies

Invalid source drill: drop a malformed file into the ingest folder and run ingestion. Expected evidence: the file is recorded as failed with a reason, nothing from it reaches the index, and existing documents still answer. Unavailable model drill: stop the fixture-model service or set the model URL to a closed port. Expected: readiness fails, /ask returns a user-safe error code such as model_unavailable with the request ID (or a documented fallback), and no answer is made up. Database down drill: stop db; expected: readiness fails and the API returns a service error, never a model-only answer without citations or access checks.

After each drill, restart the service and confirm smoke cases pass. Write the results in a short runbook: trigger, symptom, expected behaviour, recovery steps, time taken.

  • Bad source: logged as failed, not indexed
  • Model down: safe error, readiness false
  • DB down: no ungrounded answers
  • Record each drill in the runbook

Learn it in 4 short steps

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

  1. 1
    Run the stack with Docker Compose~1h
  2. 2
    Document a hosted option~1h
  3. 3
    Back up and restore PostgreSQL~1h
  4. 4
    Drill invalid sources and unavailable dependencies~1h

Key points

  • Pin image tags (for example a pgvector image with a fixed PostgreSQL version) so every run uses the same software.
  • Use Compose health checks and depends_on with service_healthy so the API starts only after the database is ready.
  • A backup counts only after you have restored it and run smoke tests against the restored copy.
  • When the model or database is down, return a clear, user-safe error or a documented fallback, never a guessed answer.
  • Hosted deployment is optional; describe it, but keep the local fixture mode as the reference.

Key terms

Tap a card to flip it. 0/5 known

Examples

yaml
services:
  db:
    image: pgvector/pgvector:0.8.7-pg18
    environment: {POSTGRES_USER: app, POSTGRES_PASSWORD: change-me, POSTGRES_DB: kb}
    healthcheck: {test: ["CMD-SHELL", "pg_isready -U app -d kb"], interval: 5s, retries: 10}
    volumes: [dbdata:/var/lib/postgresql]
  api:
    build: .
    environment: {DATABASE_URL: "postgresql://app:change-me@db:5432/kb", MODEL_MODE: fixture}
    depends_on: {db: {condition: service_healthy}}
    ports: ["8000:8000"]
volumes: {dbdata: {}}

Placeholder password; put real secrets in an untracked .env file.

Running the backup and restore drill

Prerequisites: stack running with fixtures loaded. Step 1: dump the kb database from the db container to a local file. Step 2: create kb_restore and restore into it. Step 3: compare row counts between kb and kb_restore. Step 4: start the API with DATABASE_URL pointing at kb_restore and run the smoke subset. Expected evidence: equal counts and passing cases. Cleanup: drop kb_restore and delete the dump if it is not needed.

bash
docker compose exec -T db pg_dump -U app -Fc kb > kb.dump
docker compose exec -T db createdb -U app kb_restore
docker compose exec -T db pg_restore -U app -d kb_restore < kb.dump
docker compose exec -T db psql -U app -d kb_restore -c "SELECT count(*) FROM chunks"
# point a test API at kb_restore and run smoke cases
pytest evals -k smoke
docker compose exec -T db dropdb -U app kb_restore

Unavailable model drill

Step 1: docker compose stop fixture-model. Step 2: call GET /ready; expect 503 with a reason naming the model. Step 3: call POST /ask; expect an error body with code model_unavailable and the request ID, and no answer text. Step 4: check the trace shows the failed model span and the outcome code. Step 5: docker compose start fixture-model, wait for ready, and run smoke cases. Record the total time from stop to green.

bash
docker compose stop fixture-model
curl -s -o /dev/null -w "%{http_code}\n" localhost:8000/ready   # expect 503
curl -s -X POST localhost:8000/ask -H "Authorization: Bearer test-token" \
  -H "Content-Type: application/json" -d '{"question": "How many leave days?"}'
docker compose start fixture-model
pytest evals -k smoke

Quick reference

  • Pin image tags; never rely on latest
  • healthcheck with pg_isready plus depends_on condition: service_healthy
  • docker compose up -d --wait starts and waits for healthy services
  • pg_dump -Fc for a compressed custom-format backup; restore with pg_restore
  • pg_dump skips roles; use pg_dumpall --globals-only for those
  • Target server needs pgvector installed before restoring a dump that uses it
  • Separate liveness and readiness; a model outage means not ready, not restart
  • Untested backup = no backup: restore and run smoke cases

Common mistakes

  • Using latest image tags, so the stack silently changes between runs.
  • Taking backups that are never restored, then discovering at the worst moment that they are incomplete.
  • Letting the API answer from the model alone when the database is down, which removes citations and access control.

Quick quiz

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

Question 1

1What does docker compose down -v do that docker compose down does not?

Question 2

2The model provider is down. What should /ask return?

Question 3

3Which statement about pg_dump is true?

Question 4

4Why separate liveness from readiness?

Question 5

5What proves that a backup works?

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 .env.example file for the stack with placeholder values only.

  2. Exercise 2medium

    Write a FastAPI readiness endpoint that checks the database and model client and returns 503 with reasons when either fails.

  3. Exercise 3hard

    Write a runbook entry for the database-down drill: trigger, expected symptoms, recovery steps, evidence and time target.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Do I need Kubernetes for this?
No. Docker Compose is enough for local runs and small deployments. A managed container service is a reasonable hosted option; choose based on your team and budget.
How often should I run recovery drills?
After any change to the database setup, and on a regular schedule such as once a quarter. Record the time taken so you notice when recovery gets slower.
Can I use a hosted model in the Compose stack?
Yes, set MODEL_MODE and an API key in your local .env file. It may cost money, so keep fixture mode as the default for tests and CI.

Go deeper

ShareXLinkedInWhatsApp