I am adding tasks as Docs in a Firestore collection. On the Backend, I have multiple NodeJs stateless instances that process these tasks. All the instances are listening to realtime change in the collection
firestore().collection('Tasks').onSnapshot(startTask, one rror);
In this case all the NodeJs instances will be notified when a Task is added. How can I ensure that only one of them process the task? I though about using firebase-queue but it seems that the project is obsolete. Is there a way to do that without extra modules? Running the NodeJs as Firebase function is not an option for me.
CodePudding user response:
One possible solution would be to add a "treated" flag to the Firestore document through a Transaction.
A given Node.js instance should only process this Task if it is not flagged as treated (e.g. you check at the beginning of the transaction if the field treated
is set to true
and if it is the case you throw an error, see the examples). And after having successfully processed it the Node.js instance shall flag the doc as treated (within the same Transaction of course).
Since you use a Node.js server (i.e. you use the Node.js server client library) the transaction places a lock on the Task document it is reading and therefore the other instances cannot modify the document. This way you are sure it will be treated only once.
More details on data contention in the server client libraries here in the doc.