SteelReed

Search

Search posts, questions…

5. Spring Boot

Distributed job scheduling: Quartz clustering, misfires and splitting big jobs across workers

Quartz's Job, JobDetail, Trigger and JobStore model, @DisallowConcurrentExecution and @PersistJobDataAfterExecution, how a Quartz cluster uses the JDBC JobStore and the QRTZ_LOCKS row lock, misfires and catch-up runs, Spring Boot configuration, and how to turn a two-day job emailing 10 million users into leased chunks processed in parallel.

19 Nov 202610 min readSenior

–

1. The problem

A job emailing 10 million users takes 2 days on one pod (17 ms per email). Turning on a Quartz cluster with 8 pods still takes 2 days: the cluster picks one node to run the job, it doesn't split the work.

2. Key idea

Quartz has four parts: Job (code), JobDetail (name + JobDataMap), Trigger (when to run), JobStore (where it's stored). Unlike @Scheduled, schedules are created at runtime and survive restarts. Each firing creates a new Job instance, so state lives in the JobDataMap, not in fields.

2.1 How does a cluster work?

There's no master. Every node uses the JDBC JobStore on the same database with isClustered=true. Whichever node grabs the TRIGGER_ACCESS row lock in QRTZ_LOCKS (SELECT … FOR UPDATE) takes the trigger. Nodes check in periodically; one silent too long is considered dead, and jobs with requestsRecovery are rerun by another node. So jobs must be idempotent.

A cluster is for fault tolerance and no duplicate runs, not load sharing.

2.2 What about missed runs?

The app is down for 3 hours, the job runs every 5 minutes:

Misfire instruction (cron) Behaviour Fits
FIRE_ONCE_NOW (default) fires 1 catch-up run syncs, cleanups
DO_NOTHING skips missed runs, waits for the next "good morning" messages
IGNORE_MISFIRE_POLICY fires 36 catch-up runs rarely right

Period-based jobs should read the period to process from data ("last day computed"), not from the run time.

2.3 How do you split a big job?

The scheduler only fires a planner job. It splits by user_id range (10,000 users per chunk) into a job_chunk table. Workers on every node claim chunks with FOR UPDATE SKIP LOCKED plus a lease (lease_until). If a worker dies, the lease expires and the chunk is claimed again.

Splitting Use when Don't use when
Chunk table + SKIP LOCKED you have a DB, want progress via SQL millions of chunks, main DB already loaded
One message per chunk (SQS, Kafka) workers scale with the queue you need "stop the whole job", built-in progress

3. In Java

JAVA
@DisallowConcurrentExecution          // per JobKey: runs never overlap, even across nodes
@PersistJobDataAfterExecution         // saves the JobDataMap after each run
public class SyncOrdersJob extends QuartzJobBean {
    private final OrderSyncService sync;
    SyncOrdersJob(OrderSyncService sync) { this.sync = sync; }
 
    @Override
    protected void executeInternal(JobExecutionContext ctx) {
        JobDataMap data = ctx.getJobDetail().getJobDataMap();
        long last = data.getLongValue("lastSyncedId");
        data.put("lastSyncedId", sync.syncAfter(last, 5_000));   // upsert by id: idempotent
    }
}
// JobBuilder.newJob(SyncOrdersJob.class).withIdentity("sync-orders").storeDurably().requestRecovery()
// cronSchedule("0 */5 * * * ?").withMisfireHandlingInstructionFireAndProceed()
// spring.quartz.job-store-type=jdbc, ...jobStore.isClustered=true, ...scheduler.instanceId=AUTO

Quartz cron has seconds first and uses ? in one of the two day fields.

SQL for claiming a leased chunk
SQL
UPDATE job_chunk
SET status = 'RUNNING', owner = :worker, lease_until = now() + interval '5 minutes'
WHERE id = (
    SELECT id FROM job_chunk
    WHERE job_id = :job AND (status = 'PENDING' OR (status = 'RUNNING' AND lease_until < now()))
    ORDER BY id LIMIT 1
    FOR UPDATE SKIP LOCKED
)
RETURNING id, from_user_id, to_user_id;
 
-- Only the lease owner may mark it done
UPDATE job_chunk SET status = 'DONE' WHERE id = :id AND owner = :worker AND status = 'RUNNING';

The owner = :worker condition is fencing: a worker paused by a long GC, returning after losing its lease, can't overwrite. Emails it already sent can't be recalled, so each email stays idempotent on campaign_id + user_id. With a quota of 1,000 emails/s, 10 million emails still take nearly 3 hours: you need a shared rate limiter.

4. Working with AI

Delegate to AI: Quartz JDBC configuration, QRTZ_* table migrations, chunk-claiming worker code.

Check yourself:

  • Every instance pointing at the QRTZ_* tables has isClustered=true.
  • Jobs keep no state in fields; requestsRecovery jobs can safely rerun.
  • @PersistJobDataAfterExecution comes with @DisallowConcurrentExecution.
  • Chunks split by id range, not OFFSET; complete checks owner.

5. Exercises

Exercise 1: Review "now runs in parallel on 8 nodes"

AI writes in the PR: "enabled an 8-node Quartz cluster, the email job now runs in parallel, 8x faster". The job is a QuartzJobBean looping over SELECT * FROM users LIMIT 10000 OFFSET ?. What's wrong, and what do you propose?

Solution to Exercise 1
  • Wrong: a cluster lets only one node take each firing, so it's still sequential, still 2 days.
  • OFFSET slows down and skips or repeats rows when the table changes.
  • Proposal: a planner job creates 1,000 chunks by user_id range; workers on every node claim with SKIP LOCKED + lease; sends are idempotent on campaign_id + user_id; a shared rate limiter follows the email provider's quota.
  • Test: 8 workers, kill one while it holds a chunk; every chunk ends DONE, none completed twice.

Exercise 2: Pick a misfire instruction

The app is down from 01:00 to 04:00. Choose for: (a) order sync every 5 minutes, (b) the "morning newsletter" at 03:00, (c) daily interest at 02:00.

Solution to Exercise 2
  • (a) FIRE_ONCE_NOW: one run at 04:00 picks up all orders since the last mark.
  • (b) DO_NOTHING, or check inside the job: after 07:00, skip.
  • (c) Don't rely on the number of catch-up runs. The job reads "last day interest was computed", computes each day up to yesterday, with a unique key (account_id, date). Then FIRE_ONCE_NOW is enough.

Summary

  • Job, JobDetail, Trigger, JobStore; state lives in the JobDataMap.
  • The cluster uses the QRTZ_LOCKS lock: no duplicate runs, survives dead nodes, doesn't share load.
  • Jobs must be idempotent; node clocks must be in sync.
  • Misfires: choose by the job's nature, read the period to process from data.
  • Big jobs: chunk them, claim with SKIP LOCKED + lease, fence on owner.

Further reading: Cron jobs and @Scheduled.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All Microservices questions →

Loading comments…
Next on the roadmapCleanup cron jobs: batched deletes, archiving and partitions