How to create critical section in nodejs multi-instance application in Kubernetes?

2/2/2022

I have a scenarios where an interval is running in nodejs for sending period mailers. Now this MEAN stack application has multiple instances in a Kubernetes deployment. What's happening is for all instances interval is running and same mailer is triggered for all the instances. I want that only single instance should trigger the mailer at a time. How to go about this? Never faced this scenario of multi-instance deployment of an application.

-- Himanshu Neo Garg
critical-section
kubernetes
mean-stack
node.js

1 Answer

2/2/2022

It would be good to run this periodic task as kubernetes cronjob. This may require you to refactor your application.

One possible solution could be to collect information where and what to sent into a message queue or database. For example, rabbitmq, redis or sql. Then periodically, the cronjob can send out all the emails and mark them as send or remove them from the to sent queue/database/collection.

-- The Fool
Source: StackOverflow