Maybe it’s cool you use the Firebase Queue to perform this kind of complex task. I was writing about it today for my team. Just connect:
Firebase Queue is a Firebase module that allows us to create four elements that solve the scheduling of our platform in a way that Plone developers couldn’t even imagine in their wettest dreams. A "queue", or queue, is a place in the database where you play tasks to be completed. The life cycle of each Queue is based on four main concepts: task, worker, spec and job.
Each "task" is a task represented as an object in the database and it can be processed by a worker.
"Workers", or workers, are processes that are waiting for tasks that are added to the database. With each task added, the Workers observe the spec of the task and decide whether or not they will attempt to process it. The first worker who starts working steals the task for himself and no other worker can interfere with it until it is complete or returns an error.
The "spec" is a definition of the things the task does in relation to other tasks. You can define links between tasks as "when you complete task X, start task Y" or "start task X with these parameters here".
"Job" is a set of specs that define a series of operations to be executed in order.
To know how to implement all this, just read the official guide at https://github.com/firebase/firebase-queue/blob/master/docs/guide.md