2022-06-06 10:00:00+00:00

In distributed microservice platforms, different services often share or partition access to the same relational database. When you release updates that change database schemas, executing these migrations manually leads to deployment bottlenecks. Enforcing migrations automatically inside your Continuous Integration and Continuous Deployment (CI/CD) pipeline ensures schemas are kept in sync safely before code changes are routed production traffic.

By integrating Alembic with GitLab runner pipelines, we can automate database migrations on code pushes.


1. Running Alembic in the CD Pipeline

We configure our CD build step to apply database changes automatically when changes are pushed to main:

# migration-ci-job.yml
deploy_schema_migrations:
  stage: deploy
  image: python:3.9-slim
  script:
    - pip install alembic psycopg2-binary
    # Run database migration upgrade to head
    - alembic upgrade head
  only:
    - main
  variables:
    # Database connection URL loaded securely from vault
    DATABASE_URL: "postgresql://db_user:secret@db-prod-host:5432/main_db"

2. Enforcing Transactional Migrations

Alembic migrations are wrapped inside transactions: if a step fails midway due to a connection error, all changes are automatically rolled back, protecting database consistency.

Zero-Downtime Expand-and-Contract Alembic Migrations

In multi-replica Kubernetes or Cloud Run deployments, old application containers continue running briefly while new containers start up. Always split destructive schema changes into two separate releases (Expand first, Contract after rollout) and set lock_timeout = '3s' in Alembic's env.py.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs