Sub topic 12
Defining Compute with the Jobs and Clusters APIs
This chapter shows how to describe compute as JSON and send it to Databricks, so that clusters and jobs can be reviewed, versioned, and reproduced. It assumes you can read JSON, know the difference between all-purpose, job, and serverless compute, and have a personal access token or other credential for a workspace.
Why define compute in code
Clicking through the cluster UI works for one cluster. It does not work when you need ten identical clusters, a review of who changed the node type, or a way to rebuild a job after someone deletes it. The Clusters API and the Jobs API accept the same settings you see in the UI as JSON. Tools built on them, such as the Databricks CLI, Terraform, and Databricks Asset Bundles, all produce this JSON in the end.
The two APIs cover different lifecycles:
| API | Endpoint family | What it manages | Compute lifetime |
|---|---|---|---|
| Clusters API | `/api/2.1/clusters/...` | All-purpose clusters | Until terminated by you or by auto termination, and restartable |
| Jobs API | `/api/2.1/jobs/...` | Jobs, tasks, and the job clusters they use | Created at run start, destroyed at run end |
Serverless has no cluster object to create. For jobs, you define it by leaving out cluster settings.
The shape of a decision
A job definition chooses compute for each task. Three choices exist, and the JSON fields differ.
Creating an all-purpose cluster
An all-purpose cluster is created with POST /api/2.1/clusters/create. This request body defines a shared interactive cluster that scales between one and four workers, shuts down after 60 idle minutes, and uses standard access mode.
{
"cluster_name": "team-interactive",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"autoscale": {
"min_workers": 1,
"max_workers": 4
},
"autotermination_minutes": 60,
"data_security_mode": "USER_ISOLATION"
}Each field maps to an earlier chapter:
spark_versionselects the Databricks Runtime. The value15.4.x-scala2.12is a Long Term Support runtime. You can list valid values withGET /api/2.1/clusters/spark-versions.node_type_idselects the virtual machine type.i3.xlargeis an AWS name. Azure and GCP use different identifiers, andGET /api/2.1/clusters/list-node-typesreturns what your workspace offers.autoscalereplacesnum_workers. You set one or the other, never both.autotermination_minutesis the idle time before shutdown. A value of0disables auto termination, which is rarely what you want.data_security_modesets the access mode.USER_ISOLATIONis standard access mode.SINGLE_USERis dedicated access mode and also needssingle_user_name.
The create call returns a cluster_id immediately, and the cluster is not yet usable. Startup is asynchronous, so a script must poll GET /api/2.1/clusters/get until the state is RUNNING.
import os
import time
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
spec = {
"cluster_name": "team-interactive",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"autoscale": {"min_workers": 1, "max_workers": 4},
"autotermination_minutes": 60,
"data_security_mode": "USER_ISOLATION",
}
resp = requests.post(f"{host}/api/2.1/clusters/create", headers=headers, json=spec)
resp.raise_for_status()
cluster_id = resp.json()["cluster_id"]
print("created", cluster_id)
while True:
info = requests.get(
f"{host}/api/2.1/clusters/get",
headers=headers,
params={"cluster_id": cluster_id},
)
info.raise_for_status()
state = info.json()["state"]
print("state:", state)
if state == "RUNNING":
break
if state in ("TERMINATED", "ERROR"):
raise RuntimeError(info.json().get("state_message", "cluster failed to start"))
time.sleep(20)The script reads the workspace URL and token from environment variables instead of hard-coding them. Keep it that way, and never commit a token to a repository.
Managing the cluster afterward
| Action | Call | Notes |
|---|---|---|
| Change settings | `POST /clusters/edit` | Needs the full spec plus `cluster_id`. A running cluster restarts. |
| Stop, keep configuration | `POST /clusters/delete` | The name is misleading: this terminates the cluster but keeps its definition. |
| Start a stopped cluster | `POST /clusters/start` | Same configuration, new instances. |
| Remove for good | `POST /clusters/permanent-delete` | The definition is gone. |
The delete naming trips up many people. If a script calls clusters/delete and you expect the cluster to vanish from the list, it will still be there in the TERMINATED state.
Defining a job cluster
For scheduled work, you do not call the Clusters API at all. You describe the cluster inside the job, and Databricks creates it when a run starts and terminates it when the run finishes. This job definition, for POST /api/2.1/jobs/create, declares one job cluster and attaches a notebook task to it.
{
"name": "nightly-etl",
"job_clusters": [
{
"job_cluster_key": "etl_cluster",
"new_cluster": {
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"num_workers": 2,
"data_security_mode": "USER_ISOLATION"
}
}
],
"tasks": [
{
"task_key": "ingest",
"job_cluster_key": "etl_cluster",
"notebook_task": {
"notebook_path": "/Workspace/Users/[email protected]/ingest"
}
}
]
}The definition has two parts that link by key:
job_clustersis a list of reusable cluster definitions. Each has ajob_cluster_keyand anew_clusterbody, which uses the same fields as the Clusters API.- Each task refers to a cluster with
job_cluster_key.
Several tasks that share one job_cluster_key run on one cluster, so you pay for one startup and the tasks can run in sequence on warm nodes. If you put new_cluster directly on each task instead, every task gets its own cluster and its own startup time.
Job clusters have no autotermination_minutes. They end with the run, so the field does not apply.
Defining a serverless task
The same task without any cluster settings runs on serverless compute, provided serverless compute for jobs is enabled in the workspace.
{
"name": "nightly-etl-serverless",
"tasks": [
{
"task_key": "ingest",
"notebook_task": {
"notebook_path": "/Workspace/Users/[email protected]/ingest"
}
}
]
}There is no node type, runtime version, or worker count to choose, because Databricks manages those. The risk is that the same JSON means different things in different workspaces. If serverless is not enabled, a task with no cluster fields is rejected instead of running somewhere else. Keep that difference in mind when you copy a definition between workspaces.
Running an existing cluster from a job
A task can also set existing_cluster_id to run on an all-purpose cluster. This is convenient during development, because there is no startup wait. In production it has two costs. All-purpose compute is billed at a higher DBU rate than job compute, and the task shares the cluster with interactive users, so a heavy notebook session can slow the job. Use it for iteration, then switch to job_cluster_key or serverless.
Keeping definitions consistent with policies
Both APIs accept a policy_id in the cluster body. A cluster policy then restricts or fills in fields such as node types, maximum workers, and auto termination. If a request violates the policy, the call fails with an error instead of creating a noncompliant cluster. Setting apply_policy_default_values to true lets the policy fill in fixed values you left out, so your JSON can stay short.
Updating a job
To change an existing job, you have two options:
POST /api/2.1/jobs/updatechanges only the fields you send. Usefields_to_removeto delete a field.POST /api/2.1/jobs/resetreplaces the whole definition with the one you send. Anything you omit is lost.
For code-driven workflows, reset is safer when the JSON file is the source of truth, since it removes drift. For a quick edit of one setting, update is less risky.
To run a job, call POST /api/2.1/jobs/run-now with the job_id. The job cluster is created at that point, which is why the first task of a run includes a startup delay.
Common errors
- Setting both
num_workersandautoscale. Choose one. If both are present the request is invalid. - Wrong
node_type_idfor the cloud. An AWS name sent to an Azure workspace fails. Read the node types from the workspace you are targeting. - Missing
data_security_mode. Depending on defaults, you may get a mode that cannot use Unity Catalog the way you intended. State the mode explicitly. - Expecting
editto be hot. Editing a running all-purpose cluster restarts it, which interrupts users. - Using
existing_cluster_idfor a nightly job. The cluster may be terminated at run time. Databricks will try to start it, which adds delay and cost, and the job still depends on a shared resource.
Putting definitions under version control
Store the JSON files in Git and apply them from a pipeline. The Databricks CLI accepts the same bodies:
databricks clusters create --json @cluster.json
databricks jobs create --json @job.jsonThe @ prefix reads the body from a file. Databricks Asset Bundles and Terraform express the same fields in YAML or HCL and add change tracking, so the choice between them is about team tooling rather than about what compute you get.
Exercise
A nightly job has three notebook tasks that run one after another. You want one cluster startup per run, two workers, and no cost once the run ends. Which fields do you put in the job definition, and what do the tasks reference?
Show answer
Add one entry to job_clusters with a job_cluster_key (for example etl_cluster) and a new_cluster body containing spark_version, node_type_id, num_workers: 2, and data_security_mode. Give each of the three tasks "job_cluster_key": "etl_cluster". All three tasks share one cluster that Databricks creates at run start and terminates at run end, so no autotermination_minutes is needed. Putting new_cluster on each task instead would start three clusters.
Exercise
Your script calls POST /api/2.1/clusters/delete for a cluster, then lists clusters and still sees it. Is the call broken?
Show answer
No. clusters/delete terminates the cluster but keeps its definition, so it appears with the state TERMINATED and can be restarted with clusters/start. Use clusters/permanent-delete to remove it entirely.