Bird
Raised Fist0
FastAPIframework~8 mins

Alembic migrations in FastAPI - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: Alembic migrations
MEDIUM IMPACT
Alembic migrations affect backend database schema changes and can indirectly impact frontend load times if migrations block API responses.
Applying database schema changes during API startup
FastAPI
from alembic import command
from alembic.config import Config

alembic_cfg = Config("alembic.ini")

# Run migrations separately before starting the app
# or run migrations asynchronously in a background task

import asyncio

async def run_migrations_async():
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(None, lambda: command.upgrade(alembic_cfg, "head"))

# Call run_migrations_async() before serving requests
Running migrations asynchronously or before app startup avoids blocking API responses, improving user experience.
📈 Performance Gainnon-blocking startup, faster API readiness, better LCP and INP
Applying database schema changes during API startup
FastAPI
from alembic import command
from alembic.config import Config

alembic_cfg = Config("alembic.ini")
command.upgrade(alembic_cfg, "head")  # runs migrations synchronously on app start
Running migrations synchronously during app startup blocks the server from handling requests, increasing API response time and delaying page load.
📉 Performance Costblocks API startup for several seconds, delaying LCP and increasing INP
Performance Comparison
PatternBackend BlockingAPI Response DelayUser ImpactVerdict
Synchronous migrations during app startHighHighDelays page load and interaction[X] Bad
Asynchronous or pre-run migrationsNone during requestsMinimalSmooth user experience[OK] Good
Rendering Pipeline
Alembic migrations run on the backend and do not directly affect browser rendering but can delay API responses that provide data for rendering.
Backend Processing
API Response Time
⚠️ BottleneckBackend blocking during migration execution
Optimization Tips
1Never run Alembic migrations synchronously during API request handling.
2Run migrations before app startup or asynchronously in background tasks.
3Monitor API response times to detect backend blocking from migrations.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of running Alembic migrations synchronously during FastAPI app startup?
AIt causes CSS layout shifts in the browser.
BIt increases the frontend bundle size.
CIt blocks the server from handling requests, increasing API response time.
DIt improves database query speed.
DevTools: Network
How to check: Open DevTools Network tab, reload the page, and check API request timings for delays caused by backend processing.
What to look for: Look for long waiting (TTFB) times indicating backend blocking possibly due to migrations.

Practice

(1/5)
1. What is the main purpose of Alembic migrations in a FastAPI project?
easy
A. To manage and apply database schema changes safely over time
B. To handle HTTP requests and responses
C. To serve static files like images and CSS
D. To create user interface components

Solution

  1. Step 1: Understand Alembic's role

    Alembic is a tool designed to manage database schema changes, not web server tasks.
  2. Step 2: Identify the correct purpose

    It helps developers apply, track, and revert database changes safely during development and deployment.
  3. Final Answer:

    To manage and apply database schema changes safely over time -> Option A
  4. Quick Check:

    Alembic = database migrations [OK]
Hint: Alembic is for database schema changes, not web or UI tasks [OK]
Common Mistakes:
  • Confusing Alembic with FastAPI routing
  • Thinking Alembic serves static files
  • Assuming Alembic builds UI components
2. Which Alembic command creates a new migration script file?
easy
A. alembic upgrade head
B. alembic init migrations
C. alembic downgrade -1
D. alembic revision -m "message"

Solution

  1. Step 1: Identify commands for migration scripts

    The command to create a new migration script is revision with a message describing the change.
  2. Step 2: Match the command

    alembic revision -m "message" creates a new migration file with the given message.
  3. Final Answer:

    alembic revision -m "message" -> Option D
  4. Quick Check:

    revision = create migration script [OK]
Hint: Use 'revision' with -m to create migration scripts [OK]
Common Mistakes:
  • Using 'upgrade' to create scripts instead of apply them
  • Confusing 'downgrade' with script creation
  • Using 'init' after project setup
3. Given this Alembic command sequence:
alembic revision -m "add users table"
alembic upgrade head
What happens after running these commands?
medium
A. The database schema is reset to the initial state
B. The migration script is deleted and no changes are applied
C. A new migration script is created and the database schema is updated to include the users table
D. The database schema is downgraded by one version

Solution

  1. Step 1: Understand the revision command

    alembic revision -m "add users table" creates a new migration script file describing the addition of the users table.
  2. Step 2: Understand the upgrade command

    alembic upgrade head applies all migrations up to the latest, updating the database schema accordingly.
  3. Final Answer:

    A new migration script is created and the database schema is updated to include the users table -> Option C
  4. Quick Check:

    revision + upgrade = new migration applied [OK]
Hint: Revision creates script; upgrade applies it to DB [OK]
Common Mistakes:
  • Thinking upgrade resets or deletes migrations
  • Confusing downgrade with upgrade
  • Assuming revision applies changes immediately
4. You run alembic upgrade head but get an error about missing dependencies in your migration script. What is the best way to fix this?
medium
A. Edit the migration script to add missing imports or fix syntax errors
B. Delete all migration scripts and start over
C. Run alembic downgrade base without fixing scripts
D. Ignore the error and rerun the command

Solution

  1. Step 1: Identify cause of error

    Missing dependencies or syntax errors in migration scripts cause upgrade failures.
  2. Step 2: Fix the migration script

    Editing the script to add missing imports or correct syntax resolves the error and allows upgrade to succeed.
  3. Final Answer:

    Edit the migration script to add missing imports or fix syntax errors -> Option A
  4. Quick Check:

    Fix script errors before upgrading [OK]
Hint: Fix migration script errors before upgrading [OK]
Common Mistakes:
  • Deleting scripts unnecessarily
  • Ignoring errors and retrying blindly
  • Downgrading without fixing root cause
5. You want to add a new column to an existing table using Alembic migrations. Which sequence correctly applies this change without losing existing data?
hard
A. Delete the database and recreate it with the new column
B. Create a new revision script adding the column, then run alembic upgrade head
C. Modify the existing migration script that created the table and rerun alembic upgrade head
D. Run alembic downgrade base then create a new revision script

Solution

  1. Step 1: Create a new migration script

    Adding a new column requires a new migration script describing the change to preserve history and data.
  2. Step 2: Apply the migration

    Running alembic upgrade head applies the new migration safely without deleting existing data.
  3. Final Answer:

    Create a new revision script adding the column, then run alembic upgrade head -> Option B
  4. Quick Check:

    New revision + upgrade = safe schema update [OK]
Hint: Always create new revision for schema changes, then upgrade [OK]
Common Mistakes:
  • Modifying old migration scripts after applying
  • Deleting database instead of migrating
  • Downgrading unnecessarily before adding columns