Skip to the page

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.

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.

Single-statement transactional enqueue

Inserting ext::napalm::Job inside the same statement as your business write commits both atomically. Rolled-back writes enqueue zero jobs, and committed writes never drop work.

A deployed query that queues a job
# 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 };

What an insert sets

querystrrequired
The deployed query to run, by name.
variablesjson
A JSON object of the query’s variables. Empty when left out.
run_timedatetime
When the job is due. Now when left out.
expire_timedatetime
When a failed attempt is no longer followed by another. A day after run_time when left out, and at most 30 days after.

A job due now starts within a second, while a delayed job waits durably in the database until due.

Run in a week
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 byRuns asRefused when
A signed-in personThat person, for the one attempt.Refused whenThe person was removed. The person’s jobs are removed too.
An agent a person let inThat person, under the agent’s grant.Refused whenThe grant was revoked or ran out.
A service keyThat key.Refused whenThe key was revoked or expired.
A scheduleThe key the schedule names.Refused whenThe key was revoked or expired.

Access is evaluated when the job runs rather than when it was queued. 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 fails, the handler answers with a status outside 2xx, a handler that took the work on ends the run with an error, or the run times out. The first retry runs 10 seconds later, and each subsequent wait doubles up to one hour. A failed attempt whose next retry would fall at or past expire_time marks the job failed. Every attempt is recorded as an ext::napalm::JobRun with start and finish timestamps, a timeout and any error message.

Exponential backoff and expire_time ceiling

Failed attempts reschedule automatically starting at 10 seconds and doubling up to 1 hour until expire_time, logging each attempt in ext::napalm::JobRun.

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.

What the handler is sent
{  "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 end-to-end TypeScript handler patterns 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 it or the run’s timeout expires.

The handler takes the work on
import { accepted, handleCalls } from 'napalm-client' export default handleCalls(  {    async trainModel(call) {      // Hand the assertion to the program that does the work.      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.

The program that does the work
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()
RequestWhat the request does
POST /jobs/{id}/stepsRecords a finished step by name along with its JSON answer. Repeating a name already recorded returns the first record.
GET /jobs/{id}/stepsLists the job’s finished steps, oldest first.
POST /jobs/{id}/timeoutResets the run’s deadline to timeout_seconds from now.
POST /jobs/{id}/finishCloses 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 because they may mutate state.

Job types of your own#

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.

dbschema/default.gel
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  );}
Queue one
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.

The job’s query
# 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 them, and cancelling one marks it cancelled while preserving its fields and links. Delete completed rows with your own query once you no longer need them.

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.

Branch-scoped cron clock and queue

Each tick on a named IANA time zone enqueues an ext::napalm::Job under the schedule’s service key and coalesces missed downtime ticks into a single run.

03:00 every day, Pacific time
napalm schedules add acme rollUpUsage '0 3 * * *' \  --key 0b6f1f5e-2a4c-4d7e-9f3b-8c1d2e3f4a5b \  --time-zone America/Los_Angeles

A schedule

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 its own job, retrying until the next tick (at most 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, 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.

queries/jobStatus.edgeql
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’s is_ready.
running
An attempt is under way, or a handler claimed the run and it 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 with is_final. The last run’s error explains 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.

Follow one job · curl
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 remove them, and Napalm never auto-purges finished rows. 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.

queries/deleteOldJobs.edgeql
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, preserving fields, steps and links for a possible later retry. Cancelling a scheduled job skips only that tick and queues the next scheduled time immediately.

Limits#

LimitValue
One attempt120 seconds for the query and the handler together.
Attempts at once10 per branch on each engine. Other attempts wait.
A long job’s timeout60 to 86,400 seconds from each request, set again without limit.
Steps1,000 per job. A name holds 200 characters and an answer 64 KiB of JSON without spaces.
Schedules128 per branch.
A sleeping projectA due job wakes the project. The job starts about ten seconds late, plus the wake time.
Finished jobsKept until you delete them. Napalm never deletes finished jobs automatically. A schedule adds one job per scheduled tick, so prune old jobs with your own query.
API turned offJobs wait. No attempt is spent, and due jobs start when the API is on again.

Limits gathers every limit of a project, an org and the control API on one page.

Type a word or two to search every docs page.