Intermediate LevelExpress JS
How do you use connect-timeout middleware to terminate hanging requests that exceed SLA thresholds?
❓ Interview Prompt: Explain connect-timeout middleware, req.timedout property, terminating hanging database queries, and returning 503 Service Unavailable.
Hanging database queries or external API calls can keep Express request sockets open indefinitely, exhausting Node.js thread memory.
Using 'connect-timeout':
Registers a request timeout threshold (e.g. 5 seconds). If the route handler takes longer than 5 seconds, the middleware sets 'req.timedout = true' and emits a 503 Service Unavailable error! Route handlers must check 'if (req.timedout) return' to halt processing.
Code Implementation Example
javascript
import express from 'express';
import timeout from 'connect-timeout';
const app = express();
app.use('/api/', timeout('5s'));
app.get('/api/heavy-query', (req, res, next) => {
setTimeout(() => {
// Check if request timed out before sending response!
if (req.timedout) return;
res.json({ status: 'Completed under 5s' });
}, 6000);
});💡Terminating hanging requests with connect-timeout middleware.
🎯 Interview Key Takeaway
Use connect-timeout middleware to cancel hanging requests exceeding SLA thresholds with 503 Service Unavailable.
#connect-timeout#SLA#Timeouts#Intermediate
Back to all Express JS Questions→