Book a 30-min callBook a call

System design: a distributed job scheduler (cron at scale)

How to design a distributed cron: schedule store, schedulers and workers, unique run keys, leases, timing wheels, missed runs, DST, retries and overdue alerts.

A clock face feeding a table of schedules, then a scheduler box, a queue of small blocks and three worker circles.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
16 min read

Questions people ask

How do I stop a cron job from running twice on several servers?

Do not run cron on every server. Have schedulers write a run record keyed by job ID and scheduled time, with a unique index so a second insert for the same slot does nothing, and have workers claim runs under a lease with a fencing token. Make the job idempotent as well, because at-least-once delivery can still repeat it.

Should missed runs execute after an outage?

It depends on the job. Catch up when every slot matters, such as per-period aggregates; run once when only the latest state matters, such as a cache refresh; skip after a deadline when a late run is useless, such as a reminder. Kubernetes CronJob expresses the last one with startingDeadlineSeconds.

What happens to a job scheduled at 02:30 on the night clocks change?

On the spring-forward night, 02:30 does not exist in zones that skip that hour; on the fall-back night, 01:30 happens twice. Cronie skips missing times and runs repeated times twice. A distributed scheduler should choose explicitly, for example shifting the run forward past the gap and running only the first of two repeated times.

Is a database poller good enough, or do I need timing wheels?

For most business schedules, with precision in seconds, an indexed query on the next run time is enough and much simpler. Timing wheels, from Varghese and Lauck, earn their place with very many timers or sub-second precision, usually in memory on top of the database.

Building something like this?