Share Redis connections across multiple queues to reduce connection count
A standard queue requires 3 connections to the Redis server. In some situations you might want to re-use connections—for example on Heroku where the connection count is restricted.You can do this with the createClient option in the Queue constructor.
bclient connections cannot be re-used, so you should return a new connection each time this is called.
Client and subscriber connections can be shared and will not be closed when the queue is closed
When shutting down the process, first close the queues, then the shared connections (if they are shared)
If you are not sharing connections but still using createClient for custom connection logic, you may need to keep a list of all connections to manually close them later for graceful shutdown
Do not set a keyPrefix on the connection you create—use Bull’s built-in prefix feature if you need a key prefix
const { REDIS_URL } = process.env;const Redis = require('ioredis');let client;let subscriber;const opts = { // redisOpts here will contain at least a property of connectionName which will identify the queue based on its name createClient: function (type, redisOpts) { switch (type) { case 'client': if (!client) { client = new Redis(REDIS_URL, redisOpts); } return client; case 'subscriber': if (!subscriber) { subscriber = new Redis(REDIS_URL, redisOpts); } return subscriber; case 'bclient': return new Redis(REDIS_URL, redisOpts); default: throw new Error('Unexpected connection type: ' + type); } }}const queueFoo = new Queue('foobar', opts);const queueQux = new Queue('quxbaz', opts);
// Shutdown sequenceawait queueFoo.close();await queueQux.close();// Now close shared connectionsawait client.quit();await subscriber.quit();
This pattern is especially useful when working with platforms that have connection limits, such as Heroku or when using Redis services with connection-based pricing.