Sub topic 12
Scheduled tasks across multiple instances
This chapter assumes you can write @Scheduled methods, understand how cron and fixed-rate triggers work, and have a Spring Boot service that talks to a relational database. Earlier chapters showed how one application runs a task. Here you will see what happens when you run the same application several times.
The duplicate-execution problem
@Scheduled is a local feature. Each JVM that starts your application creates its own scheduler, registers every annotated method, and fires it on its own clock. Spring does not coordinate with other copies of the application.
If you deploy three replicas behind a load balancer, a method annotated with @Scheduled(cron = "0 0 2 * * *") runs three times at 02:00. Each instance believes it is the only one.
This causes real damage when the task is not safe to repeat:
- Customers receive the same email several times.
- An invoice run bills the same orders twice.
- Several instances compete to delete or update the same rows, which causes lock waits or deadlocks.
- A job that calls a rate-limited external API uses up the quota several times faster.
Fixed-rate and fixed-delay tasks have the same problem. They are not synchronized across instances either, so the duplicates are spread out over time instead of arriving together.
Decide whether you have a problem
Not every scheduled task needs protection. Ask one question: is it harmful if two instances run this task at the same time, or one right after the other?
- Local housekeeping is usually fine on every instance. Examples are refreshing an in-memory cache, flushing a local buffer, or rotating a local file. Each instance has its own state to maintain.
- Work on shared state needs protection. Examples are sending notifications, processing a shared queue table, generating reports, or cleaning up database rows.
The first thing to do for shared-state tasks is to make them idempotent. An idempotent task gives the same result whether it runs once or twice. For example, "mark orders older than 30 days as archived" is idempotent. "Send a reminder to every customer with an open invoice" is not, unless you record that the reminder was sent. Idempotency is your safety net when a lock fails or a deployment briefly overlaps old and new versions.
Solution 1: run the scheduler on one instance
The simplest approach is to enable the scheduled beans on a single instance. You can use a Spring profile or a property, and deploy that instance as a separate deployment with jobs.enabled=true.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "jobs.enabled", havingValue = "true")
public class BillingJobs {
private static final Logger log = LoggerFactory.getLogger(BillingJobs.class);
@Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin")
public void nightlyBilling() {
log.info("running nightly billing");
}
}Without jobs.enabled=true, the bean is never created, so its schedule is never registered. Set the property to true on one deployment only, for example with the environment variable JOBS_ENABLED=true.
This approach needs no extra dependencies, but it has weaknesses:
- If the job instance goes down, nothing runs until you restart it.
- Someone must remember which deployment owns the jobs.
- Accidentally setting the flag on two deployments brings the duplicates back.
It fits small systems where a missed run is tolerable, or where you already have a clear separation between web and worker deployments.
Solution 2: a distributed lock with ShedLock
ShedLock is a small library that makes sure a scheduled task runs at most once at a time across instances. Before running the method, each instance tries to take a named lock stored in shared storage, such as a database table. The instance that gets the lock runs the task, and the others skip that run.
ShedLock is not a scheduler. Every instance still triggers the method on its own schedule. The lock only decides which instance does the work.
Add the dependencies net.javacrumbs.shedlock:shedlock-spring and net.javacrumbs.shedlock:shedlock-provider-jdbc-template, then create the lock table:
CREATE TABLE shedlock (
name VARCHAR(64) NOT NULL,
lock_until TIMESTAMP(3) NOT NULL,
locked_at TIMESTAMP(3) NOT NULL,
locked_by VARCHAR(255) NOT NULL,
PRIMARY KEY (name)
);Then configure a lock provider:
import javax.sql.DataSource;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
public class ShedLockConfig {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(
JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(dataSource))
.usingDbTime()
.build());
}
}Finally, annotate the task:
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ReportJobs {
@Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin")
@SchedulerLock(name = "nightlyReport", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
public void nightlyReport() {
// generate the report
}
}The lock name identifies the task, so it must be unique per task and identical on every instance.
The two lock durations
lockAtMostForis the longest time the lock is held. If the instance crashes mid-task, the lock stays in the table, and this value lets other instances take over once it expires. Set it longer than the task's worst-case runtime. If it is shorter, the lock can expire while the task is still running, and a second instance starts the same work.lockAtLeastForis the shortest time the lock is held, even if the task finishes early. It protects against small clock differences between instances. Without it, a task that finishes in 200 ms could release its lock, and an instance whose clock runs slightly behind could take the lock and run the task again for the same trigger.
The usingDbTime() option makes the provider use the database clock instead of each application server's clock, which removes most clock-skew problems. Other providers exist for Redis, MongoDB and other stores, so you can pick whatever your application already uses.
Solution 3: Quartz in clustered mode
Quartz is a full scheduling library that stores jobs and triggers in a database. With clustering enabled, several instances share one set of schedules, and the database ensures each firing goes to exactly one instance. Unlike ShedLock, Quartz owns the scheduling itself. It also balances load and recovers a job when the instance running it dies.
In Spring Boot, add spring-boot-starter-quartz and enable the JDBC job store:
spring:
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: always
properties:
org.quartz.jobStore.isClustered: true
org.quartz.scheduler.instanceId: AUTOYou then define jobs as Job classes with JobDetail and Trigger beans instead of @Scheduled. That is more code and more tables, so choose it when you need persistent schedules, misfire handling, or schedules that change at runtime. The last chapter of this tutorial covers when Quartz is the better choice.
Solution 4: move scheduling outside the application
You can also stop scheduling inside the application. The platform fires the work instead.
- Kubernetes CronJob starts a container on a schedule, and the container runs the task and exits. You get one run per trigger, retry policy, and a concurrency policy such as
Forbidto skip a run while the previous one is active. - A cloud scheduler such as Amazon EventBridge Scheduler can call an HTTP endpoint or start a task. If it calls an endpoint behind a load balancer, only one instance receives each call.
This keeps scheduling concerns out of your code, but you now have an extra deployment artifact and a trigger endpoint or command to secure.
Choosing an approach
| Approach | Extra infrastructure | Survives instance failure | Best for |
|---|---|---|---|
| Single scheduler instance | None | No, until restarted | Small systems, clear worker deployment |
| ShedLock | A shared database or store | Yes, after `lockAtMostFor` | Existing `@Scheduled` code that needs at-most-once runs |
| Quartz clustered | Database schema | Yes, with job recovery | Persistent or dynamic schedules, misfire handling |
| Platform scheduler | CronJob or cloud service | Yes, with platform retries | Batch work that suits a separate container |
For most Spring Boot services that already use @Scheduled, ShedLock is the smallest change.
Common mistakes
- Lock names that differ per instance. If the name includes a hostname or random value, every instance gets its own lock and nothing is prevented.
- Putting
@SchedulerLockon a method without@Scheduled. ShedLock's scheduler integration only wraps methods that the Spring scheduler runs, so the lock does nothing when you call the method from other code. - Forgetting
lockAtLeastForon fast tasks. A task that takes milliseconds can run twice for one trigger when instance clocks drift. - Combining ShedLock with
@Asyncon the same method. The lock is released when the scheduler thread hands the work off, not when the real work ends. Apply the lock inside the asynchronous method's own call path, or avoid@Asyncon locked tasks. - Assuming a lock gives exactly-once. It gives at-most-one-at-a-time. If the winning instance crashes halfway, the task is rerun later, so keep it idempotent.
Exercise
Your service runs on four replicas. A @Scheduled(fixedRate = 60000) method sends a "payment overdue" email to every customer whose invoice is late. Customers report getting up to four emails per minute. Name two changes that fix this, and say which property of the task you should also improve.
Show answer
Each replica runs its own scheduler, so all four send the emails. One fix is to run the task on only one instance, for example with @ConditionalOnProperty on the job bean and the flag set on one deployment. Another is to add ShedLock with @SchedulerLock(name = "overdueEmails", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S") so only one instance runs each trigger. You should also make the task idempotent, for example by recording on the invoice that a reminder was sent and skipping invoices already marked. That protects against duplicates when a lock expires or an instance crashes.