Video in progress

What happens to this `@Scheduled` method when the service runs on 3 instances, and how do you fix it?

@Scheduled(cron = "0 0 9 * * *")
public void sendDailyDigest() {
    for (User u : userRepo.findAllSubscribed()) {
        mailService.sendDigest(u);
    }
}

Each instance runs its own scheduler, so the job runs 3 times — customers get 3 emails. The fix is a distributed lock (for example, ShedLock with a DB table), moving the job to a single dedicated worker, or making the work idempotent.

📖 Answer

On the local machine everything was fine — one instance. On prod there are 3 pods, each with Spring's own scheduler, and at 09:00 in the morning all three fire.

The most common fix is ShedLock:

@Scheduled(cron = "0 0 9 * * *")
@SchedulerLock(name = "dailyDigest", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
public void sendDailyDigest() { ... }

The lock is stored in a DB table (shedlock) or in Redis. The instance that grabs it first runs, and the others skip. lockAtLeastFor is there so that pods whose clocks differ slightly don't run the job twice in a row. lockAtMostFor is there so that if the instance dies, the lock doesn't stay forever.

This code has other problems too:

  • findAllSubscribed() loads a million users into one list — it needs paged reads;
  • emails are sent synchronously, one by one — the job runs for hours, and if a pod restarts halfway through, you don't know who has been sent to;
  • if you restart it, it sends to everyone again.

A more reliable version: the job only inserts a record into a digest_tasks table (user_id, date, unique) or drops a message on a queue, and workers send the emails, each marking "sent" by (user_id, date). That solves both the duplicates and the half-finished work.