Video in progress
What do you do when an @Scheduled job fires at the same time on all the service's replicas?
@Scheduled runs independently on every instance, so with 3 pods the job runs 3 times. The solutions: a distributed lock (ShedLock), splitting the work by rows with SKIP LOCKED, or moving the job to a separate Kubernetes CronJob.
📖 Answer
The classic case: a daily "remind people whose subscription has expired" job. Locally everything is fine, in prod there are 3 replicas and customers get 3 SMS messages each.
With ShedLock:
@Scheduled(cron = "0 0 9 * * *")
@SchedulerLock(name = "subscriptionReminder",
lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
public void remind() {
reminderService.sendDue();
}
ShedLock atomically updates a lock record in a shared DB table (or in Redis). Whichever pod gets there first runs it, and the others skip this round.
About the parameters:
lockAtMostFor: if the pod dies in the middle of the job, the lock releases itself after this long. Set it larger than the job's longest run time, otherwise a second pod starts it while it is still running.lockAtLeastFor: when clocks differ a little and the job finishes very quickly, this keeps another pod from starting it one more time.
ShedLock gives you "only one runs it", but it doesn't parallelize the work. If the job is big, a different approach is better: each pod takes its share with SELECT ... FOR UPDATE SKIP LOCKED LIMIT 100 and works on it. That way all the replicas do useful work.
And still, make the work idempotent. Lock expiry and clock skew can lead to two runs, so keep the "SMS sent" flag at the row level.
Sign up to mark studied questions and save your progress.