Run a background job #

View this page as Markdown

On this page

A job runs a script from your server application in its own container. It ends when the script exits, reaches its time limit, or is stopped. Start a job on demand with run_job or have a schedule handler start it.

A schedule calls an HTTP handler in your app at the due time. The handler can finish short work itself or request a separate job run for longer work.

Save the work under its own ID, with its input in a database or storage the job can read. The start request carries identifiers only. Save the request ID beside the work record before starting the job. Add the job run ID when the start returns.

Have the script claim the pending work in a transaction or with a conditional write before changing data. Record its progress, result or error under the work ID. The server can use that ID to look up the result later.

For a real import, save a row such as import-42 with status: pending and the input file's location. The script selects a pending import and changes its status to running in the same transaction. It processes the input only if it claimed the row, then records done and the imported count, or failed and the error, on that row.

Declare a job #

Try the job with sample data before it changes anything. Save this file as jobs/import-sample.json.

["item-1", "item-2"]

Save this script as jobs/import-sample.mjs. It reads the sample and exits.

import { readFile } from 'node:fs/promises';

const input = new URL('./import-sample.json', import.meta.url);
const items = JSON.parse(await readFile(input, 'utf8'));
console.log(`Read ${items.length} sample items.`);

Add "import:nightly": "node jobs/import-sample.mjs" to the scripts object in your application's package.json. Keep its other scripts. Run npm run import:nightly locally. Expect Read 2 sample items. in the output. After a hosted run ends, read that run's console and look for the same line.

Add this entry to the services array in your manifest.

{
  "kind": "job",
  "jobs": [
    {
      "name": "nightly_import",
      "script": "import:nightly",
      "size": "job-4gb",
      "timeout_seconds": 1800
    }
  ]
}

Declare up to five jobs in one job entry. Give each job a unique name of at most 64 characters. Start the name with a lowercase letter and use only lowercase letters, digits, and underscores. Set a timeout from 60 to 3,600 seconds.

Size CPUs Memory
job-2gb 1 2 GiB
job-4gb 2 4 GiB
job-8gb 4 8 GiB

The size in the job entry sets the job container's CPU and memory. Measure peak memory and elapsed time with representative input. Choose a size that fits the largest job you expect and a timeout that allows for slower runs. If your app has a development environment, check both choices there first.

If production is your only environment, ask the owner before starting a test run unless they already requested it. Use representative test input that is safe to process there. Compare the run's recorded seconds with your timeout. Use a memory measurement from the script to check the size.

Each job size has its own hourly rate, listed under its size key. Cloud divides the hourly rate by the number of seconds in an hour, then multiplies by the run’s recorded seconds. Cloud uses the rate in effect when the run ends. Cloud caps the seconds it charges for at the run’s time limit. A run with no recorded start costs nothing. If a run fails, is cancelled or times out, Cloud charges for its recorded seconds. The same rule applies in development and production.

If a run has a recorded start but the provider has yet to confirm its end, the seconds and charge stay pending. Cloud checks about once a minute. Usually the wait ends at the first check at least ten minutes after Cloud first saw the run end or stopped it.

A different deadline applies if the provider lists the run as failed and Cloud records a failure or stops the run while waiting for the container’s end. Compare the time of the first failed listing with the time the run’s timeout plus 90 seconds has passed since Cloud claimed it. Count ten minutes from the later time. The wait ends at the first check at or after that deadline.

Cloud uses the container’s end time if it arrives during the wait. Otherwise it uses the first recorded end, which is the time of the first failed listing for a run that ended that way. Cloud caps the recorded seconds at the timeout and posts the charge once the seconds are known.

See the pricing page or use read_rate_card to look up the rate for your job size.

To check the declaration first, call check_manifest with the application ID and full manifest. Submit the manifest and deploy the application with the script included.

A run can wait while a deploy or promotion sets up the job. When Cloud assigns the run, it uses the image and settings of the version serving then. Later deploys and promotions leave that run on its assigned version.

If you halt the environment or the account is paused or suspended, Cloud asks the hosting provider to stop recorded executions and marks unfinished runs cancelled on its next job check. Deleting the application or environment also cancels its unfinished runs and can remove their history. Save any result you need before deleting.

Server applications can run jobs in development and production. On an app with development turned on, deploy the script there to test the job. Promote the tested version before starting the job in production.

Start a run #

For a one-off run, save the work and request IDs, call run_job, read the run, and check the work record for its result.

Ask your AI assistant to call run_job with the application ID, job name and environment. Use development to try the job on your development version. The call defaults to production if you omit the environment. Your AI assistant asks the account owner before starting a production run unless the owner already asked for it.

A start can be refused if the environment is halted or has no serving version. A paused or suspended account, or a move of the application or its database, can also prevent a start.

Your account has three places for job runs across all its apps and environments. Starting and running jobs each use one place. If the provider lists a run as failed, its container may still be running when Cloud marks the run failed or stops it. Cloud frees that place when it sees the container’s end or when the timeout plus 90 seconds has passed since Cloud claimed the run, whichever comes first.

A new start with all three places in use returns HTTP 409 with job_runs_at_limit and creates no run. When a place is free, retry with the original request_id.

Give each new run its own request_id. Cloud uses the ID across all jobs in the same application and environment, so reusing it for a different job can return the earlier run.

Save the ID with the application, environment and job before calling run_job. If the reply is lost, retry with all four values from the original request.

If the retry returns repeated: true, save run.id or follow next to read the original run. A change in the application's state can cause the retry to be refused before Cloud looks up the request ID. Read the recent runs for the same job and environment. Use requested_at and started_by as clues. The list omits the request ID, so two close starts can leave the original run uncertain. Keep the original request ID while you check.

If the read still cannot identify the run, report its outcome as unknown. Check the job's own work record before deciding whether to start new work. A new run can be waiting to start, running or already ended when the start call answers. Follow the returned read for the run’s outcome.

Cloud never starts a new run on its own after a job fails. Before you run the job again, check its work record for progress and saved changes. Start a replacement only when you know what work remains and the original run can no longer write. Give the replacement a new request_id and use the same work ID.

Start a job from a schedule handler #

To start a declared job at a set time, have your schedule handler send a POST to /jobs/v0/runs. Authenticate with the environment's platform credential in TURNZERO_CLOUD_APP_TOKEN. A browser session or minted token cannot use this route. The credential supplies the application and environment. Send job and a request_id tied to that job and due time. Reuse the ID when retrying the same due time.

HTTP 202 means Cloud recorded a new job run. HTTP 200 with repeated: true returns the original run. Both give you run.id. Use it with read_job_runs to check the job's state. A successful schedule response gives the handler's outcome. Check the job and its saved result separately.

This example sends the whole start request from a Schedule package handler. It uses the gateway address when set, otherwise TURNZERO_CLOUD_API. The body contains only the job name and request ID. Keep the platform credential out of logs.

The handler's run.key identifies the schedule name and due time. Prefix it with the job name so the same due time gets the same job request ID. Keep this ID separate from the ID passed to run_schedule. Build and mount the Schedule router with a handler for the path your manifest declares. In that handler, call startNightlyImport(run, saveRunLink). Use the Schedule package option in step 2.

Supply saveRunLink to save or update the IDs in your database or storage. Save the schedule run ID, job request ID and job run ID. Use the job request ID to find and update the same record on a retry.

export async function startNightlyImport(run, saveRunLink) {
  const job = 'nightly_import';
  const requestId = `${job}:${run.key}`;
  const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
  const credential = process.env.TURNZERO_CLOUD_APP_TOKEN;
  if (!origin || !credential) throw new Error('Job endpoint or platform credential is missing');

  const response = await fetch(new URL('/jobs/v0/runs', origin), {
    // Keep the credential and body on this request, even if it redirects.
    redirect: 'manual',
    method: 'POST',
    headers: {
      authorization: `Bearer ${credential}`,
      'content-type': 'application/json',
    },
    body: JSON.stringify({ job, request_id: requestId }),
  });
  if (response.status !== 200 && response.status !== 202) {
    throw new Error(`Job start returned HTTP ${response.status}`);
  }

  const { run: jobRun } = await response.json();
  await saveRunLink({ scheduleRunId: run.run, jobRunId: jobRun.id, requestId });
  if (jobRun.state === 'failed') throw new Error('The job failed to start');
  return { status: 200, body: { jobRunId: jobRun.id } };
}

If the handler stops before saving the job run ID, recover the job request ID before starting anything again. Find the schedule run in read_schedules and copy its due value. For the example above the job request ID is the job name, followed by :, then the schedule name, @, and the exact due value.

Repeat the job start from the backend with that ID. If the first request was recorded, a recognized retry gives its run ID. If it was never recorded, this call can start the job. Before repeating a production start, ask the account owner unless they already requested that start. If the retry is refused, check recent job runs as described above.

To retry through the handler instead, use the due time of a timetable run or a manual run that supplied due_at. Start a new manual schedule run in the same environment with that due_at. In production, ask the account owner to approve the manual schedule run and any job start it may trigger, unless the owner already requested those acts. In development, no extra approval is needed.

Use a whole UTC minute the current timetable yields. It must be at or before the new request and within the time Cloud keeps run records. The handler will build the same job request ID.

For an ordinary manual run, use its recorded due to recover the job request ID directly. Reusing the schedule's original request_id only returns its earlier run. A new manual run without due_at uses a new due time and can start another job.

Check the result #

To see recent runs for the selected environment, open Job runs on your server app's Manage app page, then choose a run for details and any available logs.

Use read_job_runs with the application ID and the run ID in run to check one run. To list recent runs across all jobs in an environment, name the application and environment and leave out job and run. Add job to list only that job. The list shows the newest requests first. It returns ten by default and takes a limit from 1 to 50. Use a returned id as run to read one run and its console.

With an account-wide connection, in_flight.count shows how many places are in use across the account’s apps and environments. It includes starting and running jobs and any ended run that still holds a place after the provider listed it as failed. Compare the count with in_flight.limit, which is 3. If all three places are in use, wait for the count to drop before starting another run. An application-scoped connection omits in_flight. A run's timeout_seconds is null until Cloud assigns it.

The run record gives its state and, when known, its version number and timing. exit_code is the process exit code the hosting service reports for the job's execution, when it reports one. running can appear before Cloud records started_at, after the provider gives the run an execution ID. For starting or running, read again with the same ID after about a minute. A run can end as succeeded, failed, cancelled, or timed_out.

The hosting provider applies the job’s time limit. If Cloud still sees the execution running after the limit plus a 90-second margin, it asks the provider to stop it. Before repeating work, check what the original run saved.

Cloud starts assigning runs three minutes after it creates the job's resource in that environment. A run shows starting while it waits for that point. If a run is still unassigned after 90 seconds, Cloud records failed with reason not_claimed. The 90 seconds start at the request, or when the three-minute wait ends if the run had to wait. Once Cloud assigns the run, it checks for a provider execution ID. If it still has no ID 90 seconds after assignment, Cloud records failed with reason no_execution.

If the hosting provider rejects the start, Cloud records failed with reason provider_refused. If the provider never answers, Cloud checks for an execution before recording no_execution.

If the hosting provider lists an execution as failed before it confirms the container's end, Cloud keeps the run running while it checks for that end. Cloud waits up to five minutes from when it first sees the failure. When the start time is known, the run's timeout plus 90 seconds from its start can set an earlier deadline.

Cloud checks about once a minute and uses a confirmed end as soon as it sees one, including on the first check at or after the deadline. If that check still finds no confirmed end, Cloud tries to stop the container and records failed. It sets ended_at to when it first saw the failure. The result has no exit code or reason.

If the run is waiting for the provider’s end time, seconds is null, so read the same run again to check its recorded seconds. Tell the person that the duration is pending, and for a failed run that its state may still change to timed_out. A run the provider ended can change from failed to timed_out when its seconds reach the run’s time limit.

Cloud records succeeded if the provider reports success, or reports a failure with a confirmed container end and exit code 0 while the run is still running. An end confirmed after the run ends does not change it to succeeded, even with exit code 0.

Before reporting that the work is complete, check the expected result by its own identifier, such as the import record or the output file. For the saved import example, read row import-42 and check its status and imported count. The console line from the sample script only confirms that it read the sample. If a schedule handler started the job, check the schedule run, the job run, and the saved result.

If the run ends as failed, read its reason, its exit code when available, and its console. A start failure can have a reason without an exit code or console. The read_job_runs reference gives the next step for each console_reason value.

no_execution means Cloud recorded no provider execution. Work from the original run may still have started. Check the work's own progress or result record before starting a replacement. If you cannot establish that the original stopped, follow the replacement checks under Stop a run.

Turn Zero asks the hosting provider to stop a late execution it finds without an active run. That request does not confirm the work stopped. Check for changes the original may have saved before repeating the work.

A container can still be running after Cloud records failed without confirming its end. Check the work record and follow the replacement checks under Stop a run before starting another run.

A read of one ended run includes its last console lines when available. If console_reason is not_ingested, read the same run again in about a minute. If it is unavailable, read the run again later. If you still cannot read the console, check the work record for what ran and what it changed.

Cloud keeps ended runs for 30 days and waits for the charge decision before it removes them. Deleting the app or environment can remove its runs sooner. Save any result you need in your app’s own work record.

Stop a run #

To stop a run, call cancel_job_run with the application ID and the run ID in run. Your AI assistant asks the account owner before cancelling a production run unless the owner already requested it, and asks in development only if the run blocks a database size change or restore. Report the state it returns. If the run already ended, the call returns its recorded outcome. Cloud can record cancelled before the hosting provider confirms the stop. Read the run again with read_job_runs for the reported ended_at.

Before replacing a run whose stop you cannot confirm, wait at least its original timeout plus 90 seconds from the reported ended_at. Use 3,600 seconds as the timeout if you cannot recover the original value. Waiting gives any late execution time to end. Check the work record and any saved changes before repeating the work.

How a run uses credentials #

A successful production deploy, promotion, or rollback replaces the app’s production platform credential. A job already starting or running on an earlier version of that app can still use the previous credential. Each such run delays revocation until it ends or its timeout plus 90 seconds has elapsed since Cloud claimed it, whichever comes first. Cloud can revoke the credential once the usual grace period and all those waits have ended.

Development deploys and restarts normally reuse the current credential. If you replace the development platform credential, Cloud revokes all previous credentials for that app’s development environment without waiting for jobs to finish. This affects local environment files, the deployed development app, and jobs already running. Update your local files with the new value. Cloud tries to restart the deployed development app with the new credential. If the restart cannot start, restart or deploy the app before you run another job.

Refusals #

Refusal Cause Remedy
jobs_not_available Jobs are off where you submitted the manifest. Remove the job entry to check or submit the rest of the manifest, or wait until jobs are enabled.
serverless_no_job The manifest declares a job for a serverless application. Declare the job in a server application.
manifest_invalid The job declaration failed validation. Fix the job declaration at the path in the refusal, then check the manifest again.
job_script_missing The ZIP's root package.json lacks a declared job's script. The deploy did not start. Add the script and rebuild the ZIP, or change the job and submit the updated manifest. Check the files with deploy_files and check_only: true.
job_resource_capacity The deploy would exceed the hosting cell's job limit. A development deploy counts what a later promotion would add. The serving version stays in place. Remove the added jobs if you can deploy without them, then submit the manifest and deploy again. Otherwise, wait for Cloud to make room.
no_such_job The version serving the chosen environment does not declare that job. Check the environment and job name. If the serving version does not declare the job, deploy the declaration to the chosen environment. On a two-environment app, promote the version when the intended target is production.
no_such_job_run The run ID does not match a run for this application. Check the application ID. List recent runs of the job in its environment with read_job_runs and use the ID it returns.
job_runs_at_limit All three places are in use across your account. A run the provider listed as failed can still hold a place. Wait for a place to open. Cancelling an ended run cannot free its place sooner. You can cancel an active run you mean to stop. Retry the same start with the same request_id once a place is free.
job_run_capacity The part of the hosting service running your app has reached its limit for job runs. Wait a minute and retry the same start with the same request_id.
job_run_in_flight An active or recently ended job run may still be using this application's database. The database size change or restore did not start. Read the run before retrying. If it is still starting or running, wait for it to finish. A run that Cloud began starting can still block the database request if it was cancelled, timed out or ended without a recorded provider execution. A run with reason execution_lost or one marked failed after waiting for a confirmed end can also block the request while its end is unconfirmed. For a retry estimate, add the job's timeout for that run plus three minutes to requested_at. Cancelling a run before its timeout does not shorten this wait and can lengthen it. Cancel only if the owner authorizes it. Follow the database action's approval instructions.