How to Handle External API Rate Limits with BullMQ and Redis

by Fahim Mahmud Chisti

When several workers call the same external API at once, the provider answers with 429 Too Many Requests and your payloads start failing. This tutorial shows how to handle external API rate limits in Node.js with BullMQ and Redis: a queue that throttles outgoing requests to the provider’s limit and backs off when a 429 still arrives.

Quick answer: Put every outgoing call in a BullMQ queue and give the worker a limiter option, such as 5 jobs per 10 seconds. BullMQ enforces that limit in Redis across all workers. When the API still returns 429, pause the whole queue with worker.rateLimit() for the Retry-After time.

  1. Install bullmq, ioredis and axios, and start Redis.
  2. Create a queue with retry attempts and exponential backoff.
  3. Start a worker with limiter: { max, duration } set to the provider’s limit.
  4. On a 429, call worker.rateLimit(ms) and throw Worker.RateLimitError().
  5. Add jobs with apiQueue.add() and watch the worker start them in batches.
In this guide
  1. Before You Start
  2. What You Will Build
  3. Why In-Memory Throttling Fails Once You Scale
  4. How BullMQ Enforces a Rate Limit in Redis
  5. Step 1: Set Up the Project
  6. Step 2: Create the Queue
  7. Step 3: Start a Worker with a Rate Limiter
  8. Test It: Watch the Limiter Hold Jobs Back
  9. Step 4: Handle 429 Responses with Retry-After
  10. Limiter vs Concurrency: The Setting People Mix Up
  11. What Throughput to Expect
  12. If It Still Doesn’t Work
  13. Frequently Asked Questions
  14. Next Steps
Redis terminal output showing commands used by BullMQ for queue rate limiting.

Before You Start

  • Node.js 18 or newer (a current LTS release is best).
  • A running Redis server. Locally: docker run -d --name redis-queue -p 127.0.0.1:6379:6379 redis. BullMQ needs the eviction policy noeviction, which is the Redis default. Managed Redis services sometimes change it, so check with docker exec redis-queue redis-cli config get maxmemory-policy (drop the docker exec redis-queue part if Redis is installed locally).
  • The provider’s documented rate limit, for example “100 requests per minute”. You will copy it into the worker settings.
  • About 30 minutes. Nothing here touches a live site, but test against a sandbox or test endpoint before you send real data.

What You Will Build

  • tsconfig.json – TypeScript settings.
  • queue.ts – the Redis connection settings and the queue your app adds jobs to.
  • worker.ts – the process that sends the HTTP requests, at most 5 every 10 seconds.
  • enqueue.ts – a small script that adds test jobs.
  • .env (optional) – REDIS_HOST and REDIS_PORT if Redis is not on 127.0.0.1:6379.

Why In-Memory Throttling Fails Once You Scale

Most teams start with an in-memory throttle: a setTimeout loop or a rate-limiting package in its default mode. That works inside one Node.js process. It breaks as soon as you run several instances, because each one keeps its own count.

If instance A and instance B both think they have capacity left, they fire at the same time. To the external API that looks like one burst, and it starts returning 429s. You need one shared counter that every instance checks. Redis with BullMQ gives you that, which is why it is a standard building block for API integrations and webhooks that run on more than one server.

How BullMQ Enforces a Rate Limit in Redis

BullMQ stores every job, delay and rate-limit counter in Redis and updates them with Lua scripts, so each change is atomic. When a worker asks for the next job, BullMQ first checks the limit. If the current window is used up, it holds the job back until the window opens again, without keeping your worker busy or blocking the event loop.

Because the jobs themselves live in Redis, Redis must not delete them. Two settings matter:

  • maxmemory-policy noeviction: any other policy lets Redis silently drop queue data when memory runs low.
  • Persistence: the BullMQ docs recommend Append Only File (AOF), so a Redis restart does not lose queued payloads.

If the same app also uses Redis as a cache, keep the cache on a separate instance. A cache usually wants an eviction policy such as allkeys-lru, as in the Redis caching tutorial for Node.js, and one instance cannot have both policies.

Step 1: Set Up the Project

Run these commands in your terminal. They create the project folder and install BullMQ, its Redis client, dotenv for settings, Axios for HTTP calls and the TypeScript tools:

mkdir bullmq-rate-limiter
cd bullmq-rate-limiter
npm init -y
npm install bullmq ioredis dotenv axios
npm install --save-dev typescript @types/node tsx

The examples use TypeScript so the job payload has a defined type. Create a tsconfig.json file in the project folder:

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        "esModuleInterop": true,
        "strict": true,
        "skipLibCheck": true
    }
}

The examples below work with BullMQ 5 and 6. Since BullMQ 6, ioredis is an optional peer dependency, which is why we install it explicitly above.

Step 2: Create the Queue

Create a file named queue.ts. It defines the Redis connection settings and the queue that the rest of your app adds jobs to:

import { Queue, ConnectionOptions } from 'bullmq';
import dotenv from 'dotenv';
dotenv.config();
export const redisConnection: ConnectionOptions = {
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: parseInt(process.env.REDIS_PORT || '6379', 10),
  maxRetriesPerRequest: null,
};
export const apiQueue = new Queue('external-api-queue', {
  connection: redisConnection,
  defaultJobOptions: {
    attempts: 5,
    backoff: { type: 'exponential', delay: 2000 },
    removeOnComplete: true,
    removeOnFail: 1000,
  },
});

The defaultJobOptions give every job 5 attempts with exponential backoff starting at 2 seconds, so a failed request is retried after 2, 4, 8 and 16 seconds. Keep maxRetriesPerRequest: null: BullMQ requires it for the connections its workers use.

Step 3: Start a Worker with a Rate Limiter

The limiter option is what does the throttling. It sets the maximum number of jobs that can start within a time window. BullMQ enforces it in Redis for the whole queue, so the limit holds no matter how many worker processes you run.

Create a file named worker.ts. This worker allows at most 5 requests per 10 seconds, a typical limit for third-party and CRM APIs:

import { Worker, Job } from 'bullmq';
import axios from 'axios';
import { redisConnection } from './queue.js';
interface ApiJobData {
  url: string;
  payload: Record<string, unknown>;
}
const worker = new Worker<ApiJobData>('external-api-queue', async (job: Job<ApiJobData>) => {
  console.log(`[Worker] Processing job ${job.id} to ${job.data.url}...`);
  try {
    const response = await axios.post(job.data.url, job.data.payload, {
      headers: { 'Content-Type': 'application/json' },
      timeout: 5000,
    });
    console.log(`[Worker] Job ${job.id} completed. Status: ${response.status}`);
    return response.data;
  } catch (error: any) {
    if (error.response) {
      console.error(`[Worker] Job ${job.id} failed with status ${error.response.status}`);
      throw error;
    }
    throw new Error(`Network failure: ${error.message}`);
  }
}, {
  connection: redisConnection,
  limiter: {
    max: 5,
    duration: 10000, // At most 5 jobs per 10-second window
  },
  concurrency: 1, // One request in flight at a time per worker process
});
worker.on('failed', (job, err) => {
  console.error(`[Queue Error] Job ${job?.id} failed on attempt ${job?.attemptsMade}: ${err.message}`);
});
worker.on('error', (err) => {
  console.error('[Worker Error]', err);
});
console.log('[Worker] Outgoing API Worker started successfully.');

Start the worker in its own terminal:

npx tsx worker.ts

You should see [Worker] Outgoing API Worker started successfully. Leave it running. Anywhere in your app, you can now enqueue a request with await apiQueue.add('send', { url, payload }).

Test It: Watch the Limiter Hold Jobs Back

Create a file named enqueue.ts that adds 12 test jobs. It posts to httpbin.org, a free service that echoes requests back, so no real API is touched:

import { apiQueue } from './queue.js';
async function main() {
  for (let i = 1; i <= 12; i++) {
    await apiQueue.add('send', { url: 'https://httpbin.org/post', payload: { n: i } });
  }
  console.log('Added 12 jobs');
  await apiQueue.close();
}
main();

Run it in a second terminal:

npx tsx enqueue.ts

The script prints Added 12 jobs and exits. In the worker terminal, the first 5 jobs log Processing job and completed. Status: 200 straight away. Then the worker pauses until the next 10-second window opens before it starts the next 5, and the last 2 follow after that. If all 12 run at once, the limiter is not set on the worker you started.

Step 4: Handle 429 Responses with Retry-After

A fixed limit in your code is not always enough. Many APIs adjust their limits on the fly and return a Retry-After header with a 429 when you exceed your quota. When that happens, respect the header, hold the whole queue back and retry the job afterwards.

BullMQ’s worker methods handle both parts:

  • worker.rateLimit(ms) pauses the whole queue for that many milliseconds, so other waiting jobs do not waste calls during the block.
  • Throwing Worker.RateLimitError() afterwards moves the current job back to the waiting list instead of counting it as a failed attempt.

The code below is a complete replacement for worker.ts. If you want the same logs as before, copy the worker.on('failed') and worker.on('error') listeners from the first version to the bottom of the file.

import { Worker, Job } from 'bullmq';
import axios from 'axios';
import { redisConnection } from './queue.js';
const worker = new Worker('external-api-queue', async (job: Job) => {
  try {
    const response = await axios.post(job.data.url, job.data.payload);
    return response.data;
  } catch (error: any) {
    if (error.response && error.response.status === 429) {
      // Retry-After is normally a number of seconds. Default to 15 seconds if it is missing or not numeric
      const retryAfterSeconds = Number(error.response.headers['retry-after']);
      const delayMs = retryAfterSeconds > 0 ? retryAfterSeconds * 1000 : 15000;
      console.warn(`[Rate Limit Hit] Received 429. Rate limiting the queue for ${delayMs}ms.`);
      // Rate limit the whole queue so no other job fires during the block
      await worker.rateLimit(delayMs);
      // This special error moves the job back to the waiting list instead of marking it as failed
      throw Worker.RateLimitError();
    }
    throw error;
  }
}, {
  connection: redisConnection,
  // Required: worker.rateLimit() only takes effect when limiter options are set
  limiter: { max: 5, duration: 10000 },
});

To see it work, change the URL in enqueue.ts to https://httpbin.org/status/429, which always answers 429 without a Retry-After header. Restart the worker and run the script again. The worker logs [Rate Limit Hit] Received 429. Rate limiting the queue for 15000ms. and waits before trying again. Because that test endpoint never succeeds, stop the worker with Ctrl+C once you have seen the message. The test jobs stay in Redis; on a test instance you can clear them with docker exec redis-queue redis-cli flushall, which deletes everything in that Redis.

Limiter vs Concurrency: The Setting People Mix Up

The limiter and concurrency options are easy to confuse. The limiter caps how many jobs are started per time window, and it is global: BullMQ enforces it in Redis across every worker attached to the queue. Adding workers or raising concurrency does not raise the rate. With max: 5, duration: 10000, at most 5 jobs start per 10-second window whether you run one worker or ten.

What the limiter does not control is how many requests are in flight at the same moment. If the external API is slow, jobs started in an earlier window can still be running when the next window opens. Use concurrency to cap simultaneous requests per worker process. The total is concurrency multiplied by the number of worker processes.

What Throughput to Expect

The limiter makes throughput easy to predict. With max: 5 and duration: 10000, a backlog of 100 jobs needs 20 windows, so it drains in a little over three minutes no matter how fast the external API answers.

Because requests are held back before they are sent, a correctly sized limiter means the API should rarely return a 429 at all. The 429 handler is the safety net for when the provider’s limit is lower than you assumed or is shared with other clients. Set max and duration slightly below the documented limit to leave some headroom.

If It Still Doesn’t Work

  • ECONNREFUSED 127.0.0.1:6379: Redis is not running or is on another host. Start the container with docker start redis-queue, or set REDIS_HOST and REDIS_PORT in .env.
  • BullMQ complains about maxRetriesPerRequest: the connection options lost maxRetriesPerRequest: null, which is common when you pass your own ioredis instance. Put it back in queue.ts.
  • BullMQ logs a warning about the eviction policy: your Redis uses a policy other than noeviction. Change it in the Redis config or your provider’s dashboard before you rely on the queue.
  • Jobs sit in the queue and never run: the worker is not running, or the queue name differs. Both files must use 'external-api-queue'.
  • Jobs fail with timeout of 5000ms exceeded: the API took longer than the Axios timeout. Raise timeout in the worker if the provider is known to be slow.

Frequently Asked Questions

Can I rate limit BullMQ jobs per user or per API key?

Not with the built-in limiter, which is global per queue. Older versions accepted a groupKey in the limiter options, but group keys were removed in BullMQ 3.0. To limit per API key or per user, give each key its own queue with its own limiter, or use the groups feature of the commercial BullMQ Pro.

What is the difference between Bull and BullMQ?

BullMQ is the modern, TypeScript-first rewrite of the original Bull library. It adds parent-child job dependencies (flows) and delivers queue events through Redis Streams instead of Pub/Sub, so events are not lost when a listener briefly disconnects. Bull itself is in maintenance mode, so new projects should start with BullMQ.

How does BullMQ handle Redis connection drops?

It reconnects automatically through the ioredis library. With maxRetriesPerRequest: null in your connection options, commands wait for Redis to come back instead of failing with connection errors. Jobs already stored in Redis stay there and resume once the connection returns.

Should I use a separate Redis instance for BullMQ?

Yes, in production a dedicated instance for queues is a good idea. BullMQ needs maxmemory-policy noeviction, while a cache usually wants allkeys-lru, and one instance cannot have both. A separate instance also stops queue traffic and its Lua scripts from competing with your cache for the same CPU.

Next Steps

You now have a queue that keeps outgoing calls under the provider’s limit and backs off when a 429 still arrives. Set the limiter to your provider’s documented limit, run at least two worker processes to confirm the limit holds across both, and enable AOF on Redis before going live. If the requests you send are webhooks to your customers, add dead-letter handling and jittered retries from the guide to building a webhook retry system with exponential backoff.

Disclosure: This post may contain affiliate links. If you purchase through our link, we may earn a commission at no extra cost to you.

all_in_one_marketing_tool