'How do I get my Node.js app which is clustered to run a task only once?

I am using a cluster for my Node.js app. See: https://nodejs.org/api/cluster.html

This has been very useful for many reasons, but now I face a challenge. I want to add a feature to my app which sends a HTTP request to another server, and then gets the response, extracts the data and then saves it in a MySQL database.

I am facing an issue where this feature is inserting duplicates into my database because it is running the HTTP request multiple times (one for each worker on my cluster).

How can I run this process only once when I have 4 workers in my cluster??



Solution 1:[1]

var events = require("events");
var emitter = new events.EventEmitter();
var author = "Slim Shady";
var title = "The real Slim Shady";

//an event listener
emitter.once("addAuthorTitle", function(author, title) {
  console.log("Added Author and Title " + author + " - " + title);
});
//add record to db
// then emit an event
emitter.emit("addAuthorTitle", author, title);
emitter.emit("addAuthorTitle", author, title);

even though it would emit 4 times due to cluster but the function will be executed only once

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddharth