kue vs agenda vs bee-queue vs bull vs bullmq
Node.js 后台任务队列方案选型
kueagendabee-queuebullbullmq类似的npm包:

Node.js 后台任务队列方案选型

agendabee-queuebullbullmqkue 都是 Node.js 生态中用于处理后台作业和定时任务的队列库。它们允许开发者将耗时的操作(如发送邮件、处理图像或生成报告)从主请求循环中剥离,异步执行以提高应用响应速度。agenda 基于 MongoDB,适合需要持久化和复杂调度的场景;bullbullmq 基于 Redis,性能更高,其中 bullmq 是现代化的重构版本;bee-queue 追求极简的 Redis 实现;而 kue 是早期的 Redis 队列方案,目前已不再维护。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
kue21,8959,431-2889 年前MIT
agenda09,691301 kB4918 天前MIT
bee-queue04,036107 kB478 个月前MIT
bull016,247309 kB1472 年前MIT
bullmq09,2562.86 MB37217 小时前MIT

Node.js 作业队列深度对比:Agenda, Bee-Queue, Bull, BullMQ 与 Kue

在构建高可用的 Node.js 应用时,将耗时任务移出主线程是标准做法。agendabee-queuebullbullmqkue 都旨在解决这一问题,但它们的底层架构、存储引擎和维护状态截然不同。本文将从架构、API 设计和维护性三个维度进行深度剖析。

🗄️ 存储引擎与架构设计

选择队列库的核心在于理解数据存哪里以及如何取出来。

agenda 使用 MongoDB 存储作业。

  • 作业数据持久化在集合中,重启不会丢失。
  • 适合需要复杂查询作业历史或依赖 Mongo 生态的场景。
// agenda: 基于 MongoDB
const agenda = new Agenda({ db: { address: 'mongodb://localhost/agenda' } });
await agenda.start();

bee-queue 使用 Redis,强调极简。

  • 数据存在 Redis 内存中,配置简单。
  • 架构轻量,没有复杂的 Lua 脚本依赖。
// bee-queue: 基于 Redis
const Queue = require('bee-queue');
const queue = new Queue('my-queue', { redis: { host: 'localhost' } });

bull 使用 Redis 和 Lua 脚本。

  • 利用 Redis 特性保证作业处理的原子性。
  • 队列和处理器通常在同一个进程中配置(虽可分离)。
// bull: 基于 Redis
const Queue = require('bull');
const queue = new Queue('my-queue', 'redis://localhost');

bullmq 使用 Redis 5+,架构分离。

  • 强制区分 Queue(提交作业)和 Worker(处理作业)。
  • 支持 Redis Stream,性能更强,适合微服务架构。
// bullmq: 基于 Redis 5+
const { Queue, Worker } = require('bullmq');
const queue = new Queue('my-queue', { connection: { host: 'localhost' } });
const worker = new Worker('my-queue', async (job) => {}, { connection: { host: 'localhost' } });

kue 使用 Redis,旧式架构。

  • 早期设计,依赖 Redis 哈希表。
  • 目前已不再维护,架构过时。
// kue: 基于 Redis (已弃用)
const kue = require('kue');
const queue = kue.createQueue();

📝 定义与添加作业

不同库在创建任务时的 API 风格差异明显,这直接影响代码的可读性。

agenda 需要先定义任务名称,再调度。

  • 适合集中管理任务逻辑。
// agenda: 定义并调度
agenda.define('send email', async (job) => { /*...*/ });
await agenda.every('5 minutes', 'send email', { to: 'user@example.com' });

bee-queue 直接创建作业对象并保存。

  • API 非常直观,类似面向对象风格。
// bee-queue: 创建并保存
const job = queue.createJob({ to: 'user@example.com' });
await job.save();

bull 通过队列实例直接添加数据。

  • 简洁,适合快速投递。
// bull: 直接添加
await queue.add({ to: 'user@example.com' }, { attempts: 3 });

bullmqbull 类似,但配置更现代化。

  • 支持更丰富的选项类型定义。
// bullmq: 直接添加
await queue.add('send email', { to: 'user@example.com' }, { attempts: 3 });

kue 类似 bee-queue,创建后保存。

  • 语法老旧,但逻辑清晰。
// kue: 创建并保存 (已弃用)
const job = queue.create('send email', { to: 'user@example.com' });
job.save();

⚙️ 处理作业逻辑

当任务被执行时,各库的处理器写法有所不同,特别是在异步控制和完成信号上。

agenda 使用 async/await 或回调。

  • 完成信号由函数返回或调用 done() 决定。
// agenda: 处理器
agenda.define('send email', async (job) => {
  await sendEmail(job.attrs.data.to);
});

bee-queue 使用回调或 Promise。

  • 需要调用 done() 或返回 Promise。
// bee-queue: 处理器
queue.process(async (job, done) => {
  await sendEmail(job.data.to);
  done();
});

bull 支持 Promise 或回调。

  • 返回 Promise 即视为完成。
// bull: 处理器
queue.process(async (job) => {
  await sendEmail(job.data.to);
});

bullmq 必须在 Worker 中定义处理器。

  • 强制异步函数,天然支持 Promise。
// bullmq: Worker 处理器
const worker = new Worker('my-queue', async (job) => {
  await sendEmail(job.data.to);
}, { connection: redisConfig });

kue 使用回调风格。

  • 必须显式调用 done()
// kue: 处理器 (已弃用)
queue.process('send email', (job, done) => {
  sendEmail(job.data.to, done);
});

🕒 定时与重复任务

对于需要周期性执行的任务,各库的支持程度不一。

agenda 原生支持 cron 语法。

  • 这是 agenda 的强项,非常适合定时调度。
// agenda: 原生 Cron
await agenda.every('*/5 * * * *', 'send email');

bee-queue 不原生支持重复任务。

  • 需要外部调度器或在任务结束时重新添加任务。
// bee-queue: 无原生支持
// 需在任务完成后手动再次 job.save() 实现循环

bull 支持重复任务配置。

  • 通过 repeat 选项实现。
// bull: 重复配置
await queue.add({ to: 'user' }, { repeat: { cron: '*/5 * * * *' } });

bullmq 支持更强大的重复配置。

  • 基于 Redis Stream,处理重复任务更可靠。
// bullmq: 重复配置
await queue.add('send email', { to: 'user' }, { repeat: { pattern: '*/5 * * * *' } });

kue 支持延迟和简单重复。

  • 但功能有限,不再推荐。
// kue: 延迟任务 (已弃用)
const job = queue.create('email', data).delay(2000);
job.save();

⚠️ 维护状态与风险提示

这是架构选型中最关键的一环,直接影响项目的长期稳定性。

包名存储维护状态建议
agendaMongoDB✅ 活跃适合 Mongo 用户
bee-queueRedis⚠️ 低活跃适合简单场景
bullRedis⚠️ 维护模式旧项目继续,新项目慎用
bullmqRedis 5+✅ 活跃✅ 新项目首选
kueRedis❌ 已弃用❌ 禁止使用

kue 已明确标记为不再维护,存在已知漏洞,切勿在生产环境使用。 bull 虽然稳定,但官方推荐迁移至 bullmq 以获取更好的性能和类型支持。 agenda 是 MongoDB 生态下的最佳选择,但需注意数据库写入压力。

💡 最终建议

bullmq 是目前 Node.js 生态中最均衡的选择 — 性能强大、架构现代、社区活跃。如果你的基础设施支持 Redis 5+,它是默认选项。

agenda 适合那些已经重度依赖 MongoDB 且需要复杂定时调度的团队 — 避免引入额外的 Redis 依赖。

bee-queue 适合极简主义项目 — 如果你只需要一个简单的 FIFO 队列且不想配置复杂的环境。

kuebull (3.x) 属于历史遗产 — 除非维护旧系统,否则不应出现在新的架构设计图中。选择正确的工具能让后台任务管理变得简单 — 而不是成为技术债务的来源。

如何选择: kue vs agenda vs bee-queue vs bull vs bullmq

  • kue:

    切勿在新项目中选择 kue。该库已正式弃用且多年未维护,存在未修复的安全漏洞和兼容性问题。如果当前正在使用,应尽快制定迁移计划,转向 bullmqagenda 等活跃维护的替代方案。

  • agenda:

    如果你的项目已经使用 MongoDB,或者需要复杂的 cron 表达式调度以及作业内容的持久化存储,选择 agenda 是最自然的决定。它适合对任务状态查询要求高、且能接受比 Redis 稍慢写入速度的场景。

  • bee-queue:

    选择 bee-queue 适合需要极简 API、低内存占用且基于 Redis 的轻量级项目。它的代码库很小,易于理解,但社区活跃度相对较低,适合不需要复杂高级功能的简单队列需求。

  • bull:

    如果你的项目是旧系统维护,或者需要大量现有的 bull 3.x 生态插件,可以继续使用 bull。但需注意它已进入维护模式,新功能开发建议转向 bullmq,适合追求稳定且不想大幅重构的现有 Redis 队列用户。

  • bullmq:

    对于全新的 Node.js 项目,bullmq 是首选方案。它采用了现代架构,将队列定义与 worker 处理分离,支持 Redis 5+ 的高级特性,性能更优且类型支持更好,适合高并发和长期维护的生产环境。

kue的README

Kue

Build Status npm version Dependency Status Join the chat at https://gitter.im/Automattic/kue

Kue is a priority job queue backed by redis, built for node.js.

PROTIP This is the latest Kue documentation, make sure to also read the changelist.

Upgrade Notes (Please Read)

Installation

  • Latest release:

    $ npm install kue
    
  • Master branch:

    $ npm install http://github.com/Automattic/kue/tarball/master
    

NPM

Features

  • Delayed jobs
  • Distribution of parallel work load
  • Job event and progress pubsub
  • Job TTL
  • Optional retries with backoff
  • Graceful workers shutdown
  • Full-text search capabilities
  • RESTful JSON API
  • Rich integrated UI
  • Infinite scrolling
  • UI progress indication
  • Job specific logging
  • Powered by Redis

Overview

Creating Jobs

First create a job Queue with kue.createQueue():

var kue = require('kue')
  , queue = kue.createQueue();

Calling queue.create() with the type of job ("email"), and arbitrary job data will return a Job, which can then be save()ed, adding it to redis, with a default priority level of "normal". The save() method optionally accepts a callback, responding with an error if something goes wrong. The title key is special-cased, and will display in the job listings within the UI, making it easier to find a specific job.

var job = queue.create('email', {
    title: 'welcome email for tj'
  , to: 'tj@learnboost.com'
  , template: 'welcome-email'
}).save( function(err){
   if( !err ) console.log( job.id );
});

Job Priority

To specify the priority of a job, simply invoke the priority() method with a number, or priority name, which is mapped to a number.

queue.create('email', {
    title: 'welcome email for tj'
  , to: 'tj@learnboost.com'
  , template: 'welcome-email'
}).priority('high').save();

The default priority map is as follows:

{
    low: 10
  , normal: 0
  , medium: -5
  , high: -10
  , critical: -15
};

Failure Attempts

By default jobs only have one attempt, that is when they fail, they are marked as a failure, and remain that way until you intervene. However, Kue allows you to specify this, which is important for jobs such as transferring an email, which upon failure, may usually retry without issue. To do this invoke the .attempts() method with a number.

 queue.create('email', {
     title: 'welcome email for tj'
   , to: 'tj@learnboost.com'
   , template: 'welcome-email'
 }).priority('high').attempts(5).save();

Failure Backoff

Job retry attempts are done as soon as they fail, with no delay, even if your job had a delay set via Job#delay. If you want to delay job re-attempts upon failures (known as backoff) you can use Job#backoff method in different ways:

    // Honor job's original delay (if set) at each attempt, defaults to fixed backoff
    job.attempts(3).backoff( true )

    // Override delay value, fixed backoff
    job.attempts(3).backoff( {delay: 60*1000, type:'fixed'} )

    // Enable exponential backoff using original delay (if set)
    job.attempts(3).backoff( {type:'exponential'} )

    // Use a function to get a customized next attempt delay value
    job.attempts(3).backoff( function( attempts, delay ){
      //attempts will correspond to the nth attempt failure so it will start with 0
      //delay will be the amount of the last delay, not the initial delay unless attempts === 0
      return my_customized_calculated_delay;
    })

In the last scenario, provided function will be executed (via eval) on each re-attempt to get next attempt delay value, meaning that you can't reference external/context variables within it.

Job TTL

Job producers can set an expiry value for the time their job can live in active state, so that if workers didn't reply in timely fashion, Kue will fail it with TTL exceeded error message preventing that job from being stuck in active state and spoiling concurrency.

queue.create('email', {title: 'email job with TTL'}).ttl(milliseconds).save();

Job Logs

Job-specific logs enable you to expose information to the UI at any point in the job's life-time. To do so simply invoke job.log(), which accepts a message string as well as variable-arguments for sprintf-like support:

job.log('$%d sent to %s', amount, user.name);

or anything else (uses util.inspect() internally):

job.log({key: 'some key', value: 10});
job.log([1,2,3,5,8]);
job.log(10.1);

Job Progress

Job progress is extremely useful for long-running jobs such as video conversion. To update the job's progress simply invoke job.progress(completed, total [, data]):

job.progress(frames, totalFrames);

data can be used to pass extra information about the job. For example a message or an object with some extra contextual data to the current status.

Job Events

Job-specific events are fired on the Job instances via Redis pubsub. The following events are currently supported:

  • enqueue the job is now queued
  • start the job is now running
  • promotion the job is promoted from delayed state to queued
  • progress the job's progress ranging from 0-100
  • failed attempt the job has failed, but has remaining attempts yet
  • failed the job has failed and has no remaining attempts
  • complete the job has completed
  • remove the job has been removed

For example this may look something like the following:

var job = queue.create('video conversion', {
    title: 'converting loki\'s to avi'
  , user: 1
  , frames: 200
});

job.on('complete', function(result){
  console.log('Job completed with data ', result);

}).on('failed attempt', function(errorMessage, doneAttempts){
  console.log('Job failed');

}).on('failed', function(errorMessage){
  console.log('Job failed');

}).on('progress', function(progress, data){
  console.log('\r  job #' + job.id + ' ' + progress + '% complete with data ', data );

});

Note that Job level events are not guaranteed to be received upon process restarts, since restarted node.js process will lose the reference to the specific Job object. If you want a more reliable event handler look for Queue Events.

Note Kue stores job objects in memory until they are complete/failed to be able to emit events on them. If you have a huge concurrency in uncompleted jobs, turn this feature off and use queue level events for better memory scaling.

kue.createQueue({jobEvents: false})

Alternatively, you can use the job level function events to control whether events are fired for a job at the job level.

var job = queue.create('test').events(false).save();

Queue Events

Queue-level events provide access to the job-level events previously mentioned, however scoped to the Queue instance to apply logic at a "global" level. An example of this is removing completed jobs:

queue.on('job enqueue', function(id, type){
  console.log( 'Job %s got queued of type %s', id, type );

}).on('job complete', function(id, result){
  kue.Job.get(id, function(err, job){
    if (err) return;
    job.remove(function(err){
      if (err) throw err;
      console.log('removed completed job #%d', job.id);
    });
  });
});

The events available are the same as mentioned in "Job Events", however prefixed with "job ".

Delayed Jobs

Delayed jobs may be scheduled to be queued for an arbitrary distance in time by invoking the .delay(ms) method, passing the number of milliseconds relative to now. Alternatively, you can pass a JavaScript Date object with a specific time in the future. This automatically flags the Job as "delayed".

var email = queue.create('email', {
    title: 'Account renewal required'
  , to: 'tj@learnboost.com'
  , template: 'renewal-email'
}).delay(milliseconds)
  .priority('high')
  .save();

Kue will check the delayed jobs with a timer, promoting them if the scheduled delay has been exceeded, defaulting to a check of top 1000 jobs every second.

Processing Jobs

Processing jobs is simple with Kue. First create a Queue instance much like we do for creating jobs, providing us access to redis etc, then invoke queue.process() with the associated type. Note that unlike what the name createQueue suggests, it currently returns a singleton Queue instance. So you can configure and use only a single Queue object within your node.js process.

In the following example we pass the callback done to email, When an error occurs we invoke done(err) to tell Kue something happened, otherwise we invoke done() only when the job is complete. If this function responds with an error it will be displayed in the UI and the job will be marked as a failure. The error object passed to done, should be of standard type Error.

var kue = require('kue')
 , queue = kue.createQueue();

queue.process('email', function(job, done){
  email(job.data.to, done);
});

function email(address, done) {
  if(!isValidEmail(address)) {
    //done('invalid to address') is possible but discouraged
    return done(new Error('invalid to address'));
  }
  // email send stuff...
  done();
}

Workers can also pass job result as the second parameter to done done(null,result) to store that in Job.result key. result is also passed through complete event handlers so that job producers can receive it if they like to.

Processing Concurrency

By default a call to queue.process() will only accept one job at a time for processing. For small tasks like sending emails this is not ideal, so we may specify the maximum active jobs for this type by passing a number:

queue.process('email', 20, function(job, done){
  // ...
});

Pause Processing

Workers can temporary pause and resume their activity. It is, after calling pause they will receive no jobs in their process callback until resume is called. pause function gracefully shutdowns this worker, and uses the same internal functionality as shutdown method in Graceful Shutdown.

queue.process('email', function(job, ctx, done){
  ctx.pause( 5000, function(err){
    console.log("Worker is paused... ");
    setTimeout( function(){ ctx.resume(); }, 10000 );
  });
});

Note that the ctx parameter from Kue >=0.9.0 is the second argument of the process callback function and done is idiomatically always the last

Note that pause method signature is changed from Kue >=0.9.0 to move the callback function to the last.

Updating Progress

For a "real" example, let's say we need to compile a PDF from numerous slides with node-canvas. Our job may consist of the following data, note that in general you should not store large data in the job it-self, it's better to store references like ids, pulling them in while processing.

queue.create('slideshow pdf', {
    title: user.name + "'s slideshow"
  , slides: [...] // keys to data stored in redis, mongodb, or some other store
});

We can access this same arbitrary data within a separate process while processing, via the job.data property. In the example we render each slide one-by-one, updating the job's log and progress.

queue.process('slideshow pdf', 5, function(job, done){
  var slides = job.data.slides
    , len = slides.length;

  function next(i) {
    var slide = slides[i]; // pretend we did a query on this slide id ;)
    job.log('rendering %dx%d slide', slide.width, slide.height);
    renderSlide(slide, function(err){
      if (err) return done(err);
      job.progress(i, len, {nextSlide : i == len ? 'itsdone' : i + 1});
      if (i == len) done()
      else next(i + 1);
    });
  }

  next(0);
});

Graceful Shutdown

Queue#shutdown([timeout,] fn) signals all workers to stop processing after their current active job is done. Workers will wait timeout milliseconds for their active job's done to be called or mark the active job failed with shutdown error reason. When all workers tell Kue they are stopped fn is called.

var queue = require('kue').createQueue();

process.once( 'SIGTERM', function ( sig ) {
  queue.shutdown( 5000, function(err) {
    console.log( 'Kue shutdown: ', err||'' );
    process.exit( 0 );
  });
});

Note that shutdown method signature is changed from Kue >=0.9.0 to move the callback function to the last.

Error Handling

All errors either in Redis client library or Queue are emitted to the Queue object. You should bind to error events to prevent uncaught exceptions or debug kue errors.

var queue = require('kue').createQueue();

queue.on( 'error', function( err ) {
  console.log( 'Oops... ', err );
});

Prevent from Stuck Active Jobs

Kue marks a job complete/failed when done is called by your worker, so you should use proper error handling to prevent uncaught exceptions in your worker's code and node.js process exiting before in handle jobs get done. This can be achieved in two ways:

  1. Wrapping your worker's process function in Domains
queue.process('my-error-prone-task', function(job, done){
  var domain = require('domain').create();
  domain.on('error', function(err){
    done(err);
  });
  domain.run(function(){ // your process function
    throw new Error( 'bad things happen' );
    done();
  });
});

Notice - Domains are deprecated from Nodejs with stability 0 and it's not recommended to use.

This is the softest and best solution, however is not built-in with Kue. Please refer to this discussion. You can comment on this feature in the related open Kue issue.

You can also use promises to do something like

queue.process('my-error-prone-task', function(job, done){
  Promise.method( function(){ // your process function
    throw new Error( 'bad things happen' );
  })().nodeify(done)
});

but this won't catch exceptions in your async call stack as domains do.

  1. Binding to uncaughtException and gracefully shutting down the Kue, however this is not a recommended error handling idiom in javascript since you are losing the error context.
process.once( 'uncaughtException', function(err){
  console.error( 'Something bad happened: ', err );
  queue.shutdown( 1000, function(err2){
    console.error( 'Kue shutdown result: ', err2 || 'OK' );
    process.exit( 0 );
  });
});

Unstable Redis connections

Kue currently uses client side job state management and when redis crashes in the middle of that operations, some stuck jobs or index inconsistencies will happen. The consequence is that certain number of jobs will be stuck, and be pulled out by worker only when new jobs are created, if no more new jobs are created, they stuck forever. So we strongly suggest that you run watchdog to fix this issue by calling:

queue.watchStuckJobs(interval)

interval is in milliseconds and defaults to 1000ms

Kue will be refactored to fully atomic job state management from version 1.0 and this will happen by lua scripts and/or BRPOPLPUSH combination. You can read more here and here.

Queue Maintenance

Queue object has two type of methods to tell you about the number of jobs in each state

queue.inactiveCount( function( err, total ) { // others are activeCount, completeCount, failedCount, delayedCount
  if( total > 100000 ) {
    console.log( 'We need some back pressure here' );
  }
});

you can also query on an specific job type:

queue.failedCount( 'my-critical-job', function( err, total ) {
  if( total > 10000 ) {
    console.log( 'This is tOoOo bad' );
  }
});

and iterating over job ids

queue.inactive( function( err, ids ) { // others are active, complete, failed, delayed
  // you may want to fetch each id to get the Job object out of it...
});

however the second one doesn't scale to large deployments, there you can use more specific Job static methods:

kue.Job.rangeByState( 'failed', 0, n, 'asc', function( err, jobs ) {
  // you have an array of maximum n Job objects here
});

or

kue.Job.rangeByType( 'my-job-type', 'failed', 0, n, 'asc', function( err, jobs ) {
  // you have an array of maximum n Job objects here
});

Note that the last two methods are subject to change in later Kue versions.

Programmatic Job Management

If you did none of above in Error Handling section or your process lost active jobs in any way, you can recover from them when your process is restarted. A blind logic would be to re-queue all stuck jobs:

queue.active( function( err, ids ) {
  ids.forEach( function( id ) {
    kue.Job.get( id, function( err, job ) {
      // Your application should check if job is a stuck one
      job.inactive();
    });
  });
});

Note in a clustered deployment your application should be aware not to involve a job that is valid, currently inprocess by other workers.

Job Cleanup

Jobs data and search indexes eat up redis memory space, so you will need some job-keeping process in real world deployments. Your first chance is using automatic job removal on completion.

queue.create( ... ).removeOnComplete( true ).save()

But if you eventually/temporally need completed job data, you can setup an on-demand job removal script like below to remove top n completed jobs:

kue.Job.rangeByState( 'complete', 0, n, 'asc', function( err, jobs ) {
  jobs.forEach( function( job ) {
    job.remove( function(){
      console.log( 'removed ', job.id );
    });
  });
});

Note that you should provide enough time for .remove calls on each job object to complete before your process exits, or job indexes will leak

Redis Connection Settings

By default, Kue will connect to Redis using the client default settings (port defaults to 6379, host defaults to 127.0.0.1, prefix defaults to q). Queue#createQueue(options) accepts redis connection options in options.redis key.

var kue = require('kue');
var q = kue.createQueue({
  prefix: 'q',
  redis: {
    port: 1234,
    host: '10.0.50.20',
    auth: 'password',
    db: 3, // if provided select a non-default redis db
    options: {
      // see https://github.com/mranney/node_redis#rediscreateclient
    }
  }
});

prefix controls the key names used in Redis. By default, this is simply q. Prefix generally shouldn't be changed unless you need to use one Redis instance for multiple apps. It can also be useful for providing an isolated testbed across your main application.

You can also specify the connection information as a URL string.

var q = kue.createQueue({
  redis: 'redis://example.com:1234?redis_option=value&redis_option=value'
});

Connecting using Unix Domain Sockets

Since node_redis supports Unix Domain Sockets, you can also tell Kue to do so. See unix-domain-socket for your redis server configuration.

var kue = require('kue');
var q = kue.createQueue({
  prefix: 'q',
  redis: {
    socket: '/data/sockets/redis.sock',
    auth: 'password',
    options: {
      // see https://github.com/mranney/node_redis#rediscreateclient
    }
  }
});

Replacing Redis Client Module

Any node.js redis client library that conforms (or when adapted) to node_redis API can be injected into Kue. You should only provide a createClientFactory function as a redis connection factory instead of providing node_redis connection options.

Below is a sample code to enable redis-sentinel to connect to Redis Sentinel for automatic master/slave failover.

var kue = require('kue');
var Sentinel = require('redis-sentinel');
var endpoints = [
  {host: '192.168.1.10', port: 6379},
  {host: '192.168.1.11', port: 6379}
];
var opts = options || {}; // Standard node_redis client options
var masterName = 'mymaster';
var sentinel = Sentinel.Sentinel(endpoints);

var q = kue.createQueue({
   redis: {
      createClientFactory: function(){
         return sentinel.createClient(masterName, opts);
      }
   }
});

Note that all <0.8.x client codes should be refactored to pass redis options to Queue#createQueue instead of monkey patched style overriding of redis#createClient or they will be broken from Kue 0.8.x.

Using ioredis client with cluster support


var Redis = require('ioredis');
var kue = require('kue');

// using https://github.com/72squared/vagrant-redis-cluster

var queue = kue.createQueue({
    redis: {
      createClientFactory: function () {
        return new Redis.Cluster([{
          port: 7000
        }, {
          port: 7001
        }]);
      }
    }
  });

User-Interface

The UI is a small Express application. A script is provided in bin/ for running the interface as a standalone application with default settings. You may pass in options for the port, redis-url, and prefix. For example:

node_modules/kue/bin/kue-dashboard -p 3050 -r redis://127.0.0.1:3000 -q prefix

You can fire it up from within another application too:

var kue = require('kue');
kue.createQueue(...);
kue.app.listen(3000);

The title defaults to "Kue", to alter this invoke:

kue.app.set('title', 'My Application');

Note that if you are using non-default Kue options, kue.createQueue(...) must be called before accessing kue.app.

Third-party interfaces

You can also use Kue-UI web interface contributed by Arnaud Bénard

JSON API

Along with the UI Kue also exposes a JSON API, which is utilized by the UI.

GET /job/search?q=

Query jobs, for example "GET /job/search?q=avi video":

["5", "7", "10"]

By default kue indexes the whole Job data object for searching, but this can be customized via calling Job#searchKeys to tell kue which keys on Job data to create index for:

var kue = require('kue');
queue = kue.createQueue();
queue.create('email', {
    title: 'welcome email for tj'
  , to: 'tj@learnboost.com'
  , template: 'welcome-email'
}).searchKeys( ['to', 'title'] ).save();

Search feature is turned off by default from Kue >=0.9.0. Read more about this here. You should enable search indexes and add reds in your dependencies if you need to:

var kue = require('kue');
q = kue.createQueue({
    disableSearch: false
});
npm install reds --save

GET /stats

Currently responds with state counts, and worker activity time in milliseconds:

{"inactiveCount":4,"completeCount":69,"activeCount":2,"failedCount":0,"workTime":20892}

GET /job/:id

Get a job by :id:

{"id":"3","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":"100","state":"complete","attempts":null,"created_at":"1309973155248","updated_at":"1309973155248","duration":"15002"}

GET /job/:id/log

Get job :id's log:

['foo', 'bar', 'baz']

GET /jobs/:from..:to/:order?

Get jobs with the specified range :from to :to, for example "/jobs/0..2", where :order may be "asc" or "desc":

[{"id":"12","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309973299293","updated_at":"1309973299293"},{"id":"130","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309975157291","updated_at":"1309975157291"}]

GET /jobs/:state/:from..:to/:order?

Same as above, restricting by :state which is one of:

- active
- inactive
- failed
- complete

GET /jobs/:type/:state/:from..:to/:order?

Same as above, however restricted to :type and :state.

DELETE /job/:id

Delete job :id:

$ curl -X DELETE http://local:3000/job/2
{"message":"job 2 removed"}

POST /job

Create a job:

$ curl -H "Content-Type: application/json" -X POST -d \
    '{
       "type": "email",
       "data": {
         "title": "welcome email for tj",
         "to": "tj@learnboost.com",
         "template": "welcome-email"
       },
       "options" : {
         "attempts": 5,
         "priority": "high"
       }
     }' http://localhost:3000/job
{"message": "job created", "id": 3}

You can create multiple jobs at once by passing an array. In this case, the response will be an array too, preserving the order:

$ curl -H "Content-Type: application/json" -X POST -d \
    '[{
       "type": "email",
       "data": {
         "title": "welcome email for tj",
         "to": "tj@learnboost.com",
         "template": "welcome-email"
       },
       "options" : {
         "attempts": 5,
         "priority": "high"
       }
     },
     {
       "type": "email",
       "data": {
         "title": "followup email for tj",
         "to": "tj@learnboost.com",
         "template": "followup-email"
       },
       "options" : {
         "delay": 86400,
         "attempts": 5,
         "priority": "high"
       }
     }]' http://localhost:3000/job
[
  {"message": "job created", "id": 4},
  {"message": "job created", "id": 5}
]

Note: when inserting multiple jobs in bulk, if one insertion fails Kue will keep processing the remaining jobs in order. The response array will contain the ids of the jobs added successfully, and any failed element will be an object describing the error: {"error": "error reason"}.

Parallel Processing With Cluster

The example below shows how you may use Cluster to spread the job processing load across CPUs. Please see Cluster module's documentation for more detailed examples on using it.

When cluster .isMaster the file is being executed in context of the master process, in which case you may perform tasks that you only want once, such as starting the web app bundled with Kue. The logic in the else block is executed per worker.

var kue = require('kue')
  , cluster = require('cluster')
  , queue = kue.createQueue();

var clusterWorkerSize = require('os').cpus().length;

if (cluster.isMaster) {
  kue.app.listen(3000);
  for (var i = 0; i < clusterWorkerSize; i++) {
    cluster.fork();
  }
} else {
  queue.process('email', 10, function(job, done){
    var pending = 5
      , total = pending;

    var interval = setInterval(function(){
      job.log('sending!');
      job.progress(total - pending, total);
      --pending || done();
      pending || clearInterval(interval);
    }, 1000);
  });
}

This will create an email job processor (worker) per each of your machine CPU cores, with each you can handle 10 concurrent email jobs, leading to total 10 * N concurrent email jobs processed in your N core machine.

Now when you visit Kue's UI in the browser you'll see that jobs are being processed roughly N times faster! (if you have N cores).

Securing Kue

Through the use of app mounting you may customize the web application, enabling TLS, or adding additional middleware like basic-auth-connect.

$ npm install --save basic-auth-connect
var basicAuth = require('basic-auth-connect');
var app = express.createServer({ ... tls options ... });
app.use(basicAuth('foo', 'bar'));
app.use(kue.app);
app.listen(3000);

Testing

Enable test mode to push all jobs into a jobs array. Make assertions against the jobs in that array to ensure code under test is correctly enqueuing jobs.

queue = require('kue').createQueue();

before(function() {
  queue.testMode.enter();
});

afterEach(function() {
  queue.testMode.clear();
});

after(function() {
  queue.testMode.exit()
});

it('does something cool', function() {
  queue.createJob('myJob', { foo: 'bar' }).save();
  queue.createJob('anotherJob', { baz: 'bip' }).save();
  expect(queue.testMode.jobs.length).to.equal(2);
  expect(queue.testMode.jobs[0].type).to.equal('myJob');
  expect(queue.testMode.jobs[0].data).to.eql({ foo: 'bar' });
});

IMPORTANT: By default jobs aren't processed when created during test mode. You can enable job processing by passing true to testMode.enter

before(function() {
  queue.testMode.enter(true);
});

Screencasts

Contributing

We love contributions!

When contributing, follow the simple rules:

  • Don't violate DRY principles.
  • Boy Scout Rule needs to have been applied.
  • Your code should look like all the other code – this project should look like it was written by one person, always.
  • If you want to propose something – just create an issue and describe your question with as much description as you can.
  • If you think you have some general improvement, consider creating a pull request with it.
  • If you add new code, it should be covered by tests. No tests – no code.
  • If you add a new feature, don't forget to update the documentation for it.
  • If you find a bug (or at least you think it is a bug), create an issue with the library version and test case that we can run and see what are you talking about, or at least full steps by which we can reproduce it.

License

(The MIT License)

Copyright (c) 2011 LearnBoost <tj@learnboost.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.