I have what I believe is a fairly common situation these days: I have a webapp that scales horizontally across multiple machines in order to serve greater load. This particular application is written in Java.
On this same webapp, I find that I have a need to run a background process in this webapp periodically. However, this process executes requests against another service, and I don't believe it would be safe to have multiple invocations of this process going at once.
It would be easiest to just get a new machine that runs these background processes by itself. However, company policies make it difficult to get new machines, so I'm trying to investigate other options in case this isn't possible. This means I'm trying to figure out how to make just one machine at a time run this background process at once. I've thought about some of the following ways:
- Figure out how to make one machine the "leader" and be the only one to execute these periodic background tasks. This is complicated by the fact that I'm running on an AWS auto-scale group, so this leader could be killed at any time, so I'm stuck with needing to do leader election on my own.
- Establishing a mutex of some kind that each instance must grab before it executes. I've thought about using an in-memory data grid like Hazelcast for this, but that seems a bit heavyweight to set up and use just for this.
What are some good ways of achieving my goal of running this background process in my webapp and making sure it only runs once?