Bull

Premium Queue package for handling distributed jobs and messages in NodeJS.

README





The fastest, most reliable, Redis-based queue for Node.

    Carefully written for rock solid stability and atomicity.


Sponsors · Features · UIs · Install · Quick Guide · Documentation

Check the new Guide!


Follow @manast for Bull news and updates!



BullMQ 4 Beta


If you want to start using the next major version of Bull you are welcome to the new repo here


Sponsors


If you find Bull valuable, please consider sponsoring its development by using the Taskforce front-end   [Taskforce.sh, Inc](https://taskforce.sh).

Besides helping Bull's development, you will also benefit from a constantly-improving UI for managing all of your queues and jobs.


Features


- [x] Minimal CPU usage due to a polling-free design.
- [x] Robust design based on Redis.
- [x] Delayed jobs.
- [x] Schedule and repeat jobs according to a cron specification.
- [x] Rate limiter for jobs.
- [x] Retries.
- [x] Priority.
- [x] Concurrency.
- [x] Pause/resume—globally or locally.
- [x] Multiple job types per queue.
- [x] Threaded (sandboxed) processing functions.
- [x] Automatic recovery from process crashes.

And coming up on the roadmap...

- [ ] Job completion acknowledgement.
- [ ] Parent-child jobs relationships.


UIs


There are a few third-party UIs that you can use for monitoring:

Bull v3


Bull <= v2



Monitoring & Alerting


- With Prometheus Bull Queue Exporter


Feature Comparison


Since there are a few job queue solutions, here is a table comparing them:

| Feature         | Bull          | Kue   | Bee | Agenda |
| :-------------  |:-------------:|:-----:|:---:|:------:|
| Backend         | redis         | redis |redis| mongo  |
| Priorities      | ✓             |  ✓    |     |   ✓    |
| Concurrency     | ✓             |  ✓    |  ✓  |   ✓    |
| Delayed jobs    | ✓             |  ✓    |     |   ✓    |
| Global events   | ✓             |  ✓    |     |        |
| Rate Limiter    | ✓             |       |     |        |
| Pause/Resume    | ✓             |  ✓    |     |        |
| Sandboxed worker| ✓             |       |     |        |
| Repeatable jobs | ✓             |       |     |   ✓    |
| Atomic ops      | ✓             |       |  ✓  |        |
| Persistence     | ✓             |   ✓   |  ✓  |   ✓    |
| UI              | ✓             |   ✓   |     |   ✓    |
| Optimized for   | Jobs / Messages | Jobs | Messages | Jobs |


Install


  1. ``` sh
  2. npm install bull --save
  3. ```
or

  1. ``` sh
  2. yarn add bull
  3. ```

_Requirements: Bull requires a Redis version greater than or equal to 2.8.18._


Typescript Definitions


  1. ``` sh
  2. npm install @types/bull --save-dev
  3. ```
  1. ``` sh
  2. yarn add --dev @types/bull
  3. ```

Definitions are currently maintained in the DefinitelyTyped repo.


Contributing


We welcome all types of contributions, either code fixes, new features or doc improvements.
Code formatting is enforced by prettier
For commits please follow conventional commits convention
All code must pass lint rules and test suites before it can be merged into develop.


Quick Guide


Basic Usage

  1. ``` js
  2. var Queue = require('bull');

  3. var videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379');
  4. var audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1', password: 'foobared'}}); // Specify Redis connection using object
  5. var imageQueue = new Queue('image transcoding');
  6. var pdfQueue = new Queue('pdf transcoding');

  7. videoQueue.process(function(job, done){

  8.   // job.data contains the custom data passed when the job was created
  9.   // job.id contains id of this job.

  10.   // transcode video asynchronously and report progress
  11.   job.progress(42);

  12.   // call done when finished
  13.   done();

  14.   // or give a error if error
  15.   done(new Error('error transcoding'));

  16.   // or pass it a result
  17.   done(null, { framerate: 29.5 /* etc... */ });

  18.   // If the job throws an unhandled exception it is also handled correctly
  19.   throw new Error('some unexpected error');
  20. });

  21. audioQueue.process(function(job, done){
  22.   // transcode audio asynchronously and report progress
  23.   job.progress(42);

  24.   // call done when finished
  25.   done();

  26.   // or give a error if error
  27.   done(new Error('error transcoding'));

  28.   // or pass it a result
  29.   done(null, { samplerate: 48000 /* etc... */ });

  30.   // If the job throws an unhandled exception it is also handled correctly
  31.   throw new Error('some unexpected error');
  32. });

  33. imageQueue.process(function(job, done){
  34.   // transcode image asynchronously and report progress
  35.   job.progress(42);

  36.   // call done when finished
  37.   done();

  38.   // or give a error if error
  39.   done(new Error('error transcoding'));

  40.   // or pass it a result
  41.   done(null, { width: 1280, height: 720 /* etc... */ });

  42.   // If the job throws an unhandled exception it is also handled correctly
  43.   throw new Error('some unexpected error');
  44. });

  45. pdfQueue.process(function(job){
  46.   // Processors can also return promises instead of using the done callback
  47.   return pdfAsyncProcessor();
  48. });

  49. videoQueue.add({video: 'http://example.com/video1.mov'});
  50. audioQueue.add({audio: 'http://example.com/audio1.mp3'});
  51. imageQueue.add({image: 'http://example.com/image1.tiff'});
  52. ```

Using promises


Alternatively, you can use return promises instead of using the done callback:

  1. ``` js
  2. videoQueue.process(function(job){ // don't forget to remove the done callback!
  3.   // Simply return a promise
  4.   return fetchVideo(job.data.url).then(transcodeVideo);

  5.   // Handles promise rejection
  6.   return Promise.reject(new Error('error transcoding'));

  7.   // Passes the value the promise is resolved with to the "completed" event
  8.   return Promise.resolve({ framerate: 29.5 /* etc... */ });

  9.   // If the job throws an unhandled exception it is also handled correctly
  10.   throw new Error('some unexpected error');
  11.   // same as
  12.   return Promise.reject(new Error('some unexpected error'));
  13. });
  14. ```

Separate processes


The process function can also be run in a separate process. This has several advantages:
- The process is sandboxed so if it crashes it does not affect the worker.
- You can run blocking code without affecting the queue (jobs will not stall).
- Much better utilization of multi-core CPUs.
- Less connections to redis.

In order to use this feature just create a separate file with the processor:
  1. ``` js
  2. // processor.js
  3. module.exports = function(job){
  4.   // Do some heavy work

  5.   return Promise.resolve(result);
  6. }
  7. ```

And define the processor like this:

  1. ``` js
  2. // Single process:
  3. queue.process('/path/to/my/processor.js');

  4. // You can use concurrency as well:
  5. queue.process(5, '/path/to/my/processor.js');

  6. // and named processors:
  7. queue.process('my processor', 5, '/path/to/my/processor.js');
  8. ```

Repeated jobs


A job can be added to a queue and processed repeatedly according to a cron specification:

  1. ```
  2.   paymentsQueue.process(function(job){
  3.     // Check payments
  4.   });

  5.   // Repeat payment job once every day at 3:15 (am)
  6.   paymentsQueue.add(paymentsData, {repeat: {cron: '15 3 * * *'}});

  7. ```

As a tip, check your expressions here to verify they are correct:

Pause / Resume


A queue can be paused and resumed globally (pass true to pause processing for
just this worker):
  1. ``` js
  2. queue.pause().then(function(){
  3.   // queue is paused now
  4. });

  5. queue.resume().then(function(){
  6.   // queue is resumed now
  7. })
  8. ```

Events


A queue emits some useful events, for example...
  1. ``` js
  2. .on('completed', function(job, result){
  3.   // Job completed with output result!
  4. })
  5. ```

For more information on events, including the full list of events that are fired, check out the Events reference

Queues performance


Queues are cheap, so if you need many of them just create new ones with different
names:
  1. ``` js
  2. var userJohn = new Queue('john');
  3. var userLisa = new Queue('lisa');
  4. .
  5. .
  6. .
  7. ```

However every queue instance will require new redis connections, check how to reuse connections or you can also use named processors to achieve a similar result.

Cluster support


NOTE: From version 3.2.0 and above it is recommended to use threaded processors instead.

Queues are robust and can be run in parallel in several threads or processes
without any risk of hazards or queue corruption. Check this simple example
using cluster to parallelize jobs across processes:
  1. ``` js
  2. var
  3.   Queue = require('bull'),
  4.   cluster = require('cluster');

  5. var numWorkers = 8;
  6. var queue = new Queue("test concurrent queue");

  7. if(cluster.isMaster){
  8.   for (var i = 0; i < numWorkers; i++) {
  9.     cluster.fork();
  10.   }

  11.   cluster.on('online', function(worker) {
  12.     // Lets create a few jobs for the queue workers
  13.     for(var i=0; i<500; i++){
  14.       queue.add({foo: 'bar'});
  15.     };
  16.   });

  17.   cluster.on('exit', function(worker, code, signal) {
  18.     console.log('worker ' + worker.process.pid + ' died');
  19.   });
  20. }else{
  21.   queue.process(function(job, jobDone){
  22.     console.log("Job done by worker", cluster.worker.id, job.id);
  23.     jobDone();
  24.   });
  25. }
  26. ```



Documentation


For the full documentation, check out the reference and common patterns:

- Guide — Your starting point for developing with Bull.
- Reference — Reference document with all objects and methods available.
- Patterns — a set of examples for common patterns.
- License — the Bull license—it's MIT.

If you see anything that could use more docs, please submit a pull request!




Important Notes


The queue aims for an "at least once" working strategy. This means that in some situations, a job
could be processed more than once. This mostly happens when a worker fails to keep a lock
for a given job during the total duration of the processing.

When a worker is processing a job it will keep the job "locked" so other workers can't process it.

It's important to understand how locking works to prevent your jobs from losing their lock - becoming _stalled_ -
and being restarted as a result. Locking is implemented internally by creating a lock for lockDuration on interval
lockRenewTime (which is usually half lockDuration). If lockDuration elapses before the lock can be renewed,
the job will be considered stalled and is automatically restarted; it will be __double processed__. This can happen when:
1. The Node process running your job processor unexpectedly terminates.
2. Your job processor was too CPU-intensive and stalled the Node event loop, and as a result, Bull couldn't renew the job lock (see #488 for how we might better detect this). You can fix this by breaking your job processor into smaller parts so that no single part can block the Node event loop. Alternatively, you can pass a larger value for the lockDuration setting (with the tradeoff being that it will take longer to recognize a real stalled job).

As such, you should always listen for the stalled event and log this to your error monitoring system, as this means your jobs are likely getting double-processed.

As a safeguard so problematic jobs won't get restarted indefinitely (e.g. if the job processor aways crashes its Node process), jobs will be recovered from a stalled state a maximum of maxStalledCount times (default: 1).