Sub topic 8
Triggering and monitoring a job run
This chapter covers the two calls behind most job automation: run-now to start a run, and runs/get to watch it. You can already authenticate and send requests to the REST API. This chapter assumes you have a job defined in the workspace, a host URL, and a token in DATABRICKS_HOST and DATABRICKS_TOKEN. It also assumes you can read basic Python.
The working model
A job is a saved definition: tasks, compute, and a schedule. A run is one execution of that job. Triggering a run creates a new run object with its own run_id. The job ID identifies the definition, and the run ID identifies one execution. Everything you monitor later is keyed on the run ID.
The flow has three steps:
POST /api/2.1/jobs/run-nowwith ajob_id. The response containsrun_id.GET /api/2.1/jobs/runs/get?run_id=...repeatedly, until the run is finished.- Read the result and decide what your script does next: continue, retry, alert, or fail.
run-now returns as soon as the run is queued or created. It does not wait for the job to finish, so your script must poll.
Starting a run with curl
curl -sS -X POST "$DATABRICKS_HOST/api/2.1/jobs/run-now" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"job_id": 123}'A successful response looks like {"run_id": 455644833, "number_in_job": 455644833}. Pipe it through jq -r .run_id to capture the ID in a shell variable.
Passing parameters
If the job defines parameters, override them with job_parameters, a flat map of string keys to string values:
curl -sS -X POST "$DATABRICKS_HOST/api/2.1/jobs/run-now" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"job_id": 123, "job_parameters": {"run_date": "2026-12-04"}}'Older jobs may use task-level fields such as notebook_params. Those still work for jobs that don't define job-level parameters. Don't mix the two styles in one request. If you send a key the job doesn't define, the run may ignore it, so check the job's parameter names first.
Monitoring: life cycle state versus result state
The state object in a runs/get response has two separate fields. Mixing them up is the most common bug in polling scripts.
| Field | Answers | Example values |
|---|---|---|
| `life_cycle_state` | Where is the run in its progress? | `QUEUED`, `PENDING`, `RUNNING`, `TERMINATING`, `TERMINATED`, `SKIPPED`, `INTERNAL_ERROR` |
| `result_state` | How did it end? | `SUCCESS`, `FAILED`, `TIMEDOUT`, `CANCELED` |
result_state is only present after the run reaches a terminal life-cycle state. Until then, reading it directly raises a KeyError in Python, so use .get().
A run that ends in TERMINATED has finished running, but it may have failed. TERMINATED with result_state of FAILED is a failure. Checking only the life-cycle state makes failed jobs look successful.
A run can also sit in QUEUED (when queueing is enabled and the concurrency limit is reached) or WAITING_FOR_RETRY (between automatic retries). Treat both as non-terminal.
A basic polling script
This script triggers a run and polls until the life-cycle state is terminal, then prints the outcome.
import os
import time
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
resp = requests.post(f"{host}/api/2.1/jobs/run-now", headers=headers, json={"job_id": 123})
resp.raise_for_status()
run_id = resp.json()["run_id"]
while True:
r = requests.get(f"{host}/api/2.1/jobs/runs/get", headers=headers, params={"run_id": run_id})
r.raise_for_status()
state = r.json()["state"]
if state["life_cycle_state"] in ("TERMINATED", "SKIPPED", "INTERNAL_ERROR"):
print(state.get("result_state"), state.get("state_message"))
break
time.sleep(15)This works for a demonstration. It has four weaknesses for unattended use:
- It can loop forever if a run hangs.
- A single network error or
429response crashes the script, even though the run keeps going in Databricks. - It prints the result but does not set an exit code, so a CI step still passes after a failed job.
- It can't cancel the run if the script gives up.
A more robust version
The next script adds a deadline, tolerance for transient HTTP errors, an exit code, and cancellation on timeout. It also sends an idempotency token.
import os
import sys
import time
import uuid
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
TERMINAL = {"TERMINATED", "SKIPPED", "INTERNAL_ERROR"}
DEADLINE = time.time() + 60 * 60 # give up after one hour
def call(method, path, **kwargs):
"""Send a request, retrying on 429 and 5xx responses."""
for attempt in range(5):
r = requests.request(method, f"{host}{path}", headers=headers, timeout=30, **kwargs)
if r.status_code == 429 or r.status_code >= 500:
wait = int(r.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait)
continue
r.raise_for_status()
return r.json()
r.raise_for_status()
body = {"job_id": 123, "idempotency_token": str(uuid.uuid4())}
run_id = call("POST", "/api/2.1/jobs/run-now", json=body)["run_id"]
print(f"Started run {run_id}")
while time.time() < DEADLINE:
state = call("GET", "/api/2.1/jobs/runs/get", params={"run_id": run_id})["state"]
if state["life_cycle_state"] in TERMINAL:
result = state.get("result_state")
print(result, state.get("state_message"))
sys.exit(0 if result == "SUCCESS" else 1)
time.sleep(15)
call("POST", "/api/2.1/jobs/runs/cancel", json={"run_id": run_id})
print("Timed out, cancel requested")
sys.exit(2)Generating the idempotency_token once per logical trigger helps if you wrap run-now in your own retry logic. If a request times out and you resend it with the same token, Databricks returns the existing run instead of starting a second one. The token can be at most 64 characters. A fresh token on each retry would defeat this protection, so in a real pipeline derive it from something stable, such as a pipeline run ID.
The Retry-After header, when present, tells you how many seconds to wait after a 429. Later chapters cover rate limits in more detail.
Looking at the results of a run
For a job with a single task, GET /api/2.1/jobs/runs/get-output?run_id=... returns the task's output, such as a notebook's exit value or an error message. For a multi-task job, the parent run_id has no output of its own. The runs/get response includes a tasks array, and each entry has its own run_id and state. Call get-output with a task's run_id to read that task's output. To find out which task failed, loop over tasks and look for a result_state other than SUCCESS.
The same flow works from the CLI. databricks jobs run-now 123 starts a run and, by default, waits for it to finish. Add --no-wait to return immediately, and use databricks jobs get-run <run_id> to inspect it.
Common errors
400with "Job does not exist" orINVALID_PARAMETER_VALUE: thejob_idis wrong, or belongs to a different workspace thanDATABRICKS_HOST. Check the host first.401or403: the token is expired, or the identity lacks the "Can Manage Run" permission on the job.KeyError: 'result_state': you read the field before the run reached a terminal state. Use.get().- Two runs where you wanted one: you retried
run-nowwithout anidempotency_token. - A run stuck in
QUEUED: the job has hit its maximum concurrent runs. Raise the limit or wait.
Exercise
Your CI script triggers a job, polls until life_cycle_state is TERMINATED, and exits with code 0. The job's notebook raised an exception, but the CI step still passed. What is wrong, and what should the script check instead?
Show answer
The script checks only the life-cycle state, which says the run has finished, not how it ended. A failed notebook still reaches TERMINATED. The script should read state.get("result_state") once the life-cycle state is terminal and exit non-zero unless it equals SUCCESS. It should also treat SKIPPED and INTERNAL_ERROR as failures.
Exercise
Why should the idempotency_token be generated once per logical trigger rather than once per HTTP attempt?
Show answer
If an attempt times out, the run may already exist on the server. Resending the same token makes Databricks return that existing run instead of creating a second one. A new token on each attempt would start a duplicate run every time you retry.