Sobes.tech
Senior

If we have multiple instances of the application, how can we ensure that the same operation from the scheduler is not processed simultaneously by multiple instances?

sobes.tech AI

Answer from AI

To prevent multiple instances of an application from processing the same operation simultaneously from a scheduler, distributed locking mechanisms are usually used.

Main approaches:

  • Using a database: create a lock table where an operation is marked as "locked" by one of the instances. Before executing the operation, the instance attempts to establish a lock (for example, via a unique key or flag). If the lock already exists — the operation is not performed.

  • Using Redis with lock support (e.g., Redlock): the instance tries to acquire a lock with TTL, and if successful — performs the task.

  • Using specialized systems for distributed locking, such as ZooKeeper or Consul.

Example with Redis (Java, using Redisson):

RLock lock = redisson.getLock("myScheduledTaskLock");
if(lock.tryLock(0, 10, TimeUnit.SECONDS)) {
    try {
        // perform the task
    } finally {
        lock.unlock();
    }
}

Thus, only one instance can acquire the lock and perform the operation at a given time.