What the Architecture Covers
Quality gates
Linting, type checks and automated tests with coverage on every push and pull request.
Reproducible builds
Docker images built once, tagged by commit and promoted unchanged from staging to production.
Staging first
Automatic deploy to staging followed by smoke tests against the real stack.
Safe production releases
Health-checked rollouts with an approval step and one-click rollback to the previous image.
Migrations in the pipeline
Database migrations run as a controlled pipeline step, never by hand.
Secrets handled properly
Credentials injected from a secrets manager at deploy time, never stored in the repository.
How the pieces fit
The whole pipeline is one GitHub Actions workflow with four jobs. Pull requests run only the first job; merges to main run all four. This version deploys to ECS, matching the AWS deployment architecture, but the shape works for any container platform.
- 1Test every change. On every pull request and every push to main, Ruff checks lint and formatting, mypy checks types, Alembic applies every migration to a fresh PostgreSQL service container, and pytest runs with coverage against that same database.
- 2Block bad merges. Branch protection makes the test job a required status check, so a red build cannot reach main.
- 3Build once. On main, one Docker image is built, tagged with the commit SHA and pushed to Amazon ECR, where tag immutability stops anyone overwriting it.
- 4Deploy to staging. A deploy script registers a new ECS task definition revision with that tag, runs migrations as a one-off task, updates the service and waits until it is stable.
- 5Smoke test the real stack. Health checks and a few critical requests run against staging through the real load balancer, database and cache.
- 6Wait for approval. The production job targets a GitHub environment with required reviewers, so it pauses until someone approves.
- 7Promote the same image. Production gets the exact image staging tested, through a health-checked rolling update.
The workflow
name: ci-cd
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
env:
AWS_REGION: us-east-1
REGISTRY: 123456789012.dkr.ecr.us-east-1.amazonaws.com
IMAGE: api
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app_test
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
DATABASE_URL: postgresql+psycopg://app:app@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- run: pip install -r requirements.txt -r requirements-dev.txt
- run: ruff check .
- run: ruff format --check .
- run: mypy app
- run: alembic upgrade head
- run: pytest --cov=app --cov-report=term-missing
build:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-build
aws-region: us-east-1
- uses: aws-actions/amazon-ecr-login@v2
- run: docker build -t "$REGISTRY/$IMAGE:$GITHUB_SHA" .
- run: docker push "$REGISTRY/$IMAGE:$GITHUB_SHA"
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
permissions:
contents: read
id-token: write
env:
SMOKE_BASE_URL: https://staging-api.example.com
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-deploy-staging
aws-region: us-east-1
- run: ./deploy/ecs-deploy.sh staging "$GITHUB_SHA"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install httpx pytest
- run: pytest tests/smoke
deploy-production:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
concurrency:
group: production-deploy
cancel-in-progress: false
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-deploy-production
aws-region: us-east-1
- run: ./deploy/ecs-deploy.sh production "$GITHUB_SHA"
- run: curl --fail --retry 5 --retry-delay 10 https://api.example.com/health/readyA few details carry most of the weight. The if condition on the build job keeps pull requests from building or deploying anything, and jobs that depend on a skipped job are skipped too. No long-lived AWS keys are stored in GitHub: each job that touches AWS requests an OpenID Connect token, which is why it needs id-token: write, and exchanges it for short-lived credentials from an IAM role. The concurrency group means two production releases never run over each other.
The deploy script is plain AWS CLI: describe-task-definition, swap the image tag, register-task-definition, run-task for alembic upgrade head with the new image, check that the task exited cleanly, then update-service and aws ecs wait services-stable. If the migration task fails, the script stops before the service changes, so the old version keeps serving.
Scoping deploy roles per environment
Each deploy role trusts only tokens from one GitHub environment of one repository:
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:example-org/api:environment:production"
}
}
}Combined with a deployment branch rule that limits the production environment to main, a job from another branch cannot assume the role. Its permissions cover only what the deploy script calls: describing and registering task definitions, running and describing the migration task, updating one ECS service, and iam:PassRole for that service's execution and task roles. The staging role is a separate role with the same shape, so staging credentials can never touch production. Required reviewers on environments depend on your GitHub plan for private repositories, so check that before relying on them.
Smoke tests
Smoke tests are short, read-only and aimed at the deployed URL, not at the code:
import os
import httpx
BASE_URL = os.environ["SMOKE_BASE_URL"]
def test_dependencies_ready():
response = httpx.get(f"{BASE_URL}/health/ready", timeout=10)
assert response.status_code == 200
assert response.json() == {"postgres": "ok", "redis": "ok"}
def test_api_schema_served():
response = httpx.get(f"{BASE_URL}/openapi.json", timeout=10)
assert response.status_code == 200
assert response.json()["paths"]If either test fails, the production job never starts. I add one test per critical flow as the product grows, using a dedicated test tenant.
Rollback and migrations
Every image stays in ECR under its commit SHA, so rolling back never means rebuilding old code. If new tasks fail their health checks, the ECS deployment circuit breaker returns the service to the last working revision on its own. For problems found later, I open the last good workflow run and re-run its production job. Re-runs use the original commit SHA, so the old image goes out through the same script, approval and checks. GitHub only allows re-runs for a limited time, so the deploy script also accepts any earlier image tag directly.
Database migrations are not rolled back automatically. Because migrations run before the new code takes traffic, each one must also work with the version still running: add columns and tables first, remove them in a later release. The PostgreSQL design blueprint shows that pattern for a NOT NULL column. A downgrade is a deliberate, reviewed step.
Failure modes and how the design handles them
- A flaky test. It is fixed or quarantined with an issue, not re-run until green, because a pipeline people distrust gets bypassed.
- A migration fails. It already ran on a fresh database in CI and on staging data. In production the script stops before updating the service.
- A broken build reaches staging. Smoke tests fail and production is never touched.
- A bad release reaches production. Failed health checks trigger the circuit breaker, or the last good run is re-run.
- Two releases collide. The concurrency group serializes production deploys.
- Credentials leak. There are no static AWS keys to leak, and OIDC credentials expire on their own.
- A third-party action is compromised. The workflow's default permissions are read-only, and stricter setups pin actions to a full commit SHA.
Checklist
- Ruff, mypy and pytest run on every pull request, and the test job is a required status check.
- Tests use a real PostgreSQL service container, and migrations run from scratch in CI.
- Images are built once, tagged by commit SHA and stored with tag immutability on.
- Staging deploys automatically from main and is smoke tested before production.
- Production uses a GitHub environment with an approval step and a branch rule limited to main.
- AWS access uses OIDC roles scoped per environment, with no static keys in GitHub.
- Migrations run as a pipeline step and stay compatible with the running version.
- The ECS deployment circuit breaker is on, with rollback enabled.
- The rollback path has been practiced, not just written down.
Tools & Stack
- GitHub Actions
- pytest
- Ruff
- mypy
- Docker
- Container registry
- AWS
In Practice
This blueprint is part of my Python backend & API development service. Tell me about your system on Upwork and I'll propose the right setup, timeline and cost.
Hire Me on Upwork


