Production Deployment
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Getting the code running on a server is the easy half. The harder half is being able to ship a change without fear, notice when it's wrong, undo it quickly and switch the feature off without a deploy. This final lesson of the module packages the service in a container, adds the files and checks around it, and ends with a launch plan and a checklist you can reuse. We built the image and ran the container for real, and we say what that did and didn't prove.
What you'll learn
- A container for the service that runs as a non-root user and exits when misconfigured.
- Liveness versus readiness, and why they differ.
- Secrets and configuration at deploy time.
- A rollout plan: shadow, canary, full, and how to roll back.
- What the in-process pieces can't do once you run more than one copy.
Before you start
The entry point
The service is built by a factory function. uvicorn main:build --factory calls it once at start-up, so configuration errors stop the process before it accepts traffic:
"""Entry point. Run with: uvicorn main:build --factory --host 0.0.0.0 --port 8000"""
import logging
import os
import sys
import anthropic
from costs import Prices
from observability import JsonFormatter
from service import create_app
from settings import ConfigError, Settings
ORDERS = {"A100": {"status": "shipped", "carrier": "DHL"}, "A101": {"status": "processing", "carrier": None}} # replace with your data source
def prices_from_env() -> Prices:
try:
return Prices(float(os.environ["AI_PRICE_INPUT_PER_MTOK"]), float(os.environ["AI_PRICE_OUTPUT_PER_MTOK"]))
except (KeyError, ValueError):
raise ConfigError("Set AI_PRICE_INPUT_PER_MTOK and AI_PRICE_OUTPUT_PER_MTOK from the official pricing page.") from None
def build():
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)
settings = Settings.from_env() # raises ConfigError: the container exits instead of limping along
# One layer of retries only: the Gateway owns them, so the SDK's own are switched off.
client = anthropic.Anthropic(api_key=settings.api_key, timeout=settings.request_timeout, max_retries=0)
return create_app(settings, client, ORDERS, prices_from_env())
Two decisions here are worth repeating. The SDK's own retries are switched off (max_retries=0) because the gateway owns retry policy (lesson 8.8). And the prices come from the environment, so a missing price stops the start instead of silently reporting zero cost.
The container
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
RUN useradd --create-home --uid 10001 app
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY --chown=app:app *.py ./
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status == 200 else 1)"
CMD ["uvicorn", "main:build", "--factory", "--host", "0.0.0.0", "--port", "8000"]
- Small base image and pinned requirements. The requirements file sets a lower bound and a ceiling for the SDK major version, so a future major release doesn't arrive unannounced.
- Non-root. The process runs as an unprivileged user (id 10001). If someone gets code execution through a bug, they start with fewer rights.
- Only the code is copied. No
.env file goes into the image. Anything in an image can be read by anyone with the image.
- A health check that calls
/healthz from inside the container using only the standard library.
And a compose file for running it on one machine, with the secret file kept outside the image and the container locked down:
services:
assistant:
build:
context: ..
dockerfile: deploy/Dockerfile
env_file: .env # never committed; copy .env.example to .env and fill it in
ports:
- "127.0.0.1:8000:8000" # reachable from this machine only; put a reverse proxy with TLS in front
restart: unless-stopped
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 512m
The port is bound to 127.0.0.1, so only the same machine can reach it. In front of it you'd put a reverse proxy that terminates TLS. The file also drops all Linux capabilities, sets no-new-privileges, makes the filesystem read-only and caps memory. And here's the template for the environment file, with no values in it:
# Copy to .env and fill in. Never commit .env.
ANTHROPIC_API_KEY=
SERVICE_TOKEN= # at least 24 random characters, e.g. from: python -c "import secrets; print(secrets.token_urlsafe(32))"
AI_MODEL=claude-sonnet-5-5
AI_FALLBACK_MODEL=claude-haiku-5-5
AI_SCREEN_MODEL=claude-haiku-5-5
AI_TIMEOUT_SECONDS=30
AI_MAX_ATTEMPTS=3
AI_MAX_OUTPUT_TOKENS=800
AI_DAILY_BUDGET_USD=25
AI_USER_DAILY_BUDGET_USD=0.50
AI_DISABLED=0 # set to 1 to switch the assistant off without a deploy
AI_PRICE_INPUT_PER_MTOK= # copy both prices for your model from the official pricing page
AI_PRICE_OUTPUT_PER_MTOK=
What we ran
We built the image with Docker 29 on the development machine and ran it with a dummy key and token (no real key was used or needed). Results:
GET /healthz returned 200, and GET /readyz returned {"status":"ready"}.
POST /v1/answer without the token returned 401.
- The container's configured user was
app. A few seconds after launch Docker reported the health check as "starting"; we didn't wait for the first full interval, so we haven't seen it report "healthy".
- A container started with a missing API key and a too-short token exited immediately with the
ConfigError message. That is the behaviour you want from a bad deploy.
We did not test a real cloud deployment, TLS, a reverse proxy, running several replicas or any real model call from the container. One more observation: uvicorn's own access log lines are plain text, not our JSON format. If your log pipeline needs uniform JSON, configure uvicorn's logging or turn its access log off and log requests in the app.
Liveness and readiness
They answer different questions, and mixing them up causes outages:
/healthz (liveness): "is the process running?". It makes no outbound calls. If it failed whenever the model API was down, your orchestrator would restart healthy containers in a loop.
/readyz (readiness): "should traffic be sent here?". Ours reports not ready if the kill switch is on or the circuit breaker is open, with the reasons, so a load balancer stops routing to an instance that can't help. It deliberately doesn't call the model API on every probe, which would cost money and could trip rate limits.
The kill switch
Set AI_DISABLED=1 and the service returns a clear 503 for answers without making any model call. That's a configuration change and a restart, not a code deploy, and it's the control you'll be glad of the first time a prompt change misbehaves or a bill spikes. Practise using it. A switch nobody has tested is a hope.
Checks before every deploy
The preflight script from lesson 8.2 runs in the pipeline before the image is built: it scans for secrets, checks that .env is ignored by git and requires a recent evaluation report that meets the pass rate and has its security cases passing. A deploy that fails preflight doesn't proceed. We tested it with a leaked fake key, a missing report and a failing security case, and as a real subprocess exit code.
Rolling out safely
- Shadow. The service drafts, but people don't see the drafts, or they see them and write their own reply. You compare what it said with what people did. No customer is affected.
- Assisted. People see drafts and approve or edit each one. Track approval rate, edit rate and "needs a person" rate.
- Canary. For anything that sends without review, route a small share of traffic to the new version and watch error rate, latency, cost and quality metrics before widening.
- Full, with the kill switch ready.
Roll back by deploying the previous image tag, so tag images with a version or commit and keep the last few. Prompts, model names and thresholds are configuration, so they roll back too, which is a reason to version them with the code. A model or prompt change deserves the same care as a code change: run the evaluation set first and compare with the baseline.
What breaks when you run more than one copy
Our teaching service keeps its budgets, response cache, metrics and circuit breaker in memory. That's fine for one process and wrong for several:
- A per-user budget is enforced per replica, so three replicas allow three times the allowance. Move it to a shared store such as Redis or your database, with atomic increments.
- Each replica's breaker opens independently. That's often acceptable, but be aware of it.
- Metrics should be exported to a shared system, not read from one instance's
/metricsz.
- A restart loses in-memory budgets and cache.
None of this is hard, but it's the kind of thing that works in testing and surprises you in production.
Data and compliance
Know where customer text goes: your logs, your database and Anthropic's API. Anthropic's documentation lists data-retention eligibility per feature (for example, the Batches API is documented as not eligible for zero data retention, with a 29-day retention), so read the page for each feature you use against your own obligations. Decide how long you keep stored conversations, who can read them and how a customer's data is deleted. This course doesn't give legal advice; involve whoever handles privacy for your organisation.
After launch
- A dashboard with error rate, p95 latency, cost, cache hit rate, fallback rate, "needs a person" rate and flagged messages.
- Alerts that go to a person who can act, and a short runbook for each: what it means, what to check, how to switch the feature off.
- The evaluation set running on a schedule against the live model, since models and prompts change.
- A habit of turning every incident into a new evaluation case.
- A review of the spend and the per-user limits each month.
The checklist
| Area | Before you launch | Lesson |
| Config | Fails at start-up on bad values; secrets hidden in logs and reprs | 8.1 |
| Security | Auth on every route; key server-side; preflight in CI; threat model written | 8.2 |
| Injection | Untrusted text framed as data; screen fails closed; attack cases in evals | 8.3 |
| Inputs | Size limits, cleaning, allow-listed identifiers, redaction in logs | 8.4 |
| Outputs | Stop reason checked; schema and business rules; one repair; person fallback | 8.5 |
| Evals | Tagged set, baseline, must-pass security tag, run before release | 8.6 |
| Observability | Request IDs, JSON logs without customer text, metrics, alerts with minimum volume | 8.7 |
| Reliability | One retry layer, fallback, breaker, calm errors, idempotent side effects | 8.8 |
| Performance | Measured TTFT and total; caches that skip personal data; limits on concurrency | 8.9 |
| Cost | Prices in config; per-user and daily budgets; platform limits; cost alerts | 8.10 |
| Deploy | Non-root container, health and readiness, kill switch tested, rollback ready | 8.11 |
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A small team deploys the assistant in shadow mode on a Tuesday. For a week it drafts replies that nobody sees, and the team compares them with what staff wrote. They find it handles order-status questions well and sends exchange questions to a person too often, so they add evaluation cases and adjust the prompt. In week two staff see drafts and approve them. After a month of stable numbers they allow auto-sending only for status questions. One Friday the daily cost alert fires, and they set AI_DISABLED=1 in under two minutes while they investigate. Nobody had to write a patch to stop it.
Mistakes to avoid
- Baking secrets into an image or committing a
.env.
- Making liveness depend on the model API.
- Launching to everyone at once with no way to switch it off.
- In-memory budgets across several replicas.
- Changing a prompt or model without running the evaluation set.
- No owner for the alerts.
Security notes
Run as non-root with a read-only filesystem, drop capabilities, keep the service on a private network behind TLS and authenticate every route that costs money. Rotate keys on a schedule and after any suspected leak. Keep separate keys and workspaces for production, staging and development.
Cost and speed
A container like this is small and cheap to run. The model calls dominate the cost. Use the budgets and alerts from lesson 8.10, and review the numbers during the shadow phase so the first real bill holds no surprises.
Key takeaways
- Build a minimal, non-root image with no secrets in it; fail at start-up on bad configuration.
- Liveness doesn't call the model; readiness reflects whether traffic should be sent.
- Have a kill switch and practise it. Roll out in shadow, assisted, canary, full.
- Move budgets, caches and metrics to shared stores before running more than one replica.
- Turn every incident into an evaluation case.
Lesson recap: ship a safe image, roll out in stages, and learn from every incident.
Quick quiz
- Why shouldn't
/healthz call the model API?
- What does the container do when the API key is missing?
- Why is an in-memory per-user budget a problem with several replicas?
- What is the purpose of shadow mode?
- How do you roll back a bad release?
Answers and explanations
- If it failed whenever the API had trouble, the orchestrator would restart healthy containers. Liveness should only say the process is running.
- It exits immediately with a configuration error, so the failed deploy is visible instead of serving broken traffic.
- Each replica keeps its own count, so total allowed spend is multiplied by the number of replicas. A shared store with atomic updates fixes it.
- To see what the system would do on real traffic, and compare with what people did, without any customer being affected.
- Deploy the previous tagged image. Because prompts, model names and thresholds are configuration kept with the code, they roll back too.
Official references and further reading
Related tutorials