Chapter 5 · Ship It
Deployment and Production Readiness
- Page 20 of 22
- 33 min read
Your API passes its tests, runs in Docker and is built by GitHub Actions. It is still only useful to you. Deployment is the step that puts it on a computer that stays on, with a public HTTPS address, real secrets, a real database and a way to find out when it breaks. For an AI product it is also where surprises live: a model that needs more memory than the free plan has, a first request that waits for a sleeping server, an LLM key that leaks into a log, a bad release that you cannot undo.
This page does two things. First it makes your app deployable on your own machine, with everything verified here: settings from the environment, a PORT, health and readiness checks, JSON logs, migrations at start, graceful shutdown, a smoke test and a rollback. Then it shows how those pieces map onto Render, Google Cloud Run, Railway and a VPS. The cloud steps are described, not run, because they need your account; the parts that run on any host are the ones you can really test.
What you will learn
- The difference between local, staging and production, and how to choose a host in 2026 (free tiers are smaller than they used to be).
- How to prepare an app for any platform: settings and secrets from the environment,
PORT, workers, health and readiness, JSON logs, migrations on deploy. - Graceful shutdown: what happens on
SIGTERM, shown with a real in-flight request. - A post-deploy smoke test, deploying from GitHub to Render, an image to Cloud Run, and deploying from Actions.
- Rollback with Git, backups, monitoring, cost control and a production-readiness checklist.
Local, staging and production
An environment is one complete copy of your system: code, config, database and secrets. Teams keep at least three, and the rule that matters is that they are the same code with different configuration.
| Local | Staging | Production | |
|---|---|---|---|
| Purpose | Write and debug | Rehearse the exact release | Serve real users |
| Data | Sample or fake | Fake, or anonymised copies | Real; backed up |
| Secrets | Dev keys in .env | Separate test keys with low spending caps | Real keys in the host's secret store |
| Who deploys | You | CI, on every merge | CI, on a tag, often with approval |
If you have one environment, make it staging. A staging copy that you can break without telling anyone is how you learn what your deploy really does.
Choosing a host in 2026
Free hosting has shrunk. Most "always free" plans from a few years ago are now trials, credits or paid-only, and the survivors have sharp edges. Plans change often, so check current limits on each pricing page before you decide. This is the picture at the time of writing:
| Option | Good for | Free in 2026? | Watch out for |
|---|---|---|---|
| Render | A web service from a GitHub repo, plus managed Postgres | Free web services sleep after 15 minutes without traffic. A free Postgres expires after 30 days (plus a 14-day grace period) | A slow first request after sleep; no persistent disk on the free plan |
| Google Cloud Run | Containers that scale to zero and cost almost nothing when idle | A monthly free tier; you still need a billing account | Stateless; cold starts; the port comes from PORT (8080) |
| Railway | The quickest "repo plus database" setup | A $5 trial, then a $1 per month credit | A database eats the small credit quickly |
| Fly.io | Containers close to your users | No free tier; pay as you go | You manage volumes and regions |
| Koyeb | Docker deploys with a nice UI | Closed its free plan to new users | Check before you plan around it |
| Hugging Face Spaces | Demos, especially Gradio and Streamlit | Docker Spaces need a PRO account | Not a general backend host |
| A VPS | Full control, steady cost, several apps on one machine | No; a few dollars a month | You patch, secure, monitor and back it up yourself |
For learning, Render's free plan or Cloud Run are the usual first stops. For a portfolio demo, remember that a sleeping service makes the first visitor wait up to a minute, so open the link yourself before you share it. For anything with real users, plan on paying a small, predictable amount rather than relying on a free tier. International card payments can be the real obstacle for learners in Bangladesh, so check what each platform accepts before you build on it.
Preparing the app: the twelve-factor habits
Every platform asks the same few things of your app, and they are old, boring habits (they come from the "twelve-factor app" method). The review API from the Docker page, extended with a database, now follows them:
| Platform expectation | What the app does |
|---|---|
| Config lives in the environment | settings.py reads APP_* variables; the secret has no default, so a missing key stops the start |
| Listen on the port you are given | The start script uses $PORT; Render and Cloud Run set it for you |
| Logs go to standard output | One JSON object per line; the platform collects and searches them |
| Say whether you are alive and ready | /health is cheap; /ready checks the database |
Stop cleanly on SIGTERM | The lifespan shutdown closes resources after in-flight requests finish |
| Schema changes ship with the code | Alembic runs before the server starts |
Start with a project folder and a virtual environment. The dependencies go in requirements.txt because every platform understands that file (with uv you would use uv add and a lockfile, exactly as in earlier pages).
mkdir -p ~/projects/review-api
cd ~/projects/review-api# file: requirements.txt
fastapi[standard]>=0.143
pydantic-settings>=2.10
sqlalchemy>=2.0
alembic>=1.16python -m venv .venv
source .venv/bin/activate
pip install -q -r requirements.txtSettings and secrets
All configuration sits in one Settings class from pydantic-settings, the pattern from Dependencies, Lifespan, Middleware and Settings. Three things matter for deployment. The API key has no default, so a deploy that forgot the secret fails at start instead of running unprotected. port reads the unprefixed PORT because that is what platforms inject. And a validator fixes a trap: managed Postgres hosts give you a URL starting with postgres:// or postgresql://, but SQLAlchemy 2 wants a driver name, postgresql+psycopg://.
# file: settings.py
"""Settings: every value that changes between laptop, staging and production."""
from functools import lru_cache
from typing import Literal
from pydantic import Field, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env", extra="ignore")
env: Literal["local", "staging", "production"] = "local"
version: str = "dev"
database_url: str = "sqlite:///./reviews.db"
api_key: SecretStr # no default: the app refuses to start without it
log_level: str = "INFO"
port: int = Field(8000, validation_alias="PORT") # platforms inject PORT, no prefix
@field_validator("database_url")
@classmethod
def use_psycopg_driver(cls, url: str) -> str:
# Hosts hand out postgres:// or postgresql://; SQLAlchemy 2 needs a driver name.
for old in ("postgres://", "postgresql://"):
if url.startswith(old):
return "postgresql+psycopg://" + url[len(old):]
return url
@lru_cache
def get_settings() -> Settings:
return Settings()Check both behaviours. Without the key the settings refuse to load, and the error names the missing field (printing only loc and msg keeps it free of version-specific links). With the key, a platform-style database URL is rewritten:
python -c "
from pydantic import ValidationError
from settings import Settings
try:
Settings()
except ValidationError as exc:
print([(e['loc'], e['msg']) for e in exc.errors()])
"
APP_API_KEY=x python -c "
from settings import Settings
print(Settings(database_url='postgres://user:[email protected]/reviews').database_url)
"[(('api_key',), 'Field required')]
postgresql+psycopg://user:[email protected]/reviewsNever commit real values. Keep a
.envfile for local use (it is in.gitignore, as you will see below), commit a.env.examplethat lists the names without secrets, and put production values in the host's secret store. A key that was ever in Git history must be treated as leaked and rotated, as in Git for AI Projects: Data, Models, LFS, DVC and Leaked Secrets.
JSON logs, health and readiness
Two small files carry the operational behaviour. logs.py formats every log record as one JSON line on standard output. Platforms such as Render, Cloud Run and Railway collect standard output, and a JSON line lets you filter on level or status instead of grepping prose. Never write logs to a file inside a container: the disk is disposable and nobody will read it.
# file: logs.py
"""One JSON object per log line, so a platform can search and filter the fields."""
import json
import logging
import sys
import time
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
data = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
**getattr(record, "fields", {}),
}
if record.exc_info:
data["exc"] = self.formatException(record.exc_info)
return json.dumps(data)
def setup_logging(level: str = "INFO") -> None:
handler = logging.StreamHandler(sys.stdout) # containers log to stdout, never to files
handler.setFormatter(JsonFormatter())
logging.getLogger().handlers[:] = [handler]
logging.getLogger().setLevel(level)Now main.py. Read it for four things. The lifespan opens the database engine at start and, in finally, marks the app not ready, closes the engine and logs shutdown complete. /health (liveness, "is the process alive?") does no I/O. /ready (readiness, "can I serve traffic right now?") runs SELECT 1 and returns 503 when it cannot, which tells a load balancer to stop sending requests without restarting you. A middleware logs one line per request but skips the probes, which would otherwise drown the log. The /slow endpoint stands in for a slow model call, so we can watch a shutdown with a request in flight.
# file: main.py
"""Review API, ready for production: health, readiness, JSON logs, graceful shutdown."""
import asyncio
import hmac
import logging
import time
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response
from pydantic import BaseModel, Field
from sqlalchemy import create_engine, text
from logs import setup_logging
from settings import Settings, get_settings
log = logging.getLogger("review-api")
@asynccontextmanager
async def lifespan(app: FastAPI):
settings = get_settings()
setup_logging(settings.log_level)
app.state.engine = create_engine(settings.database_url, pool_pre_ping=True)
app.state.ready = True
log.info("startup", extra={"fields": {"env": settings.env, "version": settings.version, "port": settings.port}})
try:
yield
finally:
app.state.ready = False # a load balancer should stop sending traffic first
app.state.engine.dispose()
log.info("shutdown complete", extra={"fields": {"version": settings.version}})
app = FastAPI(title="Review API", lifespan=lifespan)
@app.middleware("http")
async def access_log(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
if request.url.path not in ("/health", "/ready"): # probes would drown the log
ms = round((time.perf_counter() - start) * 1000)
log.info("request", extra={"fields": {"method": request.method, "path": request.url.path,
"status": response.status_code, "ms": ms}})
return response
SettingsDep = Annotated[Settings, Depends(get_settings)]
def require_key(settings: SettingsDep, x_api_key: Annotated[str | None, Header()] = None) -> None:
if x_api_key is None or not hmac.compare_digest(x_api_key, settings.api_key.get_secret_value()):
raise HTTPException(401, "Missing or wrong API key")
class ReviewIn(BaseModel):
text: str = Field(min_length=3, max_length=2000)
@app.get("/health")
async def health(settings: SettingsDep) -> dict[str, str]:
"""Liveness: the process is up. Cheap, no dependencies."""
return {"status": "ok", "version": settings.version}
@app.get("/ready")
def ready(request: Request, response: Response) -> dict[str, str]:
"""Readiness: can this instance serve real traffic right now?"""
try:
if not request.app.state.ready:
raise RuntimeError("shutting down")
with request.app.state.engine.connect() as conn:
conn.execute(text("SELECT 1"))
except Exception as exc:
response.status_code = 503
return {"status": "unavailable", "reason": type(exc).__name__}
return {"status": "ready"}
@app.post("/v1/reviews", status_code=201, dependencies=[Depends(require_key)])
def create_review(review: ReviewIn, request: Request) -> dict[str, int]:
with request.app.state.engine.begin() as conn:
result = conn.execute(text("INSERT INTO reviews (text) VALUES (:t)"), {"t": review.text})
return {"id": result.lastrowid}
@app.get("/v1/reviews/count")
def count_reviews(request: Request) -> dict[str, int]:
with request.app.state.engine.connect() as conn:
return {"count": conn.execute(text("SELECT COUNT(*) FROM reviews")).scalar_one()}
@app.get("/slow")
async def slow(seconds: float = 1.0) -> dict[str, str]:
await asyncio.sleep(min(seconds, 10)) # a stand-in for a slow model call
return {"status": "done"}Migrations on deploy
New code often needs a new table or column. The rule from Databases with SQLAlchemy and Alembic is to apply migrations with alembic upgrade head on every deploy, before the new code takes traffic. Here the first migration creates the reviews table. env.py reads the database URL from the same environment variable as the app, so staging and production migrate their own databases.
# file: alembic.ini
[alembic]
script_location = migrations# file: migrations/env.py
import os
from alembic import context
from sqlalchemy import create_engine
url = os.environ.get("APP_DATABASE_URL", "sqlite:///./reviews.db")
with create_engine(url).connect() as connection:
context.configure(connection=connection)
with context.begin_transaction():
context.run_migrations()# file: migrations/versions/0001_create_reviews.py
"""create reviews"""
import sqlalchemy as sa
from alembic import op
revision = "0001"
down_revision = None
def upgrade() -> None:
op.create_table("reviews", sa.Column("id", sa.Integer, primary_key=True), sa.Column("text", sa.Text, nullable=False))
def downgrade() -> None:
op.drop_table("reviews")The start script ties it together: migrate, then exec the server so that it becomes the main process and receives SIGTERM directly. (This file starts with a comment line because the page tooling uses it as the file name; on your machine you would add #!/usr/bin/env bash on top.) --workers comes from WEB_CONCURRENCY, the variable many platforms set for you, and --no-access-log avoids duplicating the per-request line our middleware already writes.
Migrating inside the start command is the simplest option, and it is fine for one instance. With several instances starting at once they would all try to migrate, so larger systems run
alembic upgrade headas a separate release step (Render's pre-deploy command on paid plans, a Cloud Run job, a CI step) and make each migration backward compatible, so that the old code keeps working while the new one rolls out: add the column first, deploy, and only later remove the old one.
# file: start.sh
set -euo pipefail
alembic upgrade head
exec uvicorn main:app --host 0.0.0.0 --port "${PORT:-8000}" --workers "${WEB_CONCURRENCY:-1}" --no-access-logRun it like a platform would
Export the configuration, start the script in the background with its output in a file, and wait for the health check. The exported SERVER_PID is how we will stop it later; a platform does the same with its own process manager.
export APP_ENV=staging APP_VERSION=1.0.0 APP_API_KEY=dev-key-123 PORT=8000
bash start.sh > server.log 2>&1 &
export SERVER_PID=$!
echo $SERVER_PID > server.pid
curl -s --retry 30 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status":"ok","version":"1.0.0"}The migration ran before the server started (you can check that reviews.db now exists). Now readiness, a write with the API key, a read, and a write without the key:
curl -s http://localhost:8000/ready; echo
curl -s -X POST http://localhost:8000/v1/reviews -H "X-API-Key: $APP_API_KEY" -H "Content-Type: application/json" -d '{"text": "Great course"}'; echo
curl -s http://localhost:8000/v1/reviews/count; echo
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:8000/v1/reviews -H "Content-Type: application/json" -d '{"text": "no key"}'{"status":"ready"}
{"id":1}
{"count":1}
401Every line of the log is JSON, except the lines the server itself prints. The command below keeps the JSON lines, drops the timestamp and rounds the timing so the output is the same every time:
grep '^{' server.log | sed -E 's/"ts": "[^"]+", //; s/"ms": [0-9]+/"ms": N/'{"level": "INFO", "logger": "review-api", "msg": "startup", "env": "staging", "version": "1.0.0", "port": 8000}
{"level": "INFO", "logger": "review-api", "msg": "request", "method": "POST", "path": "/v1/reviews", "status": 201, "ms": N}
{"level": "INFO", "logger": "review-api", "msg": "request", "method": "GET", "path": "/v1/reviews/count", "status": 200, "ms": N}
{"level": "INFO", "logger": "review-api", "msg": "request", "method": "POST", "path": "/v1/reviews", "status": 401, "ms": N}Notice what is missing: the /health and /ready calls are not logged, there is no key or review text anywhere, and the failed write shows up as "status": 401, which is what an alert rule would count.
A post-deploy smoke test
Tests before the deploy prove the code works. A smoke test after the deploy proves this running service works: the right version is answering, the database is reachable, auth is on, validation is on. smoke_test.py waits up to a minute for the service (a sleeping free instance or a rollout in progress needs time), insists on the expected version so that you do not test the old release by accident, and uses only requests that cannot change data: a write without a key must give 401, and a write with a key but an empty body must give 422.
# file: smoke_test.py
"""Post-deploy smoke test: python smoke_test.py BASE_URL [EXPECTED_VERSION]. Reads SMOKE_API_KEY."""
import os
import sys
import time
import httpx
def main(base_url: str, expected_version: str | None) -> int:
key = os.environ["SMOKE_API_KEY"]
with httpx.Client(base_url=base_url, timeout=10) as client:
deadline = time.monotonic() + 60 # a sleeping or still-deploying service needs time
while True:
try:
health = client.get("/health")
if health.status_code == 200 and expected_version in (None, health.json()["version"]):
break
except httpx.TransportError:
pass
if time.monotonic() > deadline:
print("FAIL service did not become healthy with the expected version")
return 1
time.sleep(1)
checks = {
"health is ok": health.json()["status"] == "ok",
"ready (database reachable)": client.get("/ready").status_code == 200,
"no key is rejected": client.post("/v1/reviews", json={"text": "hello"}).status_code == 401,
"bad body is rejected": client.post("/v1/reviews", json={}, headers={"X-API-Key": key}).status_code == 422,
"read path works": client.get("/v1/reviews/count").status_code == 200,
}
for name, ok in checks.items():
print(("PASS " if ok else "FAIL ") + name)
return 0 if all(checks.values()) else 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None))export SMOKE_API_KEY=$APP_API_KEY
python smoke_test.py http://localhost:8000 1.0.0
echo "exit code: $?"PASS health is ok
PASS ready (database reachable)
PASS no key is rejected
PASS bad body is rejected
PASS read path works
exit code: 0The exit code is what automation reads: 0 lets a pipeline continue, anything else fails the job and, in a careful setup, triggers the rollback.
Graceful shutdown
A platform stops your app on every deploy, scale-down and restart. It sends SIGTERM ("please stop"), waits a grace period, and only then sends SIGKILL, which cannot be caught. Docker and Cloud Run wait 10 seconds by default; Render waits longer (30 seconds at the time of writing, check current numbers). A well-behaved server uses the grace period: it stops accepting new connections, lets in-flight requests finish, runs the lifespan shutdown to close pools and flush buffers, and exits with code 0. For an AI service that matters because a request may be a 20-second model call that a deploy must not cut in half.
Watch it happen. Start a 2-second request, send SIGTERM to the exported PID while it is running, wait for the process to finish, then read the relevant log lines:
curl -s "http://localhost:8000/slow?seconds=2" > slow.out &
sleep 0.5
kill -TERM $SERVER_PID
for i in $(seq 100); do grep -q "Finished server process" server.log && break; sleep 0.1; done
wait
cat slow.out; echo
grep -E 'Shutting down|Waiting for (connections|application shutdown)|"/slow"|shutdown complete' server.log | sed -E 's/"ts": "[^"]+", //; s/"ms": [0-9]+/"ms": N/'{"status":"done"}
INFO: Shutting down
INFO: Waiting for connections to close. (CTRL+C to force quit)
{"level": "INFO", "logger": "review-api", "msg": "request", "method": "GET", "path": "/slow", "status": 200, "ms": N}
INFO: Waiting for application shutdown.
{"level": "INFO", "logger": "review-api", "msg": "shutdown complete", "version": "1.0.0"}
INFO: Application shutdown complete.Read the order. The server announces it is shutting down and waits for connections to close. The slow request is not cut: it finishes, the client receives its answer, and its log line appears. Only then does the application shutdown run, and our shutdown complete line proves the finally block executed. A server that was killed instead would have left the client with a broken connection and never printed that line.
If a request can run longer than the platform's grace period, you have two choices: raise the grace period, or move that work to a background job with a status URL (Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning). You can also cap the wait yourself with uvicorn's --timeout-graceful-shutdown (you will try it in the exercises).
Workers and fastapi run
One Python process uses one CPU core for Python code. To use more cores on one machine, run several worker processes. fastapi run main.py --workers 2 (or uvicorn --workers 2, which is what start.sh does through WEB_CONCURRENCY) starts a supervisor that manages the workers; each worker runs its own lifespan, so each opens its own database pool. Rules of thumb: on a small host one or two workers is plenty; on Kubernetes or Cloud Run prefer one process per container and let the platform add containers; and an ML model is loaded once per worker, so memory use is multiplied by the worker count. (Gunicorn's old uvicorn worker class is deprecated; use uvicorn's own --workers.)
Try two workers and count what each one logs. The shutdown is the same: the supervisor receives SIGTERM, passes it on, and every worker runs its own shutdown:
fastapi run main.py --port 8000 --workers 2 > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 30 --retry-connrefused --retry-delay 0 http://localhost:8000/health > /dev/null
for i in $(seq 100); do [ "$(grep -c 'Application startup complete' server.log)" = 2 ] && break; sleep 0.1; done
echo "workers started: $(grep -c 'Started server process' server.log)"
kill -TERM $SERVER_PID
for i in $(seq 100); do grep -q "Stopping parent process" server.log && break; sleep 0.1; done
echo "workers shut down cleanly: $(grep -c '"shutdown complete"' server.log)"workers started: 2
workers shut down cleanly: 2Deploying from GitHub to Render
Render builds and runs your repository on every push. The configuration can live in the repository as a Blueprint file, render.yaml, so that the deployment is reviewed and versioned like code. This one describes a web service and a Postgres database, and wires the database URL into the service without you ever copying a password:
# file: render.yaml
services:
- type: web
name: review-api
runtime: python
plan: free # sleeps after 15 minutes without traffic
buildCommand: pip install -r requirements.txt
startCommand: bash start.sh # runs the migrations, then the server
healthCheckPath: /health
autoDeployTrigger: checksPass # deploy only when the GitHub checks are green
envVars:
- key: PYTHON_VERSION
value: "3.14.0"
- key: APP_ENV
value: production
- key: APP_DATABASE_URL
fromDatabase:
name: review-db
property: connectionString
- key: APP_API_KEY
sync: false # you type the value once in the dashboard; it is not in Git
databases:
- name: review-db
plan: free # expires after 30 days (+14 days grace); paid plans do notThe steps, which you do in the browser:
- Push the repository to GitHub (the local bare-repository flow from GitHub: Remotes, push, pull and clone is exactly what GitHub is from Git's point of view).
- In Render choose New, Blueprint, connect your GitHub account and pick the repository. Render reads
render.yamland shows the service and the database it will create. - Render asks for
APP_API_KEYbecause ofsync: false. Generate a long random value (python -c "import secrets; print(secrets.token_urlsafe(32))") and paste it. It never enters Git. - Apply. Render installs the requirements, runs
start.sh(migrations first), waits for/healthto answer and then switches traffic. You get an HTTPS address ending in.onrender.com. - Run the smoke test from your laptop against that address. After this, every push to
maindeploys again;autoDeployTrigger: checksPasswaits for your GitHub Actions checks to be green first.
Notes that save an evening: Render tells your app which port to use through PORT (10000 by default), so never hard-code 8000; pin the Python version with the PYTHON_VERSION variable; and a pre-deploy command for migrations is a paid-plan feature, which is why this file runs them inside start.sh. The free database is for practice only, because it expires after 30 days (plus a 14-day grace period) and the free web service sleeps after 15 minutes without traffic, so the first visitor waits for it to wake.
Managed Postgres, HTTPS and domains
A managed database means the provider runs the server, patches it and takes backups; you receive a connection URL. Use the internal URL for services in the same region (faster, private) and keep the database off the public internet where you can. HTTPS is automatic on these platforms: the platform terminates TLS and forwards plain HTTP to your app, so your app sees the proxy's address as the client. To get real client IPs for rate limiting, tell uvicorn which proxies to trust with FORWARDED_ALLOW_IPS and do not set it to * unless the platform's proxy is the only way to reach the container. A custom domain is two steps: add the domain in the dashboard, then create the DNS record it shows (a CNAME for a subdomain such as api.yourname.com); the platform issues and renews the certificate.
Deploying an image to Google Cloud Run
Cloud Run runs a container from a registry, scales it to zero when idle and bills by use. You deploy the image from Docker: Packaging Your API, which is why a good Dockerfile makes every container host easy. Two things differ from Render: the platform sets PORT (8080), and nothing on the disk survives, so the database must be external (Cloud SQL, or a hosted Postgres from another provider). These commands need a Google Cloud project with billing enabled, so they are shown, not run here:
docker build -t asia-south1-docker.pkg.dev/my-project/apps/review-api:1.0.0 .
docker push asia-south1-docker.pkg.dev/my-project/apps/review-api:1.0.0gcloud run deploy review-api \
--image asia-south1-docker.pkg.dev/my-project/apps/review-api:1.0.0 \
--region asia-south1 \
--allow-unauthenticated \
--max-instances 3 \
--set-env-vars APP_ENV=production,APP_VERSION=1.0.0 \
--set-secrets APP_API_KEY=review-api-key:latest,APP_DATABASE_URL=review-db-url:latestThe flags carry the lessons of this page: secrets come from Secret Manager, not from the command line; --max-instances caps the bill if traffic or a bug explodes; and the image tag is a version, not latest. Run migrations as a Cloud Run job or a CI step before you shift traffic. Every deploy creates an immutable revision, which makes rollback a traffic switch rather than a rebuild:
gcloud run services update-traffic review-api --region asia-south1 --to-revisions review-api-00001-abc=100Railway, a VPS, and which to pick
Railway is the shortest path: connect the repository, add a Postgres service from the catalogue, set variables (it can reference the database's URL from another service), and every push deploys. Watch the credit: a database and a service together use up a $1 monthly credit quickly. A VPS is a plain Linux machine you rent. The usual shape is Docker (or systemd) running the app on localhost:8000, and a reverse proxy in front for HTTPS. Caddy gets and renews Let's Encrypt certificates by itself:
# file: Caddyfile
api.example.com {
reverse_proxy localhost:8000
}On a VPS the security work is yours: a non-root user with SSH keys only, a firewall that opens just ports 22, 80 and 443, automatic security updates, the database not exposed to the internet, and backups you have actually restored once. Which host should you pick? Learning and demos: Render free or Cloud Run. A small real product: a paid Render or Railway plan, or one VPS. Containers with variable traffic: Cloud Run. The more your app looks like "one container that reads its settings from the environment", the easier it is to move later, and that is the real goal of everything above.
Deploying from GitHub Actions
Instead of the host watching your repository, your pipeline can decide when to deploy. This workflow runs when you push a version tag, deploys to the production environment (where you can require an approval, as in CI/CD with GitHub Actions), asks the host to deploy through a deploy-hook URL stored as a secret, and then smoke-tests the live service. If the smoke test fails, the job fails, and you know within a minute. Pin third-party actions to commit SHAs in real projects, and keep permissions at the minimum, as that page taught.
# file: .github/workflows/deploy.yml
name: Deploy
on:
push:
tags: ["v*"]
permissions:
contents: read
concurrency: deploy-production # never two deploys at once
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # secrets and approvals live on the environment
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.14"
- run: pip install httpx
- name: Ask the host to deploy this tag
run: curl -fsS -X POST "$DEPLOY_HOOK_URL"
env:
DEPLOY_HOOK_URL: ${{ secrets.DEPLOY_HOOK_URL }}
- name: Smoke test the live service
run: python smoke_test.py "$SERVICE_URL"
env:
SERVICE_URL: ${{ vars.SERVICE_URL }}
SMOKE_API_KEY: ${{ secrets.SMOKE_API_KEY }}Rollback: going back when a release is bad
Every release will one day be bad. What matters is how fast you can undo it, so decide the rollback before the deploy. There are three levels. The platform's own rollback (a previous Render deploy, a previous Cloud Run revision) is the fastest. Redeploying an earlier Git tag is the next. And git revert is the safe way to fix main itself: it adds a new commit that undoes a bad one and keeps the history, instead of rewriting shared history (Undoing Mistakes: restore, reset and revert). Database migrations are the hard part: a rollback of code cannot un-drop a column, which is why migrations are written to be backward compatible.
Let us rehearse it for real, with a local bare repository standing in for GitHub. First, ignore what must never be committed and add the small script that stands in for a platform deploy: it stops the old process gracefully, starts the new code and runs the smoke test.
# file: .gitignore
.venv/
__pycache__/
.env
*.db
*.log
*.out
*.pid# file: redeploy.sh
# Local stand-in for a platform deploy: stop the old process gracefully, start the new code, smoke test it.
# usage: bash redeploy.sh EXPECTED_VERSION
set -u
export APP_VERSION="$1"
if [ -f server.pid ] && kill -0 "$(cat server.pid)" 2>/dev/null; then
kill -TERM "$(cat server.pid)"
for i in $(seq 100); do grep -q "Finished server process" server.log && break; sleep 0.1; done
fi
bash start.sh > server.log 2>&1 &
echo $! > server.pid
python smoke_test.py "http://localhost:${PORT:-8000}" "$1"git init -q
git add .
git commit -q -m "Review API 1.0.0"
git tag -a v1.0.0 -m "Release 1.0.0"
git init -q --bare ~/remotes/review-api.git
git remote add origin ~/remotes/review-api.git
git push -q origin main --tagsNow ship a "harmless refactor" that renames a route, tag it, push it and deploy it with the script. The smoke test catches the problem, because the read path no longer exists:
sed -i 's#/v1/reviews/count#/v1/review-count#' main.py
git commit -q -am "Rename the count route"
git tag -a v1.1.0 -m "Release 1.1.0"
git push -q origin main --tags
bash redeploy.sh 1.1.0
echo "exit code: $?"PASS health is ok
PASS ready (database reachable)
PASS no key is rejected
PASS bad body is rejected
FAIL read path works
exit code: 1The deploy is bad and the pipeline knows. Roll back with git revert, tag the result as a new version (never re-use a tag), push, and redeploy. The service is healthy again, and git diff proves that the code is identical to the last good release:
git revert --no-edit HEAD
git tag -a v1.1.1 -m "Release 1.1.1 (rolls back 1.1.0)"
git push -q origin main --tags
bash redeploy.sh 1.1.1
echo "exit code: $?"
git log --oneline --decorate
echo "same code as v1.0.0: $(git diff --quiet v1.0.0 v1.1.1 && echo yes || echo no)"[main 2b92962] Revert "Rename the count route"
Date: Thu Jan 15 10:00:00 2026 +0600
1 file changed, 1 insertion(+), 1 deletion(-)
PASS health is ok
PASS ready (database reachable)
PASS no key is rejected
PASS bad body is rejected
PASS read path works
exit code: 0
2b92962 (HEAD -> main, tag: v1.1.1, origin/main) Revert "Rename the count route"
06c1673 (tag: v1.1.0) Rename the count route
daa943a (tag: v1.0.0) Review API 1.0.0
same code as v1.0.0: yesThe history keeps the whole story (the release, the mistake, the undo), which is what you want in a post-mortem. Alongside the code, keep the data in mind: before a risky migration take a backup, and write the release notes so that anyone on call knows the rollback steps.
After the deploy: monitoring, storage, backups and cost
| Area | What to do |
|---|---|
| Monitoring | Watch the basics per endpoint: request rate, error rate (5xx) and latency percentiles (p95, p99). Add an uptime ping from outside (UptimeRobot, Better Stack and similar tools have free plans) and an error tracker such as Sentry. Alert on symptoms users feel, to a channel somebody reads. |
| AI-specific signals | Model latency, queue depth, tokens and cost per request and per user, provider error rate, and prediction drift. The prompt_version and model_version from earlier pages belong in the logs. |
| Persistent storage | A container's disk vanishes on every deploy. Put records in the database, uploads and model files in object storage (S3, Cloudflare R2, Google Cloud Storage). On a VPS, use a mounted volume and back it up. |
| Backups | Use the provider's automated backups, keep one copy elsewhere (a weekly pg_dump to storage you control matters most on plans that expire), and practise a restore into a scratch database. A backup you never restored is a hope, not a backup. See SQL and Data Handling for AI: Advanced. |
| Cost | Set a budget alert on the cloud account, cap instances (--max-instances), set spending limits at the LLM provider, log cost per request, delete test resources, and review the bill monthly. A loop that calls a paid API can cost more in a night than a server does in a year. |
AI services: extra deployment concerns
| Concern | What to do |
|---|---|
| Model files | Bake a small model into the image (reproducible), or download a versioned file from object storage at start. Never commit large files to Git (Git for AI Projects: Data, Models, LFS, DVC and Leaked Secrets). |
| Memory | The model is loaded once per worker. A 512 MB free instance cannot hold a large model; size the plan from measurements, not guesses. |
| Cold starts | Loading a model takes seconds. Warm up in lifespan, make /ready fail until the model is loaded, and keep a minimum of one instance for latency-sensitive endpoints. |
| Reproducibility | Pin the image tag, the dependency lockfile and the model version. Return model_version in responses so a bad prediction can be traced to a release. |
Deployment security checklist
| Check | Why |
|---|---|
| HTTPS only, HTTP redirected | Tokens and keys travel in headers |
| Secrets in the host's secret store, one set per environment | A staging leak must not reach production |
| Database user with the least privilege; database not public | Limits what SQL injection or a stolen URL can do |
| Non-root container, scanned image, locked dependencies | Smaller attack surface (Docker: Packaging Your API) |
Debug off; /docs protected or disabled if the API is private; exact CORS origins | Do not advertise your internals |
| Deploys only from CI, from tags, with approval for production | Nobody ships from a laptop at 2 a.m. |
Production-readiness review
Before you tell anyone the service is live, walk through this list. Each row names the page of this tutorial that built the piece.
| Question | Yes means |
|---|---|
| Is the behaviour covered by tests that run in CI? | Professional testing, GitHub Actions |
| Does the deploy run migrations, and can the old code run on the new schema? | Alembic, expand-and-contract |
| Do health, readiness, a smoke test and graceful shutdown exist? | This page |
| Are limits set: rate, size, timeout, spend? | Redis rate limits, LLM backend, security |
| Is there a monitoring alert and somebody who will see it? | Uptime ping, error tracker |
| Have you restored a backup and rehearsed a rollback? | Both ran above |
| Can you describe in one paragraph what you do when it breaks at night? | A runbook, even a short one |
Real-world use
A model-serving team ships a new model version every week: the pipeline deploys to staging, smoke-tests, sends a small share of production traffic (a Cloud Run revision at 5 percent), compares error rate and latency, and only then moves everything over. Rollback is a traffic switch. An LLM gateway team adds alerts on cost per hour, because a prompt bug can double the bill before anyone is awake. A solo developer does the small version of the same loop: Blueprint file, health check, smoke test, one tag per release.
Common mistakes
- Hard-coding the port or binding to
127.0.0.1. The platform cannot reach the app and reports a timeout or "no open ports". Bind to0.0.0.0and use$PORTwhen it is set. - Secrets in Git, in the image or in logs. Anything that was committed is public to everyone with access, forever. Put values in the host's secret store, make the secret setting required, and rotate any key that leaked.
- A health check that is too shallow or too deep. A
/healththat always says "ok" hides a broken database; a liveness check that calls the database makes the platform restart a healthy app during a database blip. Keep liveness cheap and use readiness for dependencies. - Treating the container disk or SQLite as storage. The next deploy erases it. Use a managed database and object storage; keep SQLite for local runs and tests.
- No rollback plan, and breaking migrations. A release that drops a column cannot be rolled back with code. Make migrations backward compatible, back up first, and rehearse the rollback before you need it.
Try it yourself
- Easy. Create a
.env.examplelisting every setting the app reads (APP_ENV,APP_VERSION,APP_DATABASE_URL,APP_API_KEY,APP_LOG_LEVELandPORT), with empty values for the secrets. - Medium. Prove that
/readyreturns 503 when the database cannot be reached: start a second instance on port 8001 with a database path that does not exist, and show the status code and body. - Hard. Make shutdown bounded. Start an instance on port 8001 that gives in-flight requests at most 3 seconds after
SIGTERM, send it a 10-second/slowrequest, stop it, and show that the request was cut off but thelifespanshutdown still ran.
Answers
Easy. The file is documentation and a template: it is committed, the real .env is not.
# file: .env.example
APP_ENV=local
APP_VERSION=dev
APP_DATABASE_URL=sqlite:///./reviews.db
APP_API_KEY=
APP_LOG_LEVEL=INFO
PORT=8000Medium. Start with uvicorn directly, not start.sh, because the migration would fail on the missing path. The engine connects lazily, so the process starts and only /ready notices. This is exactly what a load balancer would see:
APP_DATABASE_URL=sqlite:////nonexistent/reviews.db uvicorn main:app --port 8001 --no-access-log > second.log 2>&1 &
export SECOND_PID=$!
curl -s --retry 30 --retry-connrefused --retry-delay 0 http://localhost:8001/health > /dev/null
curl -s -w "\n%{http_code}\n" http://localhost:8001/ready
kill -TERM $SECOND_PID
for i in $(seq 100); do grep -q "Finished server process" second.log && break; sleep 0.1; done{"status":"unavailable","reason":"OperationalError"}
503Hard. --timeout-graceful-shutdown 3 tells uvicorn to wait three seconds for open requests and then cancel them. wait returns when both background jobs, the server and the client, are done:
uvicorn main:app --port 8001 --no-access-log --timeout-graceful-shutdown 3 > second.log 2>&1 &
export SECOND_PID=$!
curl -s --retry 30 --retry-connrefused --retry-delay 0 http://localhost:8001/health > /dev/null
curl -s "http://localhost:8001/slow?seconds=10" > slow.out &
sleep 0.5
kill -TERM $SECOND_PID
wait
[ -s slow.out ] && echo "response received" || echo "request was cut off"
grep -E 'Cancel|shutdown complete' second.log | sed -E 's/"ts": "[^"]+", //'request was cut off
ERROR: Cancel 1 running task(s), timeout graceful shutdown exceeded
{"level": "INFO", "logger": "review-api", "msg": "shutdown complete", "version": "1.0.0"}
INFO: Application shutdown complete.The platform's grace period and this flag should agree: if the platform kills at 10 seconds, set the flag a little lower so that your own shutdown code gets to run. Finally, stop the instance that the rollback section left running:
kill -TERM $(cat server.pid)
for i in $(seq 100); do grep -q "Finished server process" server.log && break; sleep 0.1; doneSummary
- Environments are the same code with different configuration. Read settings and secrets from the environment, make the secret required, and take the port from
PORT. - Give the app JSON logs on standard output, a cheap
/health, a dependency-checking/ready, and migrations that run before the server takes traffic. - On
SIGTERMa good server finishes in-flight requests and runs itslifespanshutdown; check the platform's grace period against your slowest request. - Smoke-test every deploy from outside, check the version, and let the exit code decide. Deploy from CI on tags, and roll back with the platform, an earlier tag or
git revert. - Free hosting in 2026 is small (Render sleeps and its free database expires, Railway is credits, Fly.io has no free tier, Koyeb closed its free plan, Docker Spaces need PRO), so check current limits, plan for a small bill, and set budgets and caps, especially for LLM calls.
Next: Practice and Interview Lab turns everything so far into graded challenges: Git rescues, HTTP and API puzzles, FastAPI fixes, security checks and system-design questions, each with a hint and a solution you can run.

