M4-S1 — The scheduler and background jobs
Section titled “M4-S1 — The scheduler and background jobs”| Module | M4 — The process engines |
| After this session you can | Explain how time-based and deferred work is stored, fired and tracked, and diagnose a job that ran late, twice or never. |
| Time | 66 min with a facilitator · about 66 min on your own |
| Before you start | M2-S2 (messages and the bus) and M2-S4 (where data lives). Larkspur Lab running, signed in as Rami Aziz, with the four windows of the workbench open: logs, the bus console, the read-only record query and the API. Keep the engine trace map beside you. |
| Go deeper | Engine: Scheduler and jobs · Long-running work · Runbooks: clear stuck locks |
◆ Orientation (1 min) — Work that nobody clicked
Section titled “◆ Orientation (1 min) — Work that nobody clicked”Every morning at 06:00, Maintenance Plans raises the preventive work orders that are due. No person clicks anything: a timer does it. In ACE M3-S4 you built such a timer as a reaction and learned to make its filter catch up. In this session you open the machinery behind it: where the schedule is stored, what fires it, how the run is split across workers, and what each piece records. Then you use that knowledge on Larkspur Lab to read a schedule, change it, make it run late on purpose and explain what you see. M4-S2 picks up where this session ends: the reaction run that the timer starts.
▤ Concept (10 min) — Three subsystems, three questions
Section titled “▤ Concept (10 min) — Three subsystems, three questions”When, how in parallel, and what happened
Section titled “When, how in parallel, and what happened”Three separate pieces of the platform deal with work that does not happen inside a request. They share the word “job”, which is the main source of confusion, so keep them apart from the start:
| Piece | The question it answers | Where its state lives | What a “job” is there |
|---|---|---|---|
| The scheduler service | When should something happen? | A MongoDB collection of schedules | A stored schedule: a time, or a repeating rule |
| Background queues | How is a big piece of work split and run in parallel? | Redis, inside the service doing the work | One unit of work, for example one chunk of 100 records |
| The job-status record | What happened to work a person started? | A short-lived Redis record per person | A progress and result record the portal reads |
The scheduler service is a standalone service built on Agenda, an open-source Node.js
library that keeps schedules as documents in a MongoDB collection called agendaJobs and polls
that collection for documents that are due. The background queues use BullMQ, a Node.js
queue library that keeps its queues in Redis. The two never talk to each other directly: the
scheduler announces on the message bus that a time has come, and whichever service owns the work
then does it, often through its own BullMQ queues. You met the bus’s delivery contract in
ACDE M1-S2; here you see one of the engines that depends on it.
The round trip of a schedule
Section titled “The round trip of a schedule”sequenceDiagram participant B as Builder saves a timer reaction participant R as Reaction service participant S as Scheduler service participant M as agendaJobs collection B->>R: reaction saved (Repeat, cron) R->>S: command: schedule this interval job S->>M: cancel any job with the same key, save one Note over S,M: Agenda polls; the job falls due S->>R: event: scheduled job triggered (with the job's data) R->>R: select matching records, split into chunks, run
What to notice: the scheduler never knows what the job is for. It stores the data it was given and hands it back unchanged when the time comes; only the reaction service knows what to do.
Follow the arrows for Maintenance Plans. When a builder saves a reaction whose event is On Timer Reached and whose Interval type is Repeat, the reaction service sends a command (a message addressed to one service that asks it to do something) to the scheduler: “schedule an interval job with this cron expression, and give me back this data when it fires”. The data carries an id made of the entity’s id and the reaction’s id, joined by an underscore, plus the space and the tenant.
The scheduler first cancels any stored job with the same key, then saves exactly one. The key
is the job’s id, its space and, since 1.10, its tenant (data.id, data.spaceId, data.appId).
That is why editing a timer reaction replaces its schedule instead of adding a second one. The
uniqueness comes from that cancel-and-save logic, not from a database index, so if you ever find
two documents with the same key, suspect a write that failed halfway, not a feature.
When the job falls due, Agenda runs a small task that publishes an event (a message that
announces a fact to whoever listens) called scheduled job triggered, carrying the data back. Its
correlation id starts with TIMER- followed by Agenda’s own document id, which is how you find
it in the logs. The reaction service recognises its own job by the id, loads the reaction, applies
the reaction’s filter to its entity’s records, and runs the reaction’s action on each match.
Two consequences matter when you diagnose:
- A command that was consumed is not a schedule that was saved. The scheduler catches and logs
its own errors instead of rejecting the message, so the bus shows the command as delivered even
when nothing was stored. The only proof of a schedule is its document in
agendaJobs. - The start and end dates are checked when the job fires, not when it is saved. Before the Start Date, each tick is skipped and the job keeps repeating. After the End Date, the next tick deletes the job document. A timer whose end date passed is therefore gone from the store, and editing the reaction is the only way to bring it back.
Reading a schedule document
Section titled “Reading a schedule document”A document in agendaJobs is small. The fields you read are these:
| Field | Meaning | What it tells you |
|---|---|---|
name | Which task runs: TriggerTimerJob for a repeating timer, ScheduleJob for a one-time one | The kind of schedule |
data.id | <entity id>_<reaction id> for a timer reaction | Which reaction owns it |
repeatInterval | The cron expression | How often |
nextRunAt | When Agenda will run it next | In the past while the scheduler is up means it is stuck |
lastRunAt, lastFinishedAt | When the last run started and ended | Whether it fired at all |
lockedAt | Set while a scheduler replica holds the job | A value that stays for long means a replica died holding it |
The collection is cell infrastructure: one store for every tenant the scheduler serves, which is why the tenant is part of the key. On your lab release it lives in the scheduler’s own database; a cell can move it to a separate operations database, and the workbench names the one your release uses.
The run: chunks, and who it runs as
Section titled “The run: chunks, and who it runs as”A timer can match thousands of records, so the reaction service does not run them inside the handler that received the event. It splits the matching records into chunks of 100 and builds a BullMQ flow: one parent job and one child job per chunk. Workers process the chunks in parallel (five at a time by default), and BullMQ runs the parent only after every child has finished, which is when the run is complete. Each record still goes through the same reaction logic as an ordinary event, so everything you learn about reaction runs in M4-S2 applies here.
A timer run has no person behind it. The schedule’s data carries the user who saved the reaction, and the run executes as the executor you chose in Event Executor Type; with System, the run history shows the system as the one who did it. The chunk workers bind that identity to each job explicitly, because a worker is not inside a request and would otherwise see no user at all.
What a person sees: the job-status record
Section titled “What a person sees: the job-status record”When a person starts long work, such as a bulk update of 5,000 work orders, the data service
writes a job-status record in Redis for that person: its status (Scheduled, InProgress,
Success or Failed), a progress percentage and a result. The portal reads it with
GET /api/v1/job/<messageId>, where messageId is the id of the message that started the work.
Two facts surprise people. Only the final status is pushed live to the browser; progress in
between is written to the record and must be read by polling. And the record expires after
24 hours, so a question about yesterday’s bulk update is answered by the run history, not by
the job-status record.
Why nothing tells you a job was late
Section titled “Why nothing tells you a job was late”The scheduler publishes two metrics: a count of jobs fired and failed, and how long each run took.
There is no metric for lateness, by design: by the time Agenda reports that a job started, it has
already replaced the time the job was supposed to run. So lateness is something you work out
from the document and the history: a nextRunAt in the past while the scheduler is healthy, a
gap between runs longer than the cron allows, or runs that arrive in a burst after an outage.
▶ Guided demo (10 min) — Find the schedule behind Maintenance Plans
Section titled “▶ Guided demo (10 min) — Find the schedule behind Maintenance Plans”Starting state. Larkspur Lab as seeded: Maintenance Plans has the reaction Raise preventive
work orders, On Timer Reached, Repeat, Cron Expression 0 6 * * *.
-
In the designer open Data Entities › Maintenance Plans › Reactions and open Raise preventive work orders. Read its Interval type, Cron Expression and Event Executor Type. You see Repeat,
0 6 * * *and System. -
Copy the entity id from the address bar (reactions open inside the entity, so the address does not carry the reaction’s id), and read the reaction id from the entity’s reaction list:
curl -s "$BASE/api/reaction/v1/reaction/<entity id>" -H "x-app-token: $TOKEN". The job id is the two joined by an underscore. -
In the record-query window, open the scheduler’s database and find the document:
db.agendaJobs.find({ "data.id": "<entity id>_<reaction id>" },{ name: 1, repeatInterval: 1, nextRunAt: 1, lastRunAt: 1, lastFinishedAt: 1, lockedAt: 1, "data.spaceId": 1 })One document comes back,
nameisTriggerTimerJobandrepeatIntervalis0 6 * * *. -
Read
nextRunAt. It is tomorrow (or today) at 06:00 in the scheduler’s time zone, stored in UTC. -
Read
lastRunAtandlastFinishedAt. On a fresh seed they are empty or show the last 06:00 run. -
In Administration › Monitoring › Reaction Logs, filter Event by On Timer Reached. The runs listed match the
lastRunAtvalues: one run per fire, Executed by System.
Screenshot pending The agendaJobs document of the Maintenance Plans timer in the record-query window, showing name, repeatInterval, nextRunAt and lastRunAt
What to notice: the document holds when, not what; the only link back to the reaction is the id in data.id.
⛏ Lab (35 min) — Edit, end and delay a schedule
Section titled “⛏ Lab (35 min) — Edit, end and delay a schedule”Goal. Prove three behaviours of the scheduler on Larkspur Lab: an edit replaces a schedule, a past end date deletes it at the next tick, and a scheduler outage produces one late run, not a burst.
Before you start. The demo’s job id. Rami Aziz in the designer. Two Maintenance Plans records whose Next due is today or earlier (the seed provides Pump P-104 quarterly service and Compressor C-220 monthly check). Note the number of open Work Orders now.
Part A — an edit replaces the schedule
- In the reaction editor, change Cron Expression to
*/2 * * * *(every two minutes) and save. This is a test value; Part D puts the real one back. - Run the demo’s query again. Still exactly one document;
repeatIntervalnow reads*/2 * * * *andnextRunAtis less than two minutes away. - Count the documents with that id:
db.agendaJobs.countDocuments({ "data.id": "<job id>" }). The answer is 1.
Part B — one fire, end to end
- Wait for
nextRunAtto pass, then query again:lastRunAtandlastFinishedAtmoved andnextRunAtis two minutes later. - In the logs window, search the reaction service’s log for the fire:
kubectl -n larkspur logs deploy/lk-osos-core-rest --since=5m | grep TIMER-. The lines carry a correlation id that starts withTIMER-. - Open Work Orders. Two new preventive work orders exist, one per due plan.
- Open Reaction Logs: one run of Raise preventive work orders, Executed by System, followed by the chained run that advances each plan’s Next due.
- Wait for the next fire (two minutes). No new work order: both plans now have a future Next due, so the filter matches nothing.
Part C — a late job
- Stop the scheduler:
kubectl -n larkspur scale deploy/lk-osos-scheduler --replicas=0. - In Maintenance Plans, set Next due of Pump P-104 quarterly service back to yesterday, and wait at least five minutes (two ticks and more).
- Query the document:
nextRunAtis now in the past andlastRunAthas not moved. - Start the scheduler:
kubectl -n larkspur scale deploy/lk-osos-scheduler --replicas=1, and wait until its pod is ready. - Query again, and open Reaction Logs. One run after the restart, not one per missed tick;
nextRunAtis two minutes after that run. One new work order for P-104.
Part D — an end date, then restore
- In the reaction, set End Date to yesterday and save. Query: the document is still there, with the end date in its data.
- After the next tick, query again. The document is gone, and no run appears in Reaction Logs.
- Clear End Date, set Cron Expression back to
0 6 * * *and save. Query: one document,nextRunAtat the next 06:00. Write in your notes that the test value was restored.
Check.
- After Part A, one document with
*/2 * * * *and a count of 1. - Part B produced two work orders, then none at the following fire.
- During the outage,
nextRunAtwas in the past andlastRunAtdid not move. - After the restart, exactly one catch-up run and one work order.
- After the end date passed, the document was gone and nothing ran.
- The reaction is back on
0 6 * * *with no End Date, and one document exists.
Pass condition. Your notes show, for each of Parts A to D, the query result before and after
(the repeatInterval, nextRunAt, lastRunAt values or the count), and the restored schedule
matches the seed.
If something goes wrong
| What you see | What to do |
|---|---|
| The query returns nothing in Part A | Check the database: the workbench names the one that holds agendaJobs. Check the id: entity id first, then the reaction id. |
| Two documents with the same id | A save failed halfway in an earlier exercise. Delete the reaction’s schedule by saving the reaction again; if two remain, note it as a finding and report it to whoever maintains your lab. |
| No work orders in Part B | The plans’ Next due is in the future, or the chained reaction already advanced them. Set one back to yesterday. |
| Several catch-up runs in Part C | Note it with the times: that contradicts the behaviour this session predicts, so record it as a finding and report it to whoever maintains your lab. |
| The scheduler pod stays unready | kubectl -n larkspur describe pod -l app.kubernetes.io/name=scheduler and read the events; the bus or the database may still be starting. |
Model answer
A. Saving the reaction sent a new schedule command; the scheduler cancelled the old document
and saved one with the new cron, so the count stays 1. B. At the fire, lastRunAt moved, the
event (correlation id TIMER-…) reached the reaction service, the filter matched the two due
plans, and two work orders were created; the chained reaction moved each plan’s Next due
forward, so the next fire matched nothing. The filter’s “on or before today” is what makes it
catch up, and the chained update is what stops it repeating. C. With no scheduler running,
nothing polls the collection, so nextRunAt stays in the past and nobody is told: there is no
lateness metric. On restart Agenda finds the overdue job, runs it once and computes the next run
from that run, so missed ticks are not replayed. Because the filter compares with “on or before
today”, the one catch-up run still raises every overdue work order. D. The end date is checked
when the job fires: the first tick after it deletes the document, and nothing runs. Saving the
reaction without an end date sends a new schedule command, which creates the document again.
◇ Worked scenario (3 min) — The Monday with no work orders
Section titled “◇ Worked scenario (3 min) — The Monday with no work orders”On Monday at 09:00 Omar Haddad, the maintenance planner, reports that no preventive work orders were raised at 06:00 for the third day running. Nobody changed anything, he says. Decide at each step before you read on.
Step 1. Is there a schedule? You query agendaJobs for the reaction’s job id. There is no
document. A missing document means either the schedule was never saved or it was removed. So the
question becomes: what removes a schedule? Three things: saving the reaction with a different
event, archiving or disabling it, and an End Date that has passed.
Step 2. Which one? The reaction is active and its event is still On Timer Reached. Its End Date reads last Thursday. The history of the reaction shows that a colleague set an end date during a planned plant shutdown and meant to clear it later. The first fire after Thursday deleted the document, and nothing has fired since. Nothing announced it, because a removed job is simply no longer there to fire.
Step 3. Repair, and the missed days. You clear the End Date and save, then query: one
document, due tomorrow at 06:00. But three days of work orders were never raised. Do you need to
run anything by hand? Only if the filter cannot catch up. Its condition is Next due on or before
today, so the next fire will raise every plan that fell due during the three days. You decide not
to wait until tomorrow: you set a one-off Cron Expression of the next free minute, check the
run in Reaction Logs, and put 0 6 * * * back.
Step 4. Make it visible next time. The real failure is that a schedule disappeared silently.
You add two lines to the program’s runbook: every timer that must run daily has an entry in a
monitoring check that compares lastRunAt with the cron and alerts when a day is missed, and any
end date set for an outage is recorded with its removal date in the change log. You also add a
test to the release checklist: after an import or upgrade, count the timer schedules against the
timer reactions.
The lesson: when a scheduled job “never runs”, the first evidence is the schedule document, not
the reaction. Its absence, its nextRunAt and its lastRunAt tell you which of the three
failure families you are in: never saved, removed, or not polled.
✓ Practice (6 min) — Check your understanding
Section titled “✓ Practice (6 min) — Check your understanding”After you change a timer reaction’s cron expression and save, the bus console shows the schedule command as delivered and acknowledged. A colleague says the new schedule is therefore in place. What do you check before you agree?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A schedule document reads nextRunAt: 2026-11-20T06:00:00Z, lastRunAt: 2026-11-19T06:00:02Z
and lockedAt: null. It is now 2026-11-20 at 09:30 UTC, and the scheduler pod has been running
all morning. What does this tell you?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A bulk update of 5,000 work orders finished yesterday afternoon. Today a planner asks you how many records failed. Where do you look?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
The scheduler was down from 02:00 to 08:00. A timer reaction runs every hour on records whose due date is on or before today. What happens when the scheduler comes back at 08:00?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Two documents in agendaJobs carry the same data.id, the same space and the same tenant. What is
the most likely explanation?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
↺ Recap (1 min) — From time to work
Section titled “↺ Recap (1 min) — From time to work”You can now follow time-based work through the platform: a stored schedule in agendaJobs, an
event when it falls due, and a chunked run in the service that owns the work, with a short-lived
status record for anything a person started. You can tell a job that was never saved, removed or
not polled from the document alone. Next, M4-S2: the reaction run itself, the engine every timer
and every record change ends up in, and how it survives a pod that dies in the middle.