Finding what’s due, every second
Illustrative exampleNumbers here are illustrative: round figures to reason with, not measurements.
Reading every job each second to find the few thousand that are due is far too slow, and gets slower with every job; timers held only in a scheduler’s memory vanish when it restarts. Store next_run_at on each job, in UTC, with an index on it. Every second each scheduler reads, from the shards it covers, the jobs due in the next few seconds, in batches: a few thousand rows, however many jobs are stored.
Time buckets work too: a partition per minute and shard in Cassandra or DynamoDB, read one minute at a time and split by shard so the midnight minute isn’t one hot partition. An in-memory timing wheel or Redis sorted set is fine as a speed-up if it is rebuilt from the database after a restart.
- A customer creates a job due Tuesday at 14:00:00: it is a row with that next_run_at, and nothing else happens until then.
- At 14:00:00 the scheduler’s read of the next few seconds returns it with the others due.
- A scheduler restarts at 13:59:30; nothing lived only in memory, so the same read finds the job.
Diagram as text
Components: Jobs API (API gateway); Shard A: index on next_run_at (SQL DB); Shard B: index on next_run_at (SQL DB); Scheduler 1 (Service); Scheduler 2 (Service). Connections: Jobs API → Shard A: index on next_run_at (job due Tue 14:00); Jobs API → Shard B: index on next_run_at (other jobs); Scheduler 1 → Shard A: index on next_run_at (due in the next 5 s); Scheduler 2 → Shard B: index on next_run_at (due in the next 5 s).
Read:Learn: Indexes and search fundamentalsLearn: Data model design
Keep reading+1 min
An index or buckets
An index on next_run_at in a sharded relational database is simplest when writes are modest, as here. Buckets suit a wide-column store and very high write rates, but a bucket per minute alone puts the whole midnight minute in one partition, so add a shard number to the key.
Check yourself
Why isn’t a timer per job in the scheduler’s memory enough, even on a big machine?
Show answerHide answer