Create complex job dependencies with parent-child relationships
BullMQ supports parent-child relationships between jobs. The basic idea is that a parent job will not be moved to the wait status (i.e. where it could be picked up by a worker) until all its children jobs have been processed successfully. Apart from that, a parent or a child job are no different from regular jobs.This functionality enables the creation of flows where jobs are the node of trees of arbitrary depth.
Flows are added to a queue using the FlowProducer class.
import { FlowProducer } from 'bullmq';// A FlowProducer constructor takes an optional "connection"// object otherwise it connects to a local redis instance.const flowProducer = new FlowProducer();const flow = await flowProducer.add({ name: 'renovate-interior', queueName: 'renovate', children: [ { name: 'paint', data: { place: 'ceiling' }, queueName: 'steps' }, { name: 'paint', data: { place: 'walls' }, queueName: 'steps' }, { name: 'fix', data: { place: 'floor' }, queueName: 'steps' }, ],});
The above code will atomically add 4 jobs: one to the “renovate” queue, and 3 to the “steps” queue. When the 3 jobs in the “steps” queue are completed, the parent job in the “renovate” queue will be processed as a regular job.
Note that the parent queue does not need to be the same queue as the one used for the children.
If a jobId option is provided, make sure that it does not contain a colon : as this is considered a separator.
When the parent job is processed, it is possible to access the results generated by its child jobs. For example, let’s assume the following worker for the child jobs:
import { Worker } from 'bullmq';const stepsWorker = new Worker('steps', async job => { await performStep(job.data); if (job.name === 'paint') { return 2500; } else if (job.name === 'fix') { return 1750; }});
We can implement a parent worker that sums the costs of the children’s jobs using the getChildrenValues method:
Queue options are defined in the context of their instances. You should provide your configurations in the second parameter to avoid unexpected behaviors.
BullMQ provides seamless removal functionality for jobs that are part of a flow.When removing a job that is part of a flow, there are several important considerations:
If a parent job is removed, all its children will also be removed.
If a child job is removed, its parent dependency to said child is also removed, and if the child was the last child in the dependencies list, the parent job will be completed.
Since a job can be both a parent and a child in a large flow, both 1 and 2 will occur if removing such a job.
If any of the jobs that would be removed happen to be locked, none of the jobs will be removed, and an exception will be thrown.
Removing a job can be done using either the Job or the Queue class: