How do I stop a single function from running on multiple meteor instances?

Hi lovely folks of the Meteor community!

I’m running into an issue where because of multiple instances of meteor in galaxy, it’s running a function multiple times instead of just once.

I have a socket which is listening to outside communication and when this communication hits my server the responses are being sent multiple times instead of once.

I am happy with the load balancing and need multiple servers, however - I only want this particular function to run once instead of on multiple services. Is there a meteor function that will allow this to happen or is there any other way to achieve this goal?

Appreciate any help!

There is no built in feature for this. One way to do it is to have a lock collection, with a unique index on some parameters of your function. You try to insert into this collection when you receive the message, and if it completes, you continue, if it throws an error, you don’t.

For example, create a “locks” collection.
Add an index

    messageId: 1,
  }, { unique: true });

In the function that handles the message:

try {
  Locks.insert({ messgageId: idOfMessage });
} catch (e) {
  // Already ran the message function


Can you describe the function you need to run in more detail, such as how it’s triggered?

You can use a cron tool that automatically handles this. I use meteor-synced-cron, but there are plenty others.

Yeah, locking comes up a LOT.

It’s super scary @pagesrichie, especially since you have something already working. You’re technically reinventing a message queue, because you are calling a function on data that you need to temporarily store somewhere, and it should be done once and in order.

My recommendation is, if you already have the data coming into the server coming in, it’s just coming in multiple times, consider inserting the data once into a dedicated collection whose document ID corresponds to the ID of the message you’re receiving from the outside world. Then you only get one document, once, regardless of how many servers try to add it. Then whoever succeeds at adding this document tries running the function and marks that document as processed.

Then, you have something that will fit all the needs you don’t even know about.