0
0
Expressframework~8 mins

Application-level middleware in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Application-level middleware
MEDIUM IMPACT
This affects server response time and how quickly the server processes requests before sending responses.
Handling request processing with middleware functions
Express
app.use(async (req, res, next) => {
  await someAsyncOperation();
  next();
});
Using asynchronous operations avoids blocking the event loop, allowing other requests to be handled concurrently.
📈 Performance GainNon-blocking, improves throughput and reduces response delays
Handling request processing with middleware functions
Express
app.use((req, res, next) => {
  // heavy synchronous processing
  for (let i = 0; i < 1e7; i++) {}
  next();
});
Blocking synchronous code delays all requests, increasing server response time.
📉 Performance CostBlocks event loop, increasing response time by hundreds of milliseconds per request
Performance Comparison
PatternMiddleware CallsBlockingCPU UsageVerdict
Heavy synchronous middleware on all routesManyYesHigh[X] Bad
Asynchronous middleware on specific routesFewNoLow[OK] Good
Rendering Pipeline
Middleware functions run sequentially on the server before the response is sent. Each middleware can modify the request or response or perform async tasks. Slow or blocking middleware delays the entire response.
Request Processing
Response Preparation
⚠️ BottleneckSynchronous or heavy middleware blocks the event loop, delaying all requests.
Optimization Tips
1Avoid heavy synchronous code in middleware to prevent blocking the event loop.
2Apply middleware only to routes that need it to reduce unnecessary processing.
3Use asynchronous operations inside middleware to keep the server responsive.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using heavy synchronous middleware in Express?
AIt increases the size of the response payload.
BIt causes layout shifts in the browser.
CIt blocks the event loop, delaying all requests.
DIt reduces the number of middleware functions.
DevTools: Node.js Profiler or Chrome DevTools Performance panel
How to check: Run the server with profiling enabled, make requests, and analyze the timeline for blocking middleware or long tasks.
What to look for: Look for long synchronous tasks blocking the event loop or middleware functions taking excessive time.