Learn · Logic
Jobs & schedules
A job runs a deployed query in the background under the caller’s access. A schedule queues jobs on a cron clock.
- In the schema
ext::napalm::Job,ext::napalm::JobRun
The job queue#
Insert an ext::napalm::Job inside the statement that creates or mutates the underlying record. Because the job writes on the exact same PostgreSQL commit as your data change, rolled-back transactions queue zero phantom jobs and crashes after commit never drop queued work.
Transactional enqueue
One statement commits your data write and queued job atomically.
Name the deployed query to run and pass its parameters in variables inside a with block.
# queries/placeOrder.edgeqlwith order := (insert Order { item := <Item><uuid>$item, buyer := global caller }), job := (insert ext::napalm::Job { query := 'sendReceipt', variables := <json>(order := <str>order.id), }),select order { id };Job fields
- querystrrequired
- Name of the deployed query to run.
- variablesjson
- JSON object of query variables (defaults to
{}). - run_timedatetime
- Scheduled start timestamp (defaults to
datetime_of_statement()). - expire_timedatetime
- Cutoff after which failed attempts stop retrying (defaults to 24 hours after
run_time, up to 30 days).
A job due now starts within a second, while a delayed job waits durably in the database until due.
insert ext::napalm::Job { query := 'expireInvite', variables := <json>(invite := <str><uuid>$invite), run_time := datetime_of_statement() + <duration>'168 hours',};A job’s caller#
The database stamps the queuing caller at insert time, and an insert cannot forge another identity. When the job comes due, its query executes as that caller so your access policies govern background work identically to live requests.
| Queued by | Runs as | Refused when |
|---|---|---|
| Signed-in person | That person’s ext::auth::Identity. | Refused whenThe identity was deleted (deleting an identity also deletes its queued jobs). |
| Authorized agent | That person, bounded by the AgentGrant. | Refused whenThe grant was revoked or expired. |
| Service key | That branch service key. | Refused whenThe key was revoked or expired. |
| Cron schedule | The service key configured on the schedule. | Refused whenThe key was revoked or expired. |
Napalm evaluates access when the job runs rather than at enqueue time. If a person loses access to a record after queueing a job, the job cannot read or mutate that record either.
Retries#
A job retries whenever an attempt fails: the query errors, the handler answers outside 2xx, a long-running worker reports an error or the run times out. The first retry runs 10 seconds later, and each subsequent wait doubles up to one hour.
Bounded retry backoff
Failed attempts retry with exponential backoff from 10 seconds to 1 hour.
A failed attempt whose next retry would fall at or past expire_time marks the job failed. Every attempt records an ext::napalm::JobRun with start and finish timestamps, the run timeout and any error message.
Jobs that call a handler#
Queue a job naming an action to invoke external code with automatic retries, such as sending an email, charging a card or scoring a model. The query runs as the caller that queued the job, and matching rows go to the action’s handler signed like any action call along with the job id and attempt number.
{ "action": "sendReceipt", "variables": { "order": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90" }, "data": [{ "id": "8f2c…", "total": 4200, "buyer": { "email": "ada@example.com" } }], "job": { "id": "5d0e9c3a-7b1f-4c2e-a6d8-2f4b9e1c7a35", "attempt": 2 }}A job whose query finds no rows completes cleanly with nothing to dispatch. Pass job.id as the idempotency key for external API calls. For complete TypeScript handler examples with handleCalls, call.db() and live job progress hooks, see Actions and background jobs.
Long jobs#
A standard attempt runs for at most 120 seconds. For work that takes hours, such as model training, builds or large imports, a handler claims the run by answering 202 Accepted. The run stays open and the job remains running until the worker finishes the run or the deadline expires.
import { accepted, handleCalls } from 'napalm-client' export default handleCalls( { async trainModel(call) { // Pass the assertion to the external worker process. await startTrainer({ assertion: call.assertion }) return accepted(3600) }, }, { address: process.env.NAPALM_URL!, handlers: process.env.NAPALM_HANDLERS_URL! },)The invocation’s assertion authorizes progress updates for that run. Pass the assertion from the handler to the external process running the job, such as a long-lived container, your own backend or a queue worker. On its own, the assertion cannot read or write your application data.
import { jobRun } from 'napalm-client' const run = jobRun(assertion, { address: process.env.NAPALM_URL! }) const rows = await run.step('fetch', () => fetchRows())await run.timeout(3600)await run.step('train', () => train(rows))await run.finish()| Endpoint | Behavior |
|---|---|
POST /jobs/{id}/steps | Records a finished step by name along with its JSON answer. Repeating a name already recorded returns the first record. |
GET /jobs/{id}/steps | Lists the job’s finished steps, oldest first. |
POST /jobs/{id}/timeout | Resets the run’s deadline to timeout_seconds from now. |
POST /jobs/{id}/finish | Closes the run. Including an error fails the run and schedules a retry, and adding is_final stops retries until a manager retries the job manually. Repeating finish with the same outcome returns 200 idempotently. |
Each POST accepts a JSON object (or an empty body for {}). Any other body or non-finite number fails with 400 invalid_request. A step’s answer is capped at 64 KiB of compact UTF-8 JSON (413 request_too_large above that). Once a job reaches 1,000 recorded steps, new step names return 409 step_limit_reached, while previously recorded names still return their stored answer.
Every long run starts with a 150-second deadline. The handler’s 202 response can set {"timeout_seconds": 3600} between 60 and 86,400 seconds (an out-of-range value fails the attempt), and the worker can extend the deadline at any time. If the deadline expires before the worker finishes, the run times out and retries on the standard backoff schedule.
Each named step executes once per job. On a retry, run.step('fetch', …) reads the stored ext::napalm::JobStep record instead of running the callback again. The queuing caller can query steps directly, and a live subscription reflects each step as it completes.
call.db() continues to act as the queuing caller while the run remains open. Once the run closes, requests under /jobs/{id} fail with 409 job_run_ended so a stale worker halts immediately. The one exception is repeating finish with the same terminal outcome (success or the same error), which returns 200 so a worker that missed the response can confirm completion safely.
Every request under /jobs/{id} is idempotent, and the official handler libraries retry network errors and 500/502/503/504 responses after 0.5 s, 1 s and 2 s before surfacing the error on the fourth failure. Token exchanges behind call.db() retry the same way, whereas queries sent through call.db() run once without automatic retries.
Custom job types#
A plain job carries untyped JSON variables, whereas a custom job type carries typed properties, links and readiness rules. Extend ext::napalm::Job in your schema and insert that subtype to queue work.
type ImportJob extending ext::napalm::Job { required account: Account; is_ready := not exists ( select detached ImportJob filter .account = __source__.account and .status = ext::napalm::JobStatus.running );}insert ImportJob { query := 'importRows', account := <Account><uuid>$account,};When the job’s query declares $job (and variables does not already specify job), Napalm binds $job to the job’s UUID automatically so the query can read its typed fields directly.
# queries/importRows.edgeqlselect ImportJob { id, account: { name } }filter .id = <uuid>$job;is_ready defines when a queued job may start. Napalm dispatches a job only when it is due and is_ready evaluates to true, such as enforcing one active import per account above. Waiting for is_ready spends no attempt. Napalm re-evaluates readiness whenever a job on the branch becomes due or finishes, and every ten seconds as a sweep.
Custom job types remain ordinary rows in your schema. Napalm never deletes custom job rows automatically, and cancelling a job marks it cancelled while preserving its fields and links. Delete completed rows with your own query once those rows are no longer needed.
A branch copied with data preserves rows of custom job types so inbound links stay intact. Jobs that were waiting or running on the source arrive as cancelled without runs or steps, while plain jobs stay on the source so links to plain jobs are empty on the copy.
Schedules#
A schedule runs a deployed query on a cron clock. Like actions, schedules are branch settings, so pull-request branches start with no schedules and never run production’s cron jobs.
Cron schedules
Cron ticks enqueue jobs in your chosen time zone under a service key.
Attach a schedule to a deployed query with a five-field cron expression, a branch service key and an optional IANA time zone.
napalm schedules add acme rollUpUsage '0 3 * * *' \ --key 0b6f1f5e-2a4c-4d7e-9f3b-8c1d2e3f4a5b \ --time-zone America/Los_AngelesSchedule settings
- querystringrequired
- The deployed query to run. One schedule per query.
- cronstringrequired
- Five fields: minute, hour, day of the month, month, day of the week (0 is Sunday). Each field takes
*, numbers, ranges and steps, in comma lists. Restrict the day of the month or the day of the week, not both. - timeZonestring
- An IANA name, like
America/Los_Angeles. UTC when left out. - keyIduuidrequired
- The service key the schedule’s jobs run as. The key must belong to the branch.
- variablesobject
- The variables for each run.
Each scheduled tick enqueues a job that retries until the next tick (up to 30 days). Ticks missed during downtime coalesce into a single run rather than a backlog burst. During daylight saving transitions, a skipped wall-clock time shifts forward by the gap, and a repeated time runs once.
Each schedule keeps one job waiting at a time. As soon as that job completes, fails permanently or is cancelled, Napalm queues the next tick immediately.
Managers add and remove schedules with napalm schedules add and napalm schedules remove, on the project’s Queries tab in the console or through the Control API.
Job status#
Because jobs are rows, the queuing caller can query status, runs and steps or cancel a waiting job with delete. Service keys can read and delete jobs queued by service keys and schedules.
select ext::napalm::Job { query, status, run_time, finish_time, runs: { status, start_time, finish_time, error } order by .start_time, steps: { name, finish_time } order by .finish_time,}filter .id = <uuid>$job;pending- Waiting for
run_time, the next retry attempt or the type’sis_ready. running- An attempt is under way, or a handler claimed a long run that remains open.
completed- The query ran and any attached handler answered with a 2xx other than
202, or a long-running worker finished the run without error. failed- An attempt failed with no retry left before
expire_time, or a worker finished withis_final. The last run’serrorexplains why. An org manager can retry the job. cancelled- An org manager cancelled the job while waiting or while a worker held the run open. Nothing failed, and an org manager can retry the job.
Subscribe to jobStatus through live queries to drive a progress badge with zero polling.
curl -N https://notes.napalmdata.com/subscribe \ -H "Authorization: Bearer $SESSION" \ -H "Content-Type: application/json" \ -d '{ "subscriptions": [{ "id": "job", "name": "jobStatus", "variables": { "job": "5d0e9c3a-…" } }] }'napalm queue ls lists a branch’s jobs with read access, and the console shows main’s jobs on the project’s Queries tab. Managers can retry a failed or cancelled job with napalm queue retry or cancel a waiting or open long-running job with napalm queue cancel. Neither command exposes job variables or step answers, which stay inside your database.
Finished jobs remain in your database until you delete those rows, and Napalm never purges finished jobs automatically. Managers can prune finished jobs older than a chosen age with napalm queue clear or Clear finished on the Queries tab. The command removes completed, failed and cancelled jobs along with their runs and steps. Plain jobs clear by default, custom job types clear only when opted in, and jobs still referenced by an inbound link are never removed.
To prune old jobs automatically, deploy a cleanup query and attach a schedule. The schedule’s service key deletes jobs queued by service keys and schedules, whereas a signed-in person deletes only their own jobs.
delete ext::napalm::Jobfilter .status = ext::napalm::JobStatus.completed and .finish_time < datetime_of_statement() - <duration>'720 hours';Cancelling a job through napalm queue cancel transitions both the job and any open long run to cancelled without recording a failure or dropping the row, so fields, steps and links stay intact for a later retry. Cancelling a scheduled job skips only that tick and queues the next scheduled time immediately.
Limits#
| Limit | Value |
|---|---|
| One attempt | 120 seconds for the query and handler together. |
| Concurrent attempts | 10 per branch on each engine. Additional due jobs wait in queue. |
| Long-job deadline | 60 to 86,400 seconds per renewal, extendable without limit. |
| Steps per job | 1,000 steps. Step names hold up to 200 characters and answers hold up to 64 KiB of compact JSON. |
| Schedules | 128 per branch. |
| Sleeping projects | A due job wakes the project and starts within roughly ten seconds plus wake time. |
| Finished jobs | Retained until deleted with a query or napalm queue clear. Schedules insert one job row per tick. |
| Disabled project API | Due jobs wait without spending attempts and start once the API is re-enabled. |
Limits lists every project, organization and Control API quota on one page.