0
0
FastAPIframework~8 mins

Alembic migrations in FastAPI - Performance & Optimization

Choose your learning style9 modes available
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.