Skip to main content

Overview

The Queue constructor creates a new queue that is persisted in Redis. Every time the same queue is instantiated, it attempts to process all old jobs that may exist from a previous unfinished session.

Signature

Queue(queueName: string, url?: string, opts?: QueueOptions): Queue

Parameters

queueName
string
required
The name of the queue. Multiple queue instances with the same name will share the same job data.
url
string
Redis connection string. For example: redis://mypassword@myredis.server.com:1234
opts
QueueOptions
Configuration options for the queue.
createClient
function
Custom function to create Redis client instances. Receives type (‘client’, ‘subscriber’, or ‘bclient’) and optional Redis config.
(type: 'client' | 'subscriber' | 'bclient', config?: Redis.RedisOptions) => Redis.Redis | Redis.Cluster
Note: The ‘bclient’ (blocking client) connection cannot be shared and a new connection should be returned each time.
limiter
RateLimiter
Rate limiting configuration.
max
number
required
Maximum number of jobs processed per duration.
duration
number
required
Duration in milliseconds for the rate limit window.
bounceBack
boolean
default:"false"
When jobs get rate limited, they stay in the waiting queue instead of moving to delayed queue.
groupKey
string
Allows grouping of jobs with the specified key from the data object (e.g., “network.handle”).
redis
RedisOpts
Redis connection options (passed directly to ioredis).
port
number
default:"6379"
Redis server port.
host
string
default:"localhost"
Redis server hostname.
db
number
default:"0"
Redis database index.
password
string
Redis authentication password.
prefix
string
default:"bull"
Prefix for all queue keys in Redis.
metrics
MetricsOpts
Configure metrics collection.
maxDataPoints
number
Maximum number of data points to collect. Granularity is fixed at one minute.
defaultJobOptions
JobOpts
Default options to apply to all jobs added to the queue.
settings
AdvancedSettings
Advanced queue behavior settings.
Do not override these settings unless you understand the internals of the queue.
lockDuration
number
default:"30000"
Key expiration time for job locks in milliseconds.
lockRenewTime
number
default:"15000"
Interval in milliseconds on which to renew the job lock.
stalledInterval
number
default:"30000"
How often to check for stalled jobs in milliseconds. Use 0 to never check.
maxStalledCount
number
default:"1"
Maximum number of times a stalled job will be re-processed.
guardInterval
number
default:"5000"
Poll interval for delayed jobs and added jobs in milliseconds.
retryProcessDelay
number
default:"5000"
Delay before processing next job in case of internal error.
backoffStrategies
object
default:"{}"
A set of custom backoff strategies keyed by name.
drainDelay
number
default:"5"
Timeout for when the queue is in drained state (empty waiting for jobs).
isSharedChildPool
boolean
default:"false"
Enables multiple queues on the same instance of child pool to share the same instance.

Examples

Basic Queue

const Queue = require('bull');
const myQueue = new Queue('my-queue');

Queue with Redis URL

const queue = new Queue('notifications', 'redis://password@127.0.0.1:6379');

Queue with Redis Options

const queue = new Queue('emails', {
  redis: {
    port: 6379,
    host: '127.0.0.1',
    password: 'mypassword',
    db: 2
  }
});

Queue with Rate Limiting

const queue = new Queue('api-requests', {
  limiter: {
    max: 100,
    duration: 60000, // 100 requests per minute
    bounceBack: false
  }
});

Queue with Custom Backoff Strategy

const queue = new Queue('processing', {
  settings: {
    backoffStrategies: {
      jitter: function () {
        return 5000 + Math.random() * 500;
      }
    }
  }
});

Queue with Shared Redis Connections

const Redis = require('ioredis');
const client = new Redis();
const subscriber = new Redis();

const createClient = (type, config) => {
  switch (type) {
    case 'client':
      return client;
    case 'subscriber':
      return subscriber;
    case 'bclient':
      return new Redis(config); // bclient cannot be shared
    default:
      return new Redis(config);
  }
};

const queue = new Queue('shared', { createClient });

Queue with Metrics

const queue = new Queue('analytics', {
  metrics: {
    maxDataPoints: 1000
  }
});

Advanced Settings Notes

Lock Duration

Set this to a higher value if your jobs are CPU-intensive and blocking the event loop. Set to a lower value if jobs are extremely time-sensitive and it might be acceptable if they get double-processed.

Stalled Interval

Set this to a lower value if your jobs are extremely time-sensitive. Set this to a higher value if your Redis CPU usage is high, as this check can be expensive.

Guard Interval

When running multiple concurrent workers with delayed tasks, set this value much higher (e.g., numberOfWorkers * 5000) to avoid spikes in network bandwidth, CPU usage, and memory usage.

Max Stalled Count

Set this higher if stalled jobs are common (e.g., processes crash frequently) and it’s generally acceptable to double-process jobs.

Queue.isReady()

Returns a promise that resolves when the queue is ready to accept jobs. This is useful when you need to ensure the queue has finished initializing before adding jobs.

Signature

isReady(): Promise<Queue>

Returns

queue
Promise<Queue>
A promise that resolves to the Queue instance when ready.

Example

const queue = new Queue('myqueue', { redis: { port: 6379 }});

// Wait for queue to be ready before adding jobs
await queue.isReady();

// Now safe to add jobs
await queue.add({ data: 'value' });

Usage in Initialization

async function initializeQueue() {
  const queue = new Queue('myqueue');
  
  // Wait for Redis connection to be established
  await queue.isReady();
  
  // Set up processors
  queue.process(async (job) => {
    return processJob(job);
  });
  
  console.log('Queue is ready');
  return queue;
}
Most of the time you don’t need to call isReady() explicitly, as methods like add() and process() will wait for the queue to be ready internally.

Build docs developers (and LLMs) love