Skip to content

    System Design

    Background Jobs and Schedulers

    How schedulers fire jobs, what happens to missed and overlapping runs, how to retry safely, and why a job body must be idempotent, with a runnable Spring lab.

    By Published 15 min read

    • system-design
    • background-jobs
    • schedulers
    • spring-scheduling
    • idempotency
    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Message Queues and Pub/Sub

    What you'll learn: By the end of this lesson you will be able to separate a scheduler (which decides when) from a job (which decides what), choose what happens to runs missed while the process was down, choose what a fire does when the previous run is still going, retry a failed run without paying anyone twice, keep two application instances from doing the same work, and read the output of a lab that runs all of this on a manual clock.

    A building has a cleaner booked for 6 p.m. every day. She is ill on Tuesday: does someone clean twice as long on Wednesday, or not at all? On Thursday the job takes three hours, so Friday's 6 p.m. slot finds her still there. And if two managers each booked a cleaner for the same slot, two people clean one floor. The rota is the scheduler and the cleaning is the job. Most scheduling bugs live between the two, and none of them show up when you run the job once on a laptop.

    This is the dedicated treatment of time-triggered work. Message queues cover work triggered by an event, dead-letter queues and retries failed messages, and idempotent and commutative operations why a repeat must be harmless. The blog article Temporal vs Spring Batch argues for a durable-execution engine; this lesson covers the semantics you need whichever tool you pick.

    Verified with the Spring Framework scheduling reference, the Spring Boot task-execution and Quartz pages, the Quartz 2.3.0 documentation, the Kubernetes CronJob page, the ShedLock README and the Java 25 ScheduledExecutorService Javadoc, on 2026-12-01. The lab targets the Java 25 language level, runs on JDK 27 and uses Spring Boot 4.1.2.

    The core idea

    A scheduler only decides when to call your code. What a missed fire means, what an overlapping fire does, whether a failed run repeats and which instance runs are policies you choose, and the job body must be written so that every policy you did not choose still does no harm.

    Three illustrations run through it:

    • Minimal example: a payout job on the cron 0 */10 * * * *, run on a manual clock through a missed window, an overlap, a retry and a two-instance cluster.
    • Realistic example: ShopStream's nightly store payout, in "In practice".
    • Failure example: a rolling deploy kills the 2 a.m. run and 3,100 stores stay unpaid until the next night.

    A job and a scheduler are different things

    A job is a unit of work with a name and an effect: "settle yesterday's store payouts". A scheduler decides when to start it and, unless you give it a store, remembers nothing. Spring's @Scheduled covers the time trigger; an arriving message is a queue consumer. Per the Spring Framework reference, @Scheduled offers fixedDelay ("the period is measured from the completion time of each preceding invocation"), fixedRate ("measured between the successive start times of each invocation"), initialDelay, and cron with a zone. The method returns void and takes no arguments (reactive types are the documented exception). A Spring cron expression has six fields, second first.

    Trigger, scheduler, job body and the guards around itTrigger to Scheduler (fire time); Scheduler to Guards (start?); Guards to Job body (yes); Job body to Data store (writes); Guards to Data store (claims)Trigger: cron, rate, delayTriggercron, rate, delayScheduler: threads in the appSchedulerthreads in theappGuards: lock, run key, claimGuardslock, run key,claimJob body: safe to repeatJob bodysafe to repeatData store: effects, run recordsData storeeffects, runrecordsfire timestart?yeswritesclaims

    Figure 1. Where the decisions live. How to read this: the trigger and scheduler only produce "it is time". Whether a fire becomes a run is decided by guards, and what a run does twice is decided by the body and its data store.

    What Spring's scheduler does and does not give you

    Spring Boot auto-configures a scheduler for @EnableScheduling. Its documentation says the ThreadPoolTaskScheduler "uses one thread by default", so one slow method delays the others on that scheduler (an inference from one thread, not a quotation), and that with virtual threads enabled it is a SimpleAsyncTaskScheduler.

    The Spring reference documents no persistence of past fires and no coordination between instances. Its related warning is "make sure that you are not initializing multiple instances of the same @Scheduled annotation class at runtime, unless you do want to schedule callbacks to each such instance". Read plainly: three copies of the application have three schedulers and each fires, and an in-process schedule has no memory of a fire that happened while it was down. These are consequences of what is described, not quoted guarantees, so test them.

    Quartz is the next step. Spring Boot's Quartz page says "by default, an in-memory JobStore is used" and a JDBC store is selected with spring.quartz.job-store-type=jdbc; jobs are wired as JobDetail and Trigger beans. The Quartz documentation supplies the missing semantics. A misfire is a persistent trigger that "misses" its firing time because the scheduler was shut down or no thread was free, and on start the scheduler updates misfired triggers by each trigger's misfire instruction. @DisallowConcurrentExecution tells Quartz "not to execute multiple instances of a given job definition". Clustering "currently only works with the JDBC-Jobstore", "only one node will fire the job for each firing", and node clocks must be "within a second of each other".

    The lab lists fire times with Spring's real cron parser:

        public List<Instant> firesIn(Instant afterExclusive, Instant untilInclusive) {
            List<Instant> fires = new ArrayList<>();
            ZonedDateTime next = cron.next(afterExclusive.atZone(ZoneOffset.UTC));
            while (next != null && !next.toInstant().isAfter(untilInclusive)) {
                fires.add(next.toInstant());
                next = cron.next(next);
            }
            return fires;
        }

    All other times come from a ManualClock that moves only when the simulation moves it, which makes the output repeatable. The policies are the lab's model, not Spring's or Quartz's scheduler.

    Missed runs

    A fire is missed when its time passes and no run starts: the process was down, a deploy was rolling, every thread was busy. Three policies are common: skip, run once to cover them all, run once per missed fire.

    flowchart TD accTitle: What to do with fires missed while the scheduler was down accDescr: When the scheduler comes back it finds fire times in the past. If the job body reads everything since its last success, skipping or running once is enough because the next run catches up. If the body reads only the window of its own fire time, it needs one run per missed fire. M["Fire times passed while down"] --> Q{"What does one run read?"} Q -->|"everything since the last success"| W["Skip, or run once"] Q -->|"only the window of its own fire time"| A["Run once per missed fire"] W --> N["Next fire catches up by itself"] A --> C["Catch-up runs, in order"]

    Figure 2. Choose the policy from the job body. How to read this: the question is not "catch up or not" but "what does one run read". A watermark body catches up on its own; a window body does not.

    Tools name this differently. Quartz has per-trigger misfire instructions, and its CronTrigger tutorial says every trigger has a "smart policy" default that a CronTrigger interprets as MISFIRE_INSTRUCTION_FIRE_NOW (exact behaviour: the CronTrigger.updateAfterMisfire() Javadoc, not opened here). Kubernetes CronJobs have startingDeadlineSeconds: "after missing the deadline, the CronJob skips that instance of the Job". Plain @Scheduled has none.

    The lab stops the scheduler from 10:03 to 10:41, missing four fires, while one event arrives per minute. Each policy runs against two bodies: one reads "the ten minutes ending at my fire time", the other "everything since my last watermark".

    Expected output, captured from a real run (the lab's run A; Spring Boot 4.1.2, JDK 27, 2026-12-01):

    Run A. Missed runs. The scheduler is down from 10:03 to 10:41, so the fires at 10:10 10:20 10:30 10:40 are missed.
    70 events arrive, one a minute from 09:51 to 11:00. Each line lists the runs as 'time -> events processed'.
      body: reads the ten minutes ending at its fire time
        SKIP: 10:00 -> 10, 10:50 -> 10, 11:00 -> 10
          processed 30 of 70, lost 10:01-10:40
        FIRE_ONCE: 10:00 -> 10, 10:41 for 10:40 -> 10, 10:50 -> 10, 11:00 -> 10
          processed 40 of 70, lost 10:01-10:30
        FIRE_ALL: 10:00 -> 10, 10:41 for 10:10 -> 10, 10:41 for 10:20 -> 10, 10:41 for 10:30 -> 10, 10:41 for 10:40 -> 10, 10:50 -> 10, 11:00 -> 10
          processed 70 of 70, nothing lost
      body: reads everything since its last watermark, up to now
        SKIP: 10:00 -> 10, 10:50 -> 50, 11:00 -> 10
          processed 70 of 70, nothing lost
        FIRE_ONCE: 10:00 -> 10, 10:41 for 10:40 -> 41, 10:50 -> 9, 11:00 -> 10
          processed 70 of 70, nothing lost
        FIRE_ALL: 10:00 -> 10, 10:41 for 10:10 -> 41, 10:41 for 10:20 -> 0, 10:41 for 10:30 -> 0, 10:41 for 10:40 -> 0, 10:50 -> 9, 11:00 -> 10
          processed 70 of 70, nothing lost

    The window body loses 40 of 70 events under SKIP and 30 under FIRE_ONCE, silently, because every run it makes succeeds. The watermark body loses nothing under any policy, and FIRE_ALL only adds three runs with nothing to do. A body that reads "since I last finished" removes the missed-run problem instead of managing it.

    Overlapping runs

    A fire overlaps when the previous run has not finished. Three behaviours exist:

    • Allow: start another run now. Kubernetes' Allow is the CronJob default ("the CronJob allows concurrently running Jobs").
    • Skip: drop the fire. Kubernetes' Forbid: "the CronJob skips the new Job run".
    • Serial and late: start it when the running one ends. For the JDK's scheduleAtFixedRate, "subsequent executions may start late, but will not concurrently execute"; Spring's ThreadPoolTaskScheduler delegates to a ScheduledExecutorService.
    sequenceDiagram accTitle: Two overlapping runs paying the same payout accDescr: Run 1 starts at 10:00 and reads payouts P1 and P2 as pending. Run 2 starts at 10:10 while run 1 is still working and reads the same two payouts plus P3. Run 1 pays P1 and P2 at 10:25. Run 2 pays P1, P2 and P3 at 10:35. P1 and P2 were each paid twice. participant R1 as Run 1 (10:00) participant DB as Payout table participant R2 as Run 2 (10:10) R1->>DB: read pending: P1, P2 R2->>DB: read pending: P1, P2, P3 R1->>DB: pay P1, P2 (10:25) R2->>DB: pay P1, P2, P3 (10:35) Note over DB: P1 and P2 paid twice

    Figure 3. An allowed overlap with a snapshot body. How to read this: both runs read before either writes, so each believes the same rows are pending. The scheduler did nothing wrong; the body assumed it ran alone.

    The lab's payout job fires at 10:00, 10:10 and 10:20 and each run takes 25 minutes. The naive body reads the pending payouts at the start and pays them at the end. The claiming body marks each pending payout CLAIMED at the start, which in SQL is an UPDATE ... WHERE status = 'PENDING' whose affected-row count says who won:

                for (Map.Entry<String, String> row : status.entrySet()) {
                    if (row.getValue().equals("PENDING")) {
                        mine.add(row.getKey());
                        if (body == Body.CLAIMING) {
                            row.setValue("CLAIMED"); // the atomic claim: UPDATE ... WHERE status = 'PENDING'
                        }
                    }
                }

    Expected output, captured from a real run (the lab's run B):

    Run B. Overlapping runs. A payout job fires at 10:00, 10:10 and 10:20 and each run takes 25 minutes.
    P1 and P2 are pending at 10:00, P3 arrives at 10:05, P4 at 10:15.
      body: reads the pending payouts at the start, pays them all at the end
        ALLOW: started 10:00 10:10 10:20; most runs at once 3
          payments: P1 x3, P2 x3, P3 x2, P4 x1; unpaid at the end: none
        SKIP_IF_RUNNING: started 10:00, skipped 10:10 10:20; most runs at once 1
          payments: P1 x1, P2 x1; unpaid at the end: P3 P4
        SERIAL_LATE: started 10:00 10:25 10:50; most runs at once 1
          payments: P1 x1, P2 x1, P3 x1, P4 x1; unpaid at the end: none
      body: claims each pending payout at the start, pays what it claimed at the end
        ALLOW: started 10:00 10:10 10:20; most runs at once 3
          payments: P1 x1, P2 x1, P3 x1, P4 x1; unpaid at the end: none
        SKIP_IF_RUNNING: started 10:00, skipped 10:10 10:20; most runs at once 1
          payments: P1 x1, P2 x1; unpaid at the end: P3 P4
        SERIAL_LATE: started 10:00 10:25 10:50; most runs at once 1
          payments: P1 x1, P2 x1, P3 x1, P4 x1; unpaid at the end: none

    Under ALLOW the naive body pays 4 payouts 9 times; the claiming body, in the same three overlapping runs, pays each once. SKIP_IF_RUNNING and SERIAL_LATE are safe for both bodies, at a price: skipping leaves P3 and P4 unpaid until a later fire, and serial runs start 15 and 30 minutes late. Avoiding overlap in the scheduler trades correctness for lateness; a claiming body keeps both.

    Retries: classify, back off, make the second try harmless

    A failed run is worth repeating only if the next attempt can differ from the last; the transient and permanent classes from dead-letter queues and retries apply unchanged. Two points are specific to jobs.

    A failing @Scheduled method is not retried, and does not stop. The JDK Javadoc says that if a periodic task throws, "subsequent executions are suppressed". Spring's scheduler behaves differently, and the lab observes it (run E): a @Scheduled(fixedRate = 25) method that throws on its first run was called again. That next fire is a retry only by accident, with no back-off, and unless the exception is logged loudly nobody knows the first run failed. This is the silent failure the Temporal blog describes. Catch, classify, record and alert.

        @Scheduled(fixedRate = 25)
        public void run() {
            int n = calls.incrementAndGet();
            threeCalls.countDown();
            if (n == 1) {
                throw new IllegalStateException("the first run fails");
            }
        }

    A retry replays the work done before the failure. A batch A, B, C fails on C after paying A and B; retrying from the top pays A and B again. The fix is an idempotency record: write run id : payout id when paying, skip a payout whose key exists. In SQL that is a unique constraint, and a violated insert means "already done".

    stateDiagram-v2 accTitle: Life of one job run with retries accDescr: A fire starts a run. If every step succeeds the run is done. A transient failure with attempts left moves to a wait for the back-off and then runs again. A permanent failure, or attempts used up, marks the run failed and raises an alert. [*] --> Running: fire Running --> Succeeded: all steps done Running --> Waiting: transient failure, attempts left Waiting --> Running: back-off elapsed Running --> Failed: permanent failure or attempts used up Failed --> [*]: alert raised Succeeded --> [*]

    Figure 4. A run's states. How to read this: only the transient branch loops, through a wait. Both ways of failing end in an alert, so a failed run is never silent.

    The lab retries the batch with back-off of 1 s, 2 s, 4 s and at most four attempts. The one condition that separates the bodies:

                        if (body == Body.IDEMPOTENT && recordedKeys.contains("run-1:" + id)) {
                            steps.add("skip " + id + " (already paid)");
                        } else {

    Expected output, captured from a real run (the lab's run C, first part):

    Run C. Retries with back-off (1 s, then 2 s, then 4 s; at most 4 attempts). The batch is A, B, C.
      The provider rejects payout C on the first two attempts (transient):
      naive body (starts from A every attempt):
        02:00:00 attempt 1: paid A, paid B, FAILED on C (TransientException)
        02:00:01 attempt 2: paid A, paid B, FAILED on C (TransientException)
        02:00:03 attempt 3: paid A, paid B, paid C -> success
        payments made: A x3, B x3, C x1; run SUCCEEDED
      idempotent body (records run-1:<payout> for each payout it makes):
        02:00:00 attempt 1: paid A, paid B, FAILED on C (TransientException)
        02:00:01 attempt 2: skip A (already paid), skip B (already paid), FAILED on C (TransientException)
        02:00:03 attempt 3: skip A (already paid), skip B (already paid), paid C -> success
        payments made: A x1, B x1, C x1; run SUCCEEDED

    Attempts start at 02:00:00, 02:00:01 and 02:00:03, waits of 1 s and 2 s. Both runs succeed, but the naive one has paid A and B three times. The lab also runs a permanent failure (one attempt, not retried) and a provider that never recovers (four attempts, then "FAILED after 4 attempts, alert raised"). For long retries or poison records, enqueue the work and let a queue with a dead-letter topic own the retries.

    More than one instance

    Run the application on three servers and each starts its own scheduler, so something must ensure one instance runs a fire. Two guards are common.

    A lock with a lease. ShedLock "makes sure that your scheduled tasks are executed at most once at the same time" using a lock in a shared store. Its lockAtMostFor is always released after the stated time; the README says to set it "to a value which is much longer than normal execution time" because "if the task takes longer than lockAtMostFor the resulting behavior may be unpredictable". It also says it "is not and will never be full-fledged scheduler, it's just a lock" and "assumes that clocks on the nodes are synchronized". Quartz's JDBC store is the alternative, at the cost of a Quartz schema in your database.

    A run key. Before working, an instance inserts a row keyed by job and fire time; the first insert wins and the other stops. A key removes the duplicate instance but says nothing about two different fires overlapping.

                    case LEASE_30_MIN, LEASE_5_MIN -> {
                        Duration lease = guard == Guard.LEASE_30_MIN ? Duration.ofMinutes(30) : Duration.ofMinutes(5);
                        if (lock == null || !sim.now().isBefore(lock.until())) {
                            int token = ++tokens;
                            lock = new Lock(token, sim.now().plus(lease));
                            start(label, token);
                        } else {
                            refused.add(label);
                        }
                    }

    The lab models both with an in-memory field standing for a lock row in a shared database; nothing here is a real database or lock library. Two instances fire at 02:00, 02:10 and 02:20 and a run takes 19 minutes.

    Expected output, captured from a real run (the lab's run D):

    Run D. Two instances, a job every 10 minutes that takes 19 minutes. Both instances fire at 02:00, 02:10 and 02:20.
    The lock is an in-memory field standing for a lock row in a shared database.
      NONE: ran a@02:00 b@02:00 a@02:10 b@02:10 a@02:20 b@02:20; most runs at once 4
      LEASE_30_MIN: ran a@02:00 a@02:20; refused b@02:00 a@02:10 b@02:10 b@02:20; most runs at once 1
      LEASE_5_MIN: ran a@02:00 a@02:10 a@02:20; refused b@02:00 b@02:10 b@02:20; most runs at once 2
      RUN_KEY: ran a@02:00 a@02:10 a@02:20; refused b@02:00 b@02:10 b@02:20; most runs at once 2

    With no guard six runs start and four are active at once. The 30-minute lease holds it to one. The 5-minute lease expired mid-run, so the 02:10 fire took the lock and two runs overlapped: a lease protects only while the job is shorter than the lease. The run key refuses every b but cannot stop a@02:10 overlapping a@02:00.

    Build it: five runs on a manual clock

    This is the minimal example, a lab you can run. Runs A to D take time from a ManualClock, so their output never changes. Run E uses real threads and prints only facts that do not depend on timing.

    Goal. See the effect of each missed-run, overlap, retry and cluster policy on a payout job, and how Spring's real scheduler treats overlap and a failing run.

    Setup. From the repository's examples/spring-labs folder:

    cd examples/spring-labs && ./gradlew :labs:background-jobs-schedulers:test

    Ten behaviour tests assert the claims of runs A to D, three more probe the real scheduler, and a golden test compares the report with examples/spring-labs/golden/background-jobs-schedulers.txt. The code is under examples/spring-labs/labs/background-jobs-schedulers/src/main/java/buildingai/labs/jobs/. Only Schedule and run E use Spring's scheduling code; MissedRuns, OverlappingRuns, RetryingRuns and ClusterRuns are the lab's own model of the behaviours above, not an implementation of Quartz, ShedLock or Kubernetes.

    Expected output, captured from a real run (the lab's run E):

    Run E. Real threads, real time (only facts that do not depend on timing are printed).
      ThreadPoolTaskScheduler with 4 threads, scheduleAtFixedRate every 20 ms, each run takes 80 ms:
        most runs of that one task active at once: 1
      scheduleWithFixedDelay of 30 ms, each run takes 60 ms:
        every start came at least 30 ms after the previous end: true
      A @Scheduled(fixedRate = 25) method on Spring Boot's scheduler throws on its first run:
        it was called again, at least twice more: true

    A 4-thread pool never ran one fixed-rate task twice at once, consistent with the JDK Javadoc, the fixed delay waited, and the throwing method was called again.

    Break it. In OverlappingRuns.start, delete the line row.setValue("CLAIMED"): the claiming body then behaves like the naive one and the test that expects each payout paid once fails. Put the line back and re-run the tests.

    Stretch. Cap FIRE_ALL with a deadline as startingDeadlineSeconds would. Add a lease renewal so a long run keeps its lock.

    What the lab leaves out. A real Quartz scheduler, a real lock library, a real database, time zones and daylight-saving changes (the fires are UTC). The 19, 25 and 5 minute figures are lab parameters.

    Trade-offs

    Approach Gives Costs Fits
    @Scheduled in the app No new infrastructure No memory of missed fires, no coordination, one thread by default One instance, skippable work
    @Scheduled plus a lock library One run at a time A lock table, a lease longer than the job, synchronized clocks A few jobs in an existing app
    Quartz with a JDBC store Persistent triggers, misfires, clustering A schema and an operational surface Many jobs that must survive restarts
    Schedule enqueues, queue consumers work Retries, dead letters and scale-out A broker and idempotent consumers Large fan-out, such as one job per store

    In practice: ShopStream's nightly store payout

    This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared 5,000 stores are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    At 02:00 every night ShopStream pays each of its 5,000 stores. One @Scheduled(cron = "0 0 2 * * *") method loops over all stores and calls the payment provider. At an illustrative 0.2 s per store the loop takes 5,000 x 0.2 s = 1,000 s, about 17 minutes, on an app that now runs three instances.

    Starting architecture

    ShopStream nightly payout: the scheduler only enqueues, workers payScheduler to Run record (claim the date); Scheduler to Payout queue (enqueue 5,000); Payout queue to Workers (poll); Workers to Payment API (pay); Workers to Dead letters (after retries)Scheduler: 02:00 cronScheduler02:00 cronRun record: key: payout dateRun recordkey: payout datePayout queue: one per storePayout queueone per storeWorkers: claim, then payWorkersclaim, then payPayment API: may be downPayment APImay be downDead letters: alert on depthDead lettersalert on depthclaim the dateenqueue 5,000pollpayafter retries

    Figure 5. The target design. How to read this: the scheduler does one cheap thing, records that the date has started and enqueues one message per store. The slow, failure-prone work is done by workers that claim each store and date before paying.

    Options considered

    Option Behaviour Problem
    A. One @Scheduled loop Simple Three instances each run it
    B. Lock library around the loop One run A deploy that kills the run loses the night; the lease must outlast a growing loop
    C. Quartz JDBC store with the loop Survives restarts, misfire handling Still one long run; a restart leaves a half-paid night
    D. Scheduler enqueues, workers claim and pay Each store is its own retryable unit A broker and idempotent workers

    The decision

    Option D. The cron method claims a run record keyed by the payout date, so one instance enqueues, one message per store keyed by store and date. A worker claims the key before paying, retries transient failures with backoff and dead-letters permanent ones. A sweep every 15 minutes (illustrative) re-enqueues any store with no payout record for the date, so a missed night heals itself.

    Rollout and verification

    The team replays the lab's scenarios on staging: a window with the scheduler down, two instances firing at once, a provider outage mid-run. Verification: killing the scheduler instance at 02:06 leaves no store unpaid after the next sweep, and enqueueing twice produces no second payout.

    The 2 a.m. failure

    The page reads: 3,100 stores are unpaid at 09:00. Before the redesign a rolling deploy replaced the instances at 02:06 and killed the loop after about 1,900 stores; the next fire was 02:00 the next night, because an in-process schedule has no memory of the missed run.

    The checks: the log shows the job started and never finished, and no completion row exists for the date. The mitigation is running the payout by hand, which is safe because every payout is claimed by key. The lasting fix is the design above plus an alert when no completion record exists by 03:00.

    Architect's notes

    • Choose the policy from the job body. Ask "what does one run read" before choosing a misfire policy.
    • Write the body so the policy you did not choose is harmless. Claim rows atomically, key effects by run, read from a watermark.
    • A scheduler is not a queue. Use it to enqueue; let the queue do retries, dead letters and scale-out.
    • A lease is a bet on duration. A lease shorter than the job gives an overlap with extra steps.
    • Alert on a missing success, not only on an exception.

    Common mistakes

    • Assuming one instance. The third replica makes every job run three times.
    • A window body with a skip policy. Every run succeeds and data is silently lost.
    • A lock lease shorter than the job. The lock expires mid-run and the next fire starts a second run.
    • Letting an exception disappear. The scheduler calls the method again at the next fire and nobody is told.
    • Retrying from the top without idempotency. The first half of the batch is done twice.

    Key takeaways

    • A scheduler decides when; policies decide what a missed or overlapping fire does; the body decides whether a repeat is harmless.
    • A body that reads "since my last watermark" makes missed runs a non-problem.
    • Allowing overlap is safe only if the body claims its work atomically.
    • Spring's @Scheduled documents no persistence and no cross-instance coordination; Quartz with a JDBC store adds both.
    • A lock lease must be much longer than the job, and clocks must agree.
    • A retry replays earlier work unless the body records what it did.

    Practice exercises

    Exercise 1 (20 min). For a nightly invoice export, an hourly cache warm-up and a per-hour usage rollup, choose skip, run once or run each missed fire, and say what the body must read.

    Exercise 2 (45 min). Run the lab. In run B, work out how many payments the naive body makes if the job fired every 5 minutes and still took 25.

    Exercise 3 (1 hour). Make LEASE_5_MIN stop overlapping in ClusterRuns without lengthening the lease. Say what you added and what it costs.

    Exercise 4 (2 hours). Design ShopStream's payout sweep: its schedule, its query, the key it relies on and what it does with a store that keeps failing.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments