Advertisement
Advanced Node.js, Express & Middleware

How would you implement a global request timeout middleware in Express to prevent a slow request from hanging indefinitely?

Short answer

A timeout middleware starts a timer when a request begins, and if the response hasn't been sent by the time the timer fires, it sends a timeout response (like 503 or 504) and marks the request as timed out so any later attempt by the actual handler to still respond is safely…

Save Node.js mock interview
Advertisement
AModel answer
A timeout middleware starts a timer when a request begins, and if the response hasn't been sent by the time the timer fires, it sends a timeout response (like 503 or 504) and marks the request as timed out so any later attempt by the actual handler to still respond is safely ignored -- this protects against a slow downstream dependency (a hung database query, an unresponsive third-party API) tying up server resources indefinitely.
function requestTimeout(ms) {
  return (req, res, next) => {
    const timer = setTimeout(() => {
      if (!res.headersSent) res.status(503).json({ error: 'Request timed out' });
    }, ms);
    res.on('finish', () => clearTimeout(timer));
    next();
  };
}

app.use(requestTimeout(10000));
Real-world example
An API wraps every route with a 10-second global timeout middleware, ensuring that if a specific downstream service call hangs indefinitely due to a network issue, the affected request still returns a clear timeout error to the client rather than hanging forever and slowly exhausting server resources.
Likely follow-ups
  • What happens to the underlying operation (like a database query) that was still in progress when the timeout fires -- does it get cancelled, or does it keep running in the background?
  • How would you set different timeout durations for different routes based on their expected typical response time?
Related topics