0
0
NextJSframework~8 mins

Server action database mutations in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Server action database mutations
MEDIUM IMPACT
This affects the time to update data on the server and how quickly the UI reflects those changes, impacting interaction responsiveness and perceived speed.
Updating user data with server actions in Next.js
NextJS
let dbConnection;
export async function updateUser(data) {
  if (!dbConnection) {
    dbConnection = await db.connect();
  }
  await db.users.updateOne({ id: data.id }, { $set: data });
  // Keep connection open for batch mutations
}

// Debounce input to reduce calls
Reusing the database connection and batching updates reduces latency and server load.
📈 Performance GainReduces blocking time to under 50ms per action, improving INP significantly
Updating user data with server actions in Next.js
NextJS
export async function updateUser(data) {
  await db.connect();
  await db.users.updateOne({ id: data.id }, { $set: data });
  await db.disconnect();
}

// Called on every user input change triggering multiple server actions rapidly
Connecting and disconnecting the database on every small mutation causes high latency and blocks UI updates.
📉 Performance CostBlocks rendering for 200-500ms per action, causing input lag and poor INP
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Connect/disconnect DB per mutationN/AN/ABlocks UI update 200-500ms[X] Bad
Reuse DB connection and batch mutationsN/AN/ABlocks UI update <50ms[OK] Good
Rendering Pipeline
Server actions run on the server and update the database, then the client receives updated data to re-render UI. Slow server actions delay the next paint after user input.
Server Processing
Network
Client Rendering
⚠️ BottleneckServer Processing time for database mutation
Core Web Vital Affected
INP
This affects the time to update data on the server and how quickly the UI reflects those changes, impacting interaction responsiveness and perceived speed.
Optimization Tips
1Reuse database connections in server actions to avoid repeated connection overhead.
2Batch multiple mutations into a single server action call to reduce latency.
3Debounce client calls to server actions to prevent flooding the server with requests.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with connecting and disconnecting the database on every server action call?
AIt causes layout shifts on the client.
BIt causes high latency and blocks UI updates.
CIt increases the bundle size significantly.
DIt improves caching efficiency.
DevTools: Performance
How to check: Record a performance profile while triggering server actions. Look for long tasks on the server and delayed next paint after input.
What to look for: Long blocking times after user input and delayed UI updates indicate slow server actions.