0
0
Expressframework~8 mins

Why middleware is Express's core concept - Performance Evidence

Choose your learning style9 modes available
Performance: Why middleware is Express's core concept
MEDIUM IMPACT
Middleware affects how requests are processed and how fast the server responds, impacting server response time and throughput.
Handling multiple request tasks in Express
Express
app.use(async (req, res, next) => {
  await someAsyncTask();
  next();
});
Using asynchronous middleware avoids blocking the event loop, allowing other requests to be processed concurrently.
📈 Performance GainNon-blocking, improves throughput and reduces average response time
Handling multiple request tasks in Express
Express
app.use((req, res, next) => {
  // heavy synchronous task
  for(let i = 0; i < 1e8; i++) {}
  next();
});
Blocking synchronous code in middleware delays all requests, causing slow server responses.
📉 Performance CostBlocks event loop, increasing response time by hundreds of milliseconds
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking synchronous middlewareN/AN/AN/A[X] Bad
Asynchronous non-blocking middlewareN/AN/AN/A[OK] Good
Rendering Pipeline
Middleware functions process incoming requests sequentially before sending a response. Each middleware can modify the request or response objects or end the response.
Request Handling
Response Preparation
⚠️ BottleneckSynchronous or heavy middleware blocks the event loop, delaying all subsequent processing.
Optimization Tips
1Avoid heavy synchronous tasks in middleware to prevent blocking the event loop.
2Use asynchronous functions in middleware to keep the server responsive.
3Keep middleware simple and focused to reduce processing time per request.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using synchronous code in Express middleware?
AIt causes layout shifts in the browser
BIt blocks the event loop, delaying all requests
CIt increases CSS paint time
DIt reduces bundle size
DevTools: Node.js Profiler or Chrome DevTools Performance panel
How to check: Run the server with profiling enabled, make requests, and analyze the event loop delays and CPU usage in the profiler.
What to look for: Look for long blocking tasks or high CPU usage in middleware functions indicating slow synchronous code.