Video in progress

You have 6 pods in a cluster, but the daily settlement job must run in only one place. How do you build a "distributed singleton", and what are the risks?

The options: a lock in the database (ShedLock), leader election (Kubernetes Lease, ZooKeeper), or moving the job to a separate scheduler. The main risk is the lock expiring and two instances running at once, so the job itself must be idempotent too.

📖 Answer

A plain @Scheduled runs on every pod, and the settlement runs 6 times. Many teams find this out on prod after the first scale-out, when twice as many SMS messages go out in the morning.

ShedLock is the most widely used solution:

@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "dailySettlement", lockAtMostFor = "PT2H", lockAtLeastFor = "PT5M")
public void settle() { ... }

The lock is a single row in the database. lockAtMostFor means that if the pod dies, the lock is released after that time. And here is the trap: if the job runs longer than 2 hours, the lock is released and another pod starts too. ShedLock's lock gives no "fencing": the old owner doesn't know it is still running.

Leader election (Kubernetes Lease, Spring Integration's LockRegistryLeaderInitiator, ZooKeeper/Curator): one pod becomes the leader and runs the jobs as long as it stays leader. It's better for long-running processes, but with a GC pause or a network partition you can end up with two leaders. The protection is a fencing token: each new leader gets an increasing number, and writes to the database check where epoch <= ?.

A separate scheduler: a Kubernetes CronJob (concurrencyPolicy: Forbid) or Quartz in clustered mode. Separating the job from the web pods also protects their memory and CPU.

Whichever option I choose, I require the following:

  • the job is idempotent: the daily settlement is protected by a unique constraint on settlement_date, so a second run breaks nothing;
  • the job is split into parts and each part records its own state, so if it crashes in the middle, it continues from where it stopped, not from the start;
  • monitoring checks not "did the job run" but "is there a result": if there is no settlement row for today at 6 a.m., alert.

In fact, turning the requirement "only one instance" into "the result is the same even if it runs several times" is the most reliable solution. The lock is an optimization; idempotency is the guarantee.