0
0
NextJSframework~8 mins

Database migrations in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Database migrations
MEDIUM IMPACT
Database migrations affect the backend deployment speed and can indirectly impact frontend load times if migrations block API responses.
Applying database schema changes during app startup
NextJS
import { migrate } from 'some-migration-lib';

// Run migrations once during deployment or startup, not per request
await migrate();

export async function getServerSideProps() {
  return { props: {} };
}
Migrations run once upfront, so requests are fast and non-blocking.
📈 Performance Gainreduces request blocking to near zero, improving response time
Applying database schema changes during app startup
NextJS
import { migrate } from 'some-migration-lib';

export async function getServerSideProps() {
  await migrate(); // runs migrations on every request
  return { props: {} };
}
Running migrations on every server request blocks response and increases latency.
📉 Performance Costblocks rendering for 100-500ms per request depending on migration size
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Run migrations on every requestN/AN/ABlocks frontend rendering due to slow API[X] Bad
Run migrations once during deploymentN/AN/AFast API responses, smooth frontend rendering[OK] Good
Run large migrations synchronously in APIN/AN/ABlocks API response, causes slow interaction[X] Bad
Run large migrations asynchronously in backgroundN/AN/ANon-blocking API, fast user interaction[OK] Good
Rendering Pipeline
Database migrations run on the backend and can delay server responses that frontend depends on, indirectly affecting rendering speed.
Server Response Time
Data Fetching
Frontend Rendering
⚠️ BottleneckServer Response Time when migrations run synchronously
Optimization Tips
1Run database migrations during deployment, not on user requests.
2Avoid synchronous migrations in API handlers to prevent blocking responses.
3Use background jobs or async triggers for large migrations to keep frontend responsive.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of running database migrations during every frontend request?
AIt causes layout shifts on the page
BIt increases CSS paint cost
CIt blocks server response, increasing frontend load time
DIt reduces JavaScript bundle size
DevTools: Performance
How to check: Record a server response timeline while triggering API calls that run migrations; look for long blocking times.
What to look for: Long server blocking times or delayed API responses indicate migration blocking.