Skip to content

Deployment

🐳 Compose Architecture

The base docker-compose.yaml is production-shaped: no source mounts, no published database port, no admin UIs, and no Traefik dashboard.

Service Image Role
traefik traefik:v3.6 Reverse proxy (JSON access logs, backend health checks on /health/ready).
db postgres:18 Primary database (internal network only).
prestart app image One-off job: alembic upgrade head + seed SUPER user, then exits.
backend app image Uvicorn, non-root (uid 10001), CPU/memory limits, health check.

docker-compose.override.yml (loaded automatically by docker compose up) adds the development pieces: hot reload, DB port 5432, pgAdmin, Mailpit and the Traefik dashboard.

# Production-style
docker compose -f docker-compose.yaml up -d --build

# Local development
docker compose up -d --build

✅ Production Checklist

Setting Why
ENVIRONMENT=production Enables strict checks: the app refuses to start with changethis secrets or a SECRET_KEY shorter than 32 characters, and adds HSTS.
SECRET_KEY openssl rand -hex 32. Rotating it signs every user out.
ALLOWED_HOSTS Enables TrustedHostMiddleware, e.g. api.example.com.
BACKEND_CORS_ORIGINS, FRONTEND_HOST The real frontend origin(s).
RATE_LIMIT_STORAGE_URI=redis://… Shares rate limits across workers and replicas (memory is per process).
FORWARDED_ALLOW_IPS Proxy addresses Uvicorn trusts for X-Forwarded-For. The Compose stack sets * because only Traefik can reach the API.
WEB_CONCURRENCY Uvicorn worker count (default 2).
SENTRY_DSN, OTEL_EXPORTER_OTLP_ENDPOINT Error tracking and tracing.
POSTGRES_SSLMODE=verify-full For managed databases.
Update the Traefik Host() rule traefik/dynamic.yml uses the .test domain.

TLS

Terminate TLS at Traefik (or your cloud load balancer). With Traefik, add an HTTPS entrypoint and an ACME resolver to the traefik command, for example:

- "--entrypoints.websecure.address=:443"
- "--entrypoints.web.http.redirections.entrypoint.to=websecure"
- "--certificatesresolvers.le.acme.tlschallenge=true"
- "--certificatesresolvers.le.acme.email=ops@example.com"
- "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json"

Then add tls: {certResolver: le} and entryPoints: [websecure] to the router in traefik/dynamic.yml, publish port 443, and mount a volume for /letsencrypt.

🏗️ Image

The multi-stage Dockerfile:

  • installs locked dependencies with a pinned uv (no dev tools in the runtime image)
  • runs as an unprivileged app user
  • defines a HEALTHCHECK on /health/live and OCI labels
  • starts Uvicorn with --proxy-headers and no Server header.

Migrations are not run on container start. Run the prestart job once per release (Compose does this automatically; on Kubernetes use a Job or Helm hook), so scaling to N replicas never races on schema changes.

docker build -t fastapi-backend:local .

🚀 Releases (GHCR)

Pushing a tag vX.Y.Z triggers .github/workflows/release.yml. It:

  1. builds the image with BuildKit cache
  2. pushes it to ghcr.io/<owner>/<repo> tagged X.Y.Z, X.Y and the commit SHA
  3. attaches an SBOM and max-mode provenance, plus a GitHub build attestation
  4. signs the image with cosign (keyless, via GitHub OIDC).

Verify a published image:

cosign verify ghcr.io/<owner>/<repo>:0.3.0 \
  --certificate-identity-regexp 'https://github.com/<owner>/<repo>/' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
gh attestation verify oci://ghcr.io/<owner>/<repo>:0.3.0 --owner <owner>

Deploying the image (ECS, Kubernetes, Fly.io, a VM with Compose, and so on) is environment-specific. Run the image's /app/scripts/prestart.sh as a one-off job first, then roll out the API.

☁️ AWS Free Tier (Lambda + CloudFront + Neon)

A public demo deployment that costs $0 at demo traffic, even on an AWS account older than 12 months. It uses only Always Free services. AWS has no always-free PostgreSQL, so the database stays on Neon's free plan, which also runs on AWS. The reasoning is in ADR 0005.

flowchart LR
    B[Browser] --> CF[CloudFront]
    CF -- "default" --> S3[(S3: React SPA)]
    CF -- "/api/*, /health*, /docs<br/>+ X-Origin-Verify" --> API[Lambda api<br/>Web Adapter + Uvicorn]
    API --> DB[(Neon Postgres)]
    API -- queue_email --> Q[SQS emails + DLQ]
    Q --> W[Lambda worker]
    EB[EventBridge Scheduler<br/>daily] -- "job: purge" --> W
    W --> DB
    W --> SMTP[SMTP: SES or Gmail]
Piece Free allowance (per month)
Lambda (both functions) 1M requests, 400,000 GB-seconds
CloudFront 1 TB transfer, 10M requests (or the $0 flat-rate Free plan)
SQS 1M requests. The idle queue poller uses about 650,000 of them.
EventBridge Scheduler, CloudWatch Logs Free tier (logs are kept log_retention_days, 14 by default)
S3 A few MB for the SPA build (a cent at most; covered by the CloudFront Free plan's S3 credit)
Neon Free plan

There is no VPC, NAT gateway, load balancer, RDS or ElastiCache, and nothing else that bills by the hour.

What runs where

  • api runs app.main:app, and worker runs app.aws.worker:app. Both come from the same zip (scripts/build-lambda-zip.sh, Python 3.12, arm64), behind the AWS Lambda Web Adapter layer.
  • One domain. CloudFront sends /api/*, /health*, /docs, /redoc and /openapi.json to the API and everything else to the SPA, so Swagger UI is at <public_url>/docs.
  • Only CloudFront can call the API. CloudFront adds a secret X-Origin-Verify header, and CloudFrontOriginMiddleware rejects requests without it with 403. It also takes the client IP from CloudFront-Viewer-Address, so rate limits and the audit trail see the real viewer.
  • No post-response work is lost. Lambda freezes as soon as a response is complete, so DEFER_RESPONSE_UNTIL_COMPLETE=true holds the response until the audit row is written.
  • Emails go through SQS. The worker sends them. Failed messages are retried 5 times, then kept in the dead-letter queue for 14 days.
  • Migrations run in CI. .github/workflows/deploy-aws.yml runs scripts/prestart.sh against Neon before it updates the functions. Schema changes must stay compatible with the running version (ADR 0003).

First-time setup

Terraform creates the AWS resources once; after that, pushing a version tag makes GitHub Actions deploy your code into them.

Before you start, you need:

  • an AWS account and a Neon account;
  • the backend and frontend repositories on GitHub, with the code you want to deploy merged into master;
  • a local clone of both.

Step 2 has install commands for macOS, Windows and Linux.

1. Prepare the AWS account

  1. Don't use the root user for daily work. In IAM → Users, create a user with console access and attach the AdministratorAccess and SignInLocalDevelopmentAccess policies. Turn on MFA, then sign in as that user. Access this broad suits a personal learning account; limit it in a shared one.
  2. Set a cost alert: Billing and Cost Management → Budgets → Create budget, with your minimum budget: the smallest amount you want to be alerted about. The Zero spend budget template alerts as soon as you are charged. An existing budget is fine if it has an active alert and a current email address. If the IAM user cannot open Billing, sign in as the root user for this step, or enable IAM user and role access to Billing information in the account settings. A budget sends alerts; it does not stop spending.
  3. If this account may have been used for an earlier deployment, select the region, open Lambda and look for fastapi-template-api (<name>-api if you changed name). If it exists and you don't have the matching terraform.tfstate, stop: Terraform does not know about those resources. Find the state file, or remove the old resources, before you continue.

2. Install the tools

You need the AWS CLI 2.32.0 or newer (for aws login) and Terraform 1.10 or newer. Both are installed on your computer, not in the project, so don't add them with uv. Follow the tab for your system.

AWS CLI, with the official AWS installer:

curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

If you prefer Homebrew, run brew install awscli instead.

Terraform, with HashiCorp's Homebrew tap:

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Without Homebrew, download the macOS ARM64 zip from the Terraform install page, unzip it and move terraform to a folder in your PATH.

AWS CLI, with the official AWS installer:

curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

Avoid brew install awscli on Intel. Homebrew no longer supports Intel Macs and expects to stop running on them in or after September 2027. Its awscli formula lists no prebuilt Intel package, so Homebrew may have to build it from source.

Terraform, with HashiCorp's Homebrew tap:

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Without Homebrew, or if it fails, download the macOS AMD64 zip from the Terraform install page, unzip it and move terraform to a folder in your PATH.

You need a Microsoft-supported version of 64-bit Windows.

AWS CLI, with the official MSI installer. This installs it for all users and needs admin rights:

msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

Without admin rights, install it for your user only with https://awscli.amazonaws.com/AWSCLIV2-User.msi.

Terraform:

  1. From the Terraform install page, download the Windows zip for your processor: AMD64 for most PCs, ARM64 for ARM devices.
  2. Unzip it into a permanent folder, such as C:\terraform.
  3. Add that folder to your Path environment variable.

Open a new PowerShell window afterwards, so that both commands are found. The PowerShell commands in the later steps assume this setup.

These steps also apply to Windows Subsystem for Linux (WSL).

AWS CLI, with the official installer. It needs curl and unzip. For x86_64:

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

For ARM (uname -m shows aarch64):

curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

Terraform, from HashiCorp's package repository. Run the commands for your distribution.

Ubuntu or Debian:

sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt-get update && sudo apt-get install -y terraform

RHEL or CentOS:

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

Fedora:

sudo dnf install -y dnf-plugins-core
sudo dnf config-manager addrepo --from-repofile=https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
sudo dnf -y install terraform

Amazon Linux 2023:

sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo dnf -y install terraform

Amazon Linux 2:

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install terraform

On other distributions, use the Linux zip from the Terraform install page.

Other systems: HashiCorp also offers Terraform binaries for FreeBSD, OpenBSD and Solaris. AWS documents AWS CLI installers only for macOS, Windows and Linux, so on other systems, use a Linux machine or virtual machine for this setup.

Check both versions:

aws --version
terraform version

Use one install method per tool, so that you don't end up with two copies. Update each tool the same way you installed it. For other options and update steps, see the AWS CLI and Terraform install pages.

3. Sign in from the terminal

aws login                      # opens the browser; choose your region, e.g. us-east-1
aws sts get-caller-identity    # should show your IAM user

If the machine has no browser (for example a remote server, or possibly WSL), use aws login --remote. Open the URL it prints on another device, then paste the authorization code back into the terminal.

If Terraform reports that it cannot find credentials, export them in the same terminal and run Terraform again. These credentials are temporary, so repeat this when they expire.

eval "$(aws configure export-credentials --format env)"
aws configure export-credentials --format powershell

This prints $Env: lines. Paste them into the same window and press Enter. They contain secrets, so don't share them.

4. Create the database in Neon

  1. Create a project (or reuse an existing one) in an AWS region close to your app, ideally the same as the Terraform region (us-east-1 by default). Choose PostgreSQL 18, which local development and CI use.
  2. Click Connect and turn Connection pooling off to get the direct connection details.
  3. Note the host, database, user and password. The host must not contain -pooler: migrations need a direct connection.

5. Fill in the Terraform settings

Run Terraform from an up-to-date master, so that the infrastructure matches the code you deploy.

git status                     # should be clean
git switch master
git pull --ff-only
cd infra/aws
cp -n terraform.tfvars.example terraform.tfvars   # keeps an existing file
openssl rand -hex 32           # use the output as secret_key
git status                     # should be clean
git switch master
git pull --ff-only
cd infra/aws
# Copies only if the file doesn't exist yet
if (-not (Test-Path terraform.tfvars)) { Copy-Item terraform.tfvars.example terraform.tfvars }
# Use the output as secret_key
$bytes = New-Object byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
-join ($bytes | ForEach-Object { $_.ToString("x2") })

Set these values in terraform.tfvars:

Setting Value
region The AWS region, e.g. us-east-1
public_url "" for now
secret_key The generated value (at least 32 characters)
super_user_email The email of the app's first admin
super_user_password A new, strong password
postgres_server The Neon host only, not the whole connection string
postgres_db, postgres_user, postgres_password From Neon

Using your own repositories

The GitHub deploy roles only trust the repositories named in these settings. If you forked or copied the template, also set github_owner, backend_repo and frontend_repo. Their defaults are in infra/aws/variables.tf.

Email is optional and can be added later (see Email). Without it the app works, but sends no password-reset emails. terraform.tfvars is gitignored: never commit or share it.

6. Create the AWS resources

An AWS account can have only one GitHub OIDC provider. Check whether yours already has it:

aws iam list-open-id-connect-providers

If the list includes token.actions.githubusercontent.com and this Terraform state did not create it, add create_github_oidc_provider = false to terraform.tfvars. Then, from infra/aws:

terraform init     # downloads the providers
terraform plan     # preview; creates nothing
terraform apply    # review the plan, then type: yes

On a first deployment the plan should only add resources, with 0 to change and 0 to destroy. If it shows anything else, stop and find out why. Creating the CloudFront distribution can take several minutes.

7. Set the public URL

The first apply cannot know the CloudFront URL, and FRONTEND_HOST and email links need it. terraform apply prints it as public_url under Outputs when it finishes. To show it again, for example after you fixed a failed apply, run this from infra/aws:

terraform output public_url

Copy the URL into terraform.tfvars, without a trailing slash:

public_url = "https://dxxxxxxxx.cloudfront.net"
terraform apply
terraform output    # keep these values for steps 8 and 9

The app does not work yet: Terraform creates the functions with placeholder code.

Keep the Terraform state

infra/aws/terraform.tfstate is how Terraform tracks your resources, and it contains secrets. Don't delete or commit it. Back it up somewhere private, and update the backup after later applies.

8. Configure the backend repository

In the backend repository on GitHub, go to Settings → Environments → New environment and name it exactly production. If you restrict which branches and tags can use it, allow v*.*.* tags.

Kind Name Value
Variable PUBLIC_URL public_url output
Variable AWS_REGION Terraform region
Variable AWS_DEPLOY_ROLE_ARN deploy_role_backend_arn output
Variable AWS_API_FUNCTION, AWS_WORKER_FUNCTION api_function_name, worker_function_name outputs
Variable POSTGRES_SERVER, POSTGRES_DB, POSTGRES_USER Neon direct endpoint
Variable SUPER_USER_EMAIL (optional: SUPER_USER_NAME, PROJECT_NAME, STACK_NAME) Same values as in terraform.tfvars
Secret SECRET_KEY, SUPER_USER_PASSWORD, POSTGRES_PASSWORD Same values as in terraform.tfvars

GitHub needs no AWS access keys: the workflow gets temporary credentials through OIDC.

9. Configure the frontend repository

Create a production environment in the frontend repository too, with these variables:

Name Value
PUBLIC_URL public_url output (also the app's API URL)
AWS_REGION Terraform region
AWS_DEPLOY_ROLE_ARN deploy_role_frontend_arn output (not the backend role)
AWS_FRONTEND_BUCKET frontend_bucket output
AWS_CLOUDFRONT_DISTRIBUTION_ID cloudfront_distribution_id output

10. Deploy the backend

Pushing a v*.*.* tag starts a real deployment. Deploy the backend first. Replace vX.Y.Z with the next unused version:

git fetch origin --tags
git tag -a vX.Y.Z origin/master -m "Release vX.Y.Z"
git push origin vX.Y.Z

The tag does not change the version number or release notes in the code. It also starts the GHCR release workflow.

Open Actions → Deploy to AWS. The job migrates and seeds Neon (creating the first admin), uploads the zip to both functions, then checks GET <public_url>/health/ready. Wait for it to pass.

You can also run Deploy to AWS manually, but you must select a version tag, not a branch. The backend deploys only from a version tag on a commit in master.

11. Deploy the frontend

In your frontend clone, create and push a tag the same way (the two repositories are versioned separately), then wait for its Deploy to AWS workflow to pass.

12. Check the app

  • <public_url>/health/ready succeeds.
  • <public_url>/docs shows the API docs, which are public.
  • <public_url> shows the app, and you can log in with the admin email and password.

The first request can be slow while Lambda and Neon wake up.

Troubleshooting

Problem What to check
No valid credential sources Sign in again or export the credentials (step 3).
The OIDC provider already exists Set create_github_oidc_provider = false (step 6).
The statement id (...) provided already exists (Lambda permission) Your code declares a permission that the AWS provider already adds. Update to the latest code, which leaves these permissions to the provider, then run terraform init and terraform plan again. You don't need to import anything.
CloudFront says the account must be verified Contact AWS Support.
Not authorized to perform sts:AssumeRoleWithWebIdentity The role ARN, github_owner and repository names, and that the environment is named production.
The migration step fails The Neon values, a host without -pooler, and the GitHub secrets.
The health check fails CloudWatch → Log groups → /aws/lambda/<name>-api (<name> defaults to fastapi-template).

After fixing GitHub settings, use Re-run failed jobs. If you change terraform.tfvars, run terraform apply again. If the fix needs a code change, merge it into master and push a new tag.

Remove the deployment

From infra/aws, run terraform destroy and review the list before you confirm. It does not delete the Neon project; delete that in Neon if you no longer need its data.

Email (optional)

Leave smtp_host empty to disable email. The app still works, but password-reset emails are skipped. To send email:

  • Amazon SES: costs $0.10 per 1,000 emails. New SES accounts are in the sandbox: verify the sender and every recipient address, which is fine for a demo. Create SMTP credentials and use smtp_host = "email-smtp.<region>.amazonaws.com", port 587.
  • Gmail: free. Use smtp.gmail.com, port 587, and an app password.

Limits to know before a demo

  • Cold starts: the first request after a quiet period starts a new Lambda instance, and Neon's free compute also resumes from suspend. Open the app a minute before you present it.
  • Rate limits: limits like 5/minute on login are counted per Lambda instance (memory://), not globally.
  • Package size: the zip must stay under 50 MB for a direct upload. The build script checks this.
  • Secrets: they live in the Lambda environment and in Terraform's local terraform.tfstate (gitignored). Keep that file private.

Manual catch-up and rollback

With the production POSTGRES_* (direct endpoint) and the other required settings exported:

uv run alembic current          # what the database is on
uv run alembic upgrade head     # apply pending migrations
uv run alembic downgrade -1     # roll back one revision

To roll back the code, run Deploy to AWS on the previous tag. The workflow runs as it exists in that tag.

🔄 CI Workflows

Workflow Purpose
test-fastapi-backend-template.yml Prek hooks (Ruff, Mypy, Bandit, uv lock, docs build); tests on Python 3.12 and 3.13
test-coverage.yml Coverage (≥ 90%, branch-aware) and badge
docker-compose-test.yml Tests inside the image; production stack smoke test (non-root, Traefik routing, login); Schemathesis fuzzing for 5xx errors
contract-integrity.yml Committed openapi.json matches the code
security.yml pip-audit, TruffleHog, CodeQL, Trivy (also weekly)
release.yml Signed image with SBOM and provenance on tags
docs.yml Builds and publishes this site
deploy-aws.yml Migrates Neon and deploys both Lambda functions (version tags on master, pushed or run manually; see AWS Free Tier)
infra.yml terraform fmt/validate and a Trivy misconfiguration scan for infra/aws

Dependabot (.github/dependabot.yml) keeps Python, Actions and Docker dependencies current.

💾 Data

The database lives in the postgres_data volume. See Operations for backups, retention and key rotation.