Product How it works Features Security What is bugstack? SDKs JavaScript SDK Python SDK Go SDK Ruby SDK Docs Pricing Blog Book a demo
Log In Get started
Express · JavaScript

Fix TooManyRequestsError: Too Many Requests — rate limit exceeded in Express

This error occurs when a client exceeds the configured request rate limit. The express-rate-limit middleware blocks further requests and returns a 429 status. Fix it by tuning the rate limit window and max values, adding a custom handler with a Retry-After header, and using a persistent store for multi-instance deployments.

Reading the Stack Trace

HTTP/1.1 429 Too Many Requests X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1700000060 Retry-After: 60 Error: Too Many Requests at rateLimit (/app/node_modules/express-rate-limit/dist/index.js:72:23) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/app/node_modules/express/lib/router/index.js:328:13) at /app/node_modules/express/lib/router/index.js:284:15 at Function.process_params (/app/node_modules/express/lib/router/index.js:346:12) at next (/app/node_modules/express/lib/router/index.js:280:10) at expressInit (/app/node_modules/express/lib/middleware/init.js:40:5) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)

Here's what each line means:

Common Causes

1. Rate limit window too small

The windowMs or max values are too restrictive, causing legitimate users to hit the limit during normal usage.

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1 minute
  max: 5 // Only 5 requests per minute
});

app.use(limiter);

2. In-memory store with multiple instances

Using the default in-memory store behind a load balancer means each instance tracks its own counter, leading to inconsistent rate limiting.

const rateLimit = require('express-rate-limit');

// Default in-memory store — not shared across cluster workers
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
});

app.use(limiter);

3. No custom handler for rate-limited requests

The default 429 response does not include a helpful message or Retry-After header, leaving clients without guidance on when to retry.

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
  // No handler or message configured
});

app.use('/api/', limiter);

express-rate-limit answers the request with a 429 itself, so it never reaches the bugstack SDK as a crash. If it points to a bug in your code, pass an Error to next(err) where you handle it, and the bugstack error handler reports it; bugstack then works on it like any error the SDK reports.

Get started →

The Fix

Increase the rate limit window to 15 minutes with 100 requests, enable standard RateLimit headers, and add a custom handler that returns a clear JSON error with retry timing so clients know when they can resume requests.

Before (broken)
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 5
});

app.use(limiter);
After (fixed)
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // 100 requests per 15-minute window
  standardHeaders: true, // Return RateLimit-* headers
  legacyHeaders: false,
  handler: (req, res) => {
    res.status(429).json({
      error: 'Too many requests, please try again later.',
      retryAfter: Math.ceil(req.rateLimit.resetTime / 1000)
    });
  }
});

app.use('/api/', limiter);

Testing the Fix

const request = require('supertest');
const express = require('express');
const rateLimit = require('express-rate-limit');

function createApp(max = 2) {
  const app = express();
  app.use(rateLimit({
    windowMs: 15 * 60 * 1000,
    max,
    handler: (req, res) => {
      res.status(429).json({ error: 'Too many requests, please try again later.' });
    }
  }));
  app.get('/api/data', (req, res) => res.json({ ok: true }));
  return app;
}

describe('Rate limiting', () => {
  it('allows requests under the limit', async () => {
    const res = await request(createApp(2)).get('/api/data');
    expect(res.status).toBe(200);
  });

  it('returns 429 when limit is exceeded', async () => {
    const app = createApp(1);
    await request(app).get('/api/data');
    const res = await request(app).get('/api/data');
    expect(res.status).toBe(429);
    expect(res.body.error).toBe('Too many requests, please try again later.');
  });
});

Run your tests:

npx jest --testPathPattern=rate-limit

Pushing Through CI/CD

git checkout -b fix/express-rate-limit-error
git add src/middleware/rateLimiter.js src/__tests__/rateLimit.test.js
git commit -m "fix: tune rate limit config and add custom 429 handler"
git push origin fix/express-rate-limit-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 error source
  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

Set up once, and bugstack takes over the steps from reading the stack trace to proving the fix in an isolated sandbox and opening the pull request. Your CI runs on the pull request, and you set how much merges without you.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Set it up

const { initBugStack, bugstackErrorHandler } = require('bugstack-sdk/express')

// After app creation:
app.use(initBugStack({
  apiKey: process.env.BUGSTACK_API_KEY,
  endpoint: process.env.BUGSTACK_ENDPOINT || 'https://dashboard.bugstack.ai/api/ingest/sdk',
}))

// ... your routes ...

// Before app.listen:
app.use(bugstackErrorHandler())

Set BUGSTACK_API_KEY to the key from your dashboard (it starts with bsk_). Then pass an Error to next(err) where you handle it, and the bugstack error handler reports it.

Step 3: Connect your repository

Sign in at dashboard.bugstack.ai with GitHub, start the 14-day trial, and install the bugstack GitHub App on the repository.

Then, each time the error is reported:

  1. Your report sends the error and its stack trace
  2. bugstack reads the files in the stack trace from your repository
  3. Specialist agents work out the cause and write a small change
  4. In an isolated sandbox, a test reproduces the error and fails on your current code; with the change it passes, and your other tests still pass
  5. The change arrives as a pull request with that test and its proof, and your CI runs on it
  6. On Review, the starting level, you merge it. On Autopilot it merges with green CI and its sandbox proof, checked again at merge.

You review a pull request instead of debugging.

You set how much merges without you.

Get started →

Start with a 14-day trial: $50 of credit and a first security audit on us. Then Pro is $100 a month with $100 of usage credit every month. A card is required.

Deploying the Fix (Manual Path)

  1. Run the test suite locally to confirm rate limiting works as expected.
  2. Open a pull request with the rate limiter configuration changes.
  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 429 response rates in staging before promoting to production.

Frequently Asked Questions

Yes. The default in-memory store does not share state across multiple server instances. Use rate-limit-redis or a similar adapter so all instances enforce a consistent limit per client.

Apply the rate limiter to a specific path prefix like app.use('/api/', limiter) or use the skip option to bypass limiting for health checks and other internal endpoints.

express-rate-limit answers the request with a 429 itself, so it never reaches the bugstack SDK as a crash. If it points to a bug in your code, pass an Error to next(err) where you handle it, and the bugstack error handler reports it; bugstack then works on it like any error the SDK reports.

bugstack proves it before you see it. In an isolated copy of your repository, with the network cut, it writes a test that reproduces this error and fails on your current code; with the fix the test passes and the rest of your tests still pass. The pull request carries that test and its proof, your CI runs on it, and on Autopilot it merges only with that proof, checked again at merge.

A fix that does not turn the reproduction test green, or that breaks another test, never becomes a pull request. A fix that does is still a pull request, so your CI runs on it, and on Review, the starting level, a person merges it. Undoing a merged fix opens a revert pull request.

Stop fixing JavaScript errors manually.

bugstack catches uncaught server errors, failed deploys and failing CI, works out the cause, and opens a pull request you control.