How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Express · JavaScript

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

ServiceUnavailableError: Response timeout at IncomingMessage.<anonymous> (/app/node_modules/connect-timeout/index.js:55:17) at IncomingMessage.emit (node:events:518:28) at Timeout._onTimeout (/app/node_modules/connect-timeout/index.js:49:11) at listOnTimeout (node:internal/timers:581:17) at process.processTicksAndRejections (node:internal/process/task_queues:100:21) at generateReport (/app/src/routes/reports.js:22:18) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:144:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:114:3)

Here's what each line means:

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.

Before (broken)
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);
});
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm timeout scenarios return 503.
  2. Open a pull request with the timeout middleware and query optimization.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.