Fix ServiceUnavailableError: Response timeout — service took too long to respond in Express
This error occurs when an Express route handler takes longer than the configured timeout to send a response, typically due to a slow database query, external API call, or blocking operation. Fix it by setting appropriate timeouts, using the connect-timeout middleware, and ensuring long-running tasks are processed asynchronously.
Reading the Stack Trace
Here's what each line means:
- at IncomingMessage.<anonymous> (/app/node_modules/connect-timeout/index.js:55:17): The connect-timeout middleware detected the response was not sent within the configured timeout period.
- at Timeout._onTimeout (/app/node_modules/connect-timeout/index.js:49:11): The Node.js timer fired, indicating the timeout threshold has been exceeded for this request.
- at generateReport (/app/src/routes/reports.js:22:18): The report generation handler at line 22 is performing a long-running operation that exceeded the timeout.
Common Causes
1. Slow database query without timeout
A database query takes longer than expected and blocks the response indefinitely because no query timeout is set.
app.get('/api/reports', async (req, res) => {
// This query can take 30+ seconds on large datasets
const data = await db.query('SELECT * FROM reports WHERE created_at > $1', [req.query.since]);
res.json(data.rows);
});
2. External API call without timeout
An external API call hangs indefinitely because no timeout or abort signal is configured.
app.get('/api/weather', async (req, res) => {
const response = await fetch('https://api.weather.example.com/forecast');
const data = await response.json();
res.json(data);
});
3. Synchronous blocking operation
A CPU-intensive synchronous operation blocks the event loop, preventing the response from being sent within the timeout.
app.get('/api/compute', (req, res) => {
// CPU-intensive synchronous operation blocks the event loop
const result = heavyComputation(req.query.input);
res.json({ result });
});
The Fix
Add the connect-timeout middleware with a 15-second limit. Check req.timedout before sending responses to avoid writing to an already-closed connection. Add a LIMIT clause to the database query to prevent unbounded result sets, and handle timeout errors with a 503 response.
app.get('/api/reports', async (req, res) => {
const data = await db.query('SELECT * FROM reports WHERE created_at > $1', [req.query.since]);
res.json(data.rows);
});
const timeout = require('connect-timeout');
app.use(timeout('15s'));
app.get('/api/reports', async (req, res, next) => {
try {
const data = await db.query(
'SELECT * FROM reports WHERE created_at > $1 LIMIT 1000',
[req.query.since]
);
if (!req.timedout) {
res.json(data.rows);
}
} catch (err) {
if (!req.timedout) {
next(err);
}
}
});
app.use((err, req, res, next) => {
if (req.timedout) {
return res.status(503).json({
error: 'Service Unavailable',
message: 'The request took too long to process. Please try again.'
});
}
next(err);
});
Testing the Fix
const request = require('supertest');
const express = require('express');
const timeout = require('connect-timeout');
function createApp(queryDelay) {
const app = express();
app.use(timeout('500ms')); // Short timeout for testing
app.get('/api/reports', async (req, res, next) => {
try {
await new Promise(resolve => setTimeout(resolve, queryDelay));
if (!req.timedout) {
res.json({ reports: [] });
}
} catch (err) {
if (!req.timedout) next(err);
}
});
app.use((err, req, res, next) => {
if (req.timedout) {
return res.status(503).json({ error: 'Service Unavailable' });
}
next(err);
});
return app;
}
describe('Request timeout', () => {
it('returns 200 for fast responses', async () => {
const res = await request(createApp(50)).get('/api/reports');
expect(res.status).toBe(200);
expect(res.body.reports).toEqual([]);
});
it('returns 503 when request times out', async () => {
const res = await request(createApp(1000)).get('/api/reports');
expect(res.status).toBe(503);
expect(res.body.error).toBe('Service Unavailable');
});
});
Run your tests:
npx jest --testPathPattern=timeout
Pushing Through CI/CD
git checkout -b fix/express-timeout-error,git add src/middleware/timeout.js src/routes/reports.js src/__tests__/timeout.test.js,git commit -m "fix: add connect-timeout middleware and check req.timedout",git push origin fix/express-timeout-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx jest --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm timeout scenarios return 503.
- Open a pull request with the timeout middleware and query optimization.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and monitor response times in staging before promoting to production.
Frequently Asked Questions
BugStack tests with fast and slow operations, verifies correct 200 and 503 responses, and confirms the timeout does not interfere with normal request handling before marking it safe.
Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.
For typical API endpoints, 10-30 seconds is common. For long-running operations like report generation, consider using a job queue (Bull, BullMQ) with webhooks or polling instead of blocking the HTTP connection.
After a timeout fires, the response may already be partially sent. Checking req.timedout prevents your handler from trying to write to a closed connection, which would cause an ERR_HTTP_HEADERS_SENT error.