Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
An endpoint is not a deployment. Take a RAG service that anyone can call on your bill and get it ready for a public address: an X-API-Key check, a start-up rule that refuses ENV=prod with no key, /health and /ready, one JSON log line per request, only Caddy published, and a smoke test that prints five PASS lines.
What you will learn
- Lock paid endpoints with a service key checked by secrets.compare_digest, and refuse to start in production without one
- Give the platform two checks: /health for alive and /ready for loaded
- Keep the API private behind Caddy, with HTTPS and no buffering for streamed answers
- Prove every deploy with a smoke test against the real address
Before you start
- A Production FastAPI for an ML Model
- Streaming LLM Answers From FastAPI
Our help-centre RAG service answers questions, streams its words and runs in Docker. Can we put it on a public address exactly as it is? No. In this article we lock it with a service key, add health and readiness checks, write one JSON log line per request, put Caddy in front for HTTPS, and prove each deploy with a smoke test.
The project is docs-answer, the finished version. It runs with a stand-in test model, so you need no key. No cloud account is used, and Docker wasn't running on the machine where the outputs were captured. So the production files and commands are shown as they are, and the console output comes from running the same code without Docker.
An endpoint is not a deployment
Four things are wrong with putting the service online as it is:
- Anyone who finds the address can call
/api/ask, and every call spends your model budget. - It's plain HTTP, so anything sent can be read on the way.
- Port 8000 is open to the world, with nothing in front of it.
- If it crashes at night, nobody knows.
Failure first: wide open
python demo.py ask "Where do you ship?"
=== ask: The whole answer at once ===
[stand-in test model, help-centre docs]
"answer": "We ship to all 50 United States, to military addresses (APO and FPO) and to Canada. A PO box works for standard shipping only. See \"International shipping\" below for Canada.",
{"id": "1e4c89161009", "method": "POST", "path": "/api/ask", "status": 200, "ms": 2432}
With no service key set, which is the development default, we ask with no header and no key, and get the full answer and a 200. On a laptop that's fine. On the internet, anyone can do this, as often as they like, on your bill.
The service key
# routers/deps.py
def key_is_valid(given: str | None) -> bool:
if not settings.service_api_key: # no key configured: open, for local development only
return True
return given is not None and secrets.compare_digest(given, settings.service_api_key)
def require_api_key(x_api_key: str | None = Header(default=None)) -> None:
if not key_is_valid(x_api_key):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing or wrong X-API-Key header")
def websocket_key_is_valid(websocket: WebSocket) -> bool:
return key_is_valid(websocket.headers.get("x-api-key"))
With no key configured, everything gets through. That's for local development only, and the next step makes sure production can't run like that. Otherwise the header is compared with secrets.compare_digest, which takes the same time whether a guess is close or not, so nobody can find the key by timing the answers. require_api_key turns a bad key into a 401. The WebSocket checks the same header and closes the connection if it's wrong.
This key is for the apps that call your service. It's a different key from your model provider's.
Refuse to start open
# main.py
@asynccontextmanager
async def lifespan(app: FastAPI):
if settings.env == "prod" and not settings.service_api_key:
raise RuntimeError("ENV=prod needs SERVICE_API_KEY: refusing to start an open, paid endpoint")
# Runs once at start-up, not on every request: read the docs, load the embedding model, pick the chat model.
start = time.perf_counter()
app.state.retriever = build_retriever(load_folder(settings.docs_dir))
app.state.model = get_model()
log.info("ready in %.1fs: %s retriever, %s model, env=%s", time.perf_counter() - start,
app.state.retriever.name, app.state.model.name, settings.env)
yield
app = FastAPI(title="docs-answer", version="1.0.0", lifespan=lifespan,
docs_url="/docs" if settings.env == "dev" else None, redoc_url=None)
app.middleware("http")(log_requests)
app.include_router(health.router)
app.include_router(ask.router, dependencies=[Depends(require_api_key)])
app.include_router(stream.router, dependencies=[Depends(require_api_key)])
app.include_router(ws.router) # checks the key itself: a WebSocket has no 401
If ENV is prod and there's no service key, the app raises an error at start-up. A crash at deploy time is much better than an open door for a month. In prod the /docs page is switched off too. The ask and stream routers get require_api_key; health stays open, because the platform has to call it.
Three keys, three answers, one log line each
# logs.py
async def log_requests(request: Request, call_next):
request_id = request.headers.get("x-request-id") or uuid.uuid4().hex[:12]
start = time.perf_counter()
response = await call_next(request) # for a stream this is when the first byte is ready
response.headers["x-request-id"] = request_id
log.info(json.dumps({"id": request_id, "method": request.method, "path": request.url.path,
"status": response.status_code, "ms": round((time.perf_counter() - start) * 1000)}))
return response
python demo.py auth
=== auth: 401 without the service key ===
[stand-in test model, help-centre docs]
no key -> 401 Missing or wrong X-API-Key header
wrong key -> 401 Missing or wrong X-API-Key header
right key -> 200 We ship to all 50 United States, to military addresses (APO
/health -> 200 (no key needed: the platform calls it)
{"id": "6d662281fa8f", "method": "POST", "path": "/api/ask", "status": 401, "ms": 6}
{"id": "9895735ec115", "method": "POST", "path": "/api/ask", "status": 401, "ms": 1}
{"id": "79c1e05a6962", "method": "POST", "path": "/api/ask", "status": 200, "ms": 2426}
{"id": "77a455455367", "method": "GET", "path": "/health", "status": 200, "ms": 2}
No key, 401. A wrong key, 401. The right key, 200 and the answer. /health, 200 with no key. Below that, one JSON line per request: an id, the path, the status and the milliseconds. The 401s took a few milliseconds, because the model was never called.
Alive, and ready
from fastapi import APIRouter, Request, Response, status
router = APIRouter(tags=["health"])
@router.get("/health")
def health() -> dict:
"""Liveness: the process answers. Cheap, so the platform can call it every few seconds."""
return {"status": "ok"}
@router.get("/ready")
def ready(request: Request, response: Response) -> dict:
"""Readiness: the index and the model are loaded, so traffic may be sent here."""
state = request.app.state
retriever, model = getattr(state, "retriever", None), getattr(state, "model", None)
if retriever is None or model is None:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "loading"}
return {"status": "ready", "chunks": len(retriever.chunks), "retriever": retriever.name, "model": model.name}
/health is liveness: the process answers. /ready is readiness: the search index and the model are loaded. While they're still loading it answers 503, so no traffic is sent yet. A failed health check means "restart me". A failed ready check means "not yet". The same pair for a classic model is in A Production FastAPI for an ML Model.
The production overlay and the Caddyfile
# Production overlay. Use it on top of compose.yaml:
# docker compose -f compose.yaml -f deploy/compose.prod.yaml up -d --build
# Only Caddy is public (80 and 443, HTTPS certificates done for you); the API is reachable only inside the network.
services:
api:
command: ["serve"] # uvicorn with 2 workers and proxy headers, see demo.py
ports: !reset [] # not published: everything goes through Caddy
restart: unless-stopped # back after a crash or a reboot
environment:
ENV: prod
SERVICE_API_KEY: ${SERVICE_API_KEY:?set SERVICE_API_KEY in .env first}
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
caddy:
build:
context: ./deploy
dockerfile: Caddy.Dockerfile
image: aie-s12l04-docsanswer-caddy
restart: unless-stopped
ports: ["80:80", "443:443"]
environment:
DOMAIN: ${DOMAIN:-localhost}
volumes:
- caddy_data:/data # certificates survive a restart
depends_on:
api:
condition: service_healthy
volumes:
caddy_data:
# DOMAIN=answers.example.com -> Caddy gets a free Let's Encrypt certificate (DNS must point at this server).
# DOMAIN=localhost (default) -> a certificate from Caddy's own local CA, for a rehearsal on your PC.
{$DOMAIN} {
reverse_proxy api:8000 {
# pass every streamed piece on at once, never buffer the answer
flush_interval -1
}
}
ports: !reset []: the API publishes no port. You can only reach it through Caddy.restart: unless-stoppedbrings it back after a crash or a reboot.${SERVICE_API_KEY:?...}: if the key is missing from.env, compose stops with an error before anything starts.- Caddy is the only service with ports, 80 and 443. Give it a domain name and it gets an HTTPS certificate for you. It waits until the API's health check passes.
flush_interval -1passes every streamed piece on at once, so streaming still works behind the proxy.
A smoke test after every deploy
python demo.py smoke
python -m pytest tests/test_deploy.py -v
python demo.py tests
http://127.0.0.1:62846 (on a server: python scripts/smoke.py https://your-domain)
PASS health 200
PASS ready {"status":"ready","chunks":27,"retriever":"embeddings","model":"stand-in"}
PASS no key is refused 401
PASS ask with key 200
PASS stream arrives in pieces first words 0.61s, whole 2.44s
tests/test_deploy.py::test_paid_endpoints_need_the_key PASSED [ 14%]
tests/test_deploy.py::test_health_and_ready_stay_open PASSED [ 28%]
tests/test_deploy.py::test_websocket_without_key_is_closed PASSED [ 42%]
tests/test_deploy.py::test_prod_refuses_to_start_without_a_key PASSED [ 57%]
tests/test_deploy.py::test_requests_carry_an_id PASSED [ 71%]
tests/test_deploy.py::test_production_overlay_publishes_only_caddy PASSED [ 85%]
tests/test_deploy.py::test_smoke_script_passes_against_a_live_server PASSED [100%]
7 passed in 10.53s
21 passed in 13.53s
scripts/smoke.py takes an address and checks it. Here it runs against a local server started by demo.py smoke: health 200, ready with 27 chunks and the embeddings retriever, no key refused with a 401, ask with the key 200, and the stream arriving in pieces with first words at 0.61 s and the whole answer at 2.44 s. The seven deploy tests check the rules, and all 21 tests pass with no key and no network.
The real server, step by step
deploy/DEPLOY.md has the steps for one Linux server with Docker:
- A server with a firewall that opens only SSH from your address, and ports 80 and 443.
- A name: a DNS record pointing at the server.
- The images, pushed with a version tag. Never deploy
latest. - The secrets, in a
.envfile only you can read (chmod 600 .env). - Start it with the same compose command, with your domain set.
- The smoke test, against the real name: five PASS lines.
- Rollback: start the previous tag again.
On a managed platform the idea is the same. Its HTTPS endpoint replaces Caddy, and its secret store replaces .env.
Common mistakes
- Shipping with the dev default "no key means open". Make production refuse to start without one.
- Comparing keys with
==. Usesecrets.compare_digest. - Locking
/healthbehind the key. The platform can't call it, and marks a healthy service as dead. - Publishing the API port next to the proxy. The HTTPS front door means nothing if the back door is open.
- Calling a deploy done because the command finished. Done is five PASS lines against the real address.
Quick recap
| Red card | Fix |
|---|---|
| Anyone can spend your budget | X-API-Key with compare_digest; prod refuses to start without a key |
| Plain HTTP, port 8000 open | Only Caddy public, HTTPS, API not published |
| Nobody knows it's down | /health and /ready, JSON log line per request |
| Did the deploy work? | Smoke test after every deploy |
Try it yourself
- Run
python demo.py auth, thenpython demo.py smoke. - Set
ENV=prodwith no key, start the service, and read the error. - On a machine with Docker, start the production overlay and run
python scripts/smoke.py https://localhost.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.