Sub topic 2
How a cluster is built: driver, workers, and Spark
This chapter assumes you know the Databricks workspace and notebooks, and the basic Spark vocabulary of driver, executor, job, stage, and task. You should also be comfortable reading JSON. It explains how those Spark pieces map onto the virtual machines of a Databricks cluster. Later chapters on access modes, autoscaling, and cost build on this model.
A cluster is a set of virtual machines running Spark
A classic Databricks cluster is a group of cloud virtual machines (VMs) that run Apache Spark together. Databricks starts the VMs, installs the Databricks Runtime on them, and wires them into one Spark application. The VMs fall into two roles:
- One driver node.
- Zero or more worker nodes.
You pick the VM type (the node type) for each role. If you don't pick a driver type, it defaults to the worker type. Cloud providers name node types differently. i3.xlarge is an AWS example, and Azure and GCP use other names.
What the driver does
The driver is the coordinator. It does not store your distributed data, but almost everything you interact with passes through it:
- It runs the Spark driver process and holds the
SparkSession, the entry point your notebook code uses. - It runs the language interpreters for attached notebooks (Python, Scala, R, SQL).
- It turns your DataFrame operations into a plan, splits the plan into stages and tasks, and schedules those tasks on workers.
- It collects small results back from workers, for example the output of
display()orcollect(). - It serves the Spark UI and keeps the cluster's logs and metadata.
All users attached to a cluster share one driver. Their notebooks run in separate interpreter sessions, but they compete for the same driver CPU and memory.
What workers do
Workers do the distributed work. On Databricks, each worker node runs one Spark executor, and that executor uses all of the node's cores. An executor:
- Runs tasks assigned by the driver. By default, one core runs one task at a time, so a worker with 4 cores has 4 task slots.
- Holds partitions of data in memory or on local disk for caching and shuffles.
- Reads from and writes to cloud storage directly. Data does not flow through the driver.
The cluster's total parallelism is roughly the sum of cores across all workers. Adding workers adds task slots and memory. Making the driver bigger does neither.
| Aspect | Driver | Worker |
|---|---|---|
| Count | Exactly one | Zero or more, fixed or autoscaled |
| Runs | Notebook code, Spark scheduler, Spark UI | Executor that runs tasks |
| Holds | Plans, small results, broadcast variables | Data partitions, cache, shuffle files |
| Scales with | Larger node type | More workers or larger node type |
| If it is lost | The cluster fails and running work stops | Lost tasks are rescheduled on other workers |
The path of one query
The diagram shows what happens when a notebook cell runs a DataFrame aggregation.
In words:
- You run a cell. The notebook sends the command to the driver.
- The driver builds a query plan. Spark is lazy, so nothing runs until an action such as
count(),write, ordisplay(). - The driver splits the work into stages and tasks, one task per data partition.
- Executors on the workers pick up tasks, read their partitions from cloud storage, and compute.
- Where a stage needs data from other partitions (a join or group-by), executors exchange data in a shuffle. This traffic goes worker to worker, not through the driver.
- Small partial results return to the driver, which combines them and sends the output back to the notebook.
Why the driver size matters
Most workloads need a driver about as large as a worker. Some need more:
- Large
collect()ortoPandas()calls. These pull every row into driver memory. If the result is bigger than driver memory, you get an out-of-memory error even when the workers are idle. - Many concurrent users or notebooks. Every attached session adds interpreter memory on the one driver.
- Many partitions or tasks. A job with hundreds of thousands of tasks puts scheduling and bookkeeping load on the driver.
- Local-only Python code. Pandas, scikit-learn, and plain Python loops run on the driver only, not on workers.
The following snippet contrasts a pattern that keeps work on the workers with one that overloads the driver.
df = spark.range(0, 500_000_000)
# Work happens on the workers. Only one row returns to the driver.
total = df.selectExpr("sum(id) AS total").first()["total"]
print(total)
# Risky: this would pull 500 million rows into driver memory.
# rows = df.collect()The first query returns one number. The commented-out collect() would copy the whole dataset onto a single machine.
Setting driver and worker types in the Clusters API
The request below creates a cluster with a larger driver than its workers. driver_node_type_id overrides the default driver type. The aws_attributes block is AWS-specific and requests spot instances for workers while keeping the driver on-demand.
{
"cluster_name": "wide-driver-example",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"driver_node_type_id": "i3.2xlarge",
"autoscale": {
"min_workers": 2,
"max_workers": 8
},
"autotermination_minutes": 60,
"aws_attributes": {
"first_on_demand": 1,
"availability": "SPOT_WITH_FALLBACK"
}
}first_on_demand: 1 places the first node, the driver, on an on-demand instance. This matters because of the failure behavior in the next section.
You can inspect a running cluster's layout with the Clusters API. This Python script assumes the requests library, a workspace URL in DATABRICKS_HOST (including https://), a token in DATABRICKS_TOKEN, and the cluster ID as the first argument.
import os
import sys
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
token = os.environ["DATABRICKS_TOKEN"]
cluster_id = sys.argv[1]
resp = requests.get(
f"{host}/api/2.1/clusters/get",
headers={"Authorization": f"Bearer {token}"},
params={"cluster_id": cluster_id},
timeout=30,
)
resp.raise_for_status()
info = resp.json()
print("State: ", info.get("state"))
print("Worker type: ", info.get("node_type_id"))
print("Driver type: ", info.get("driver_node_type_id"))
print("Fixed size: ", info.get("num_workers"))
print("Autoscale: ", info.get("autoscale"))For an autoscaling cluster the response contains an autoscale object. For a fixed-size cluster it contains num_workers. Whichever one does not apply prints as None.
Failure behavior
The one-driver design has a direct consequence for reliability.
- Worker lost. Spark reruns the lost tasks on other workers and recomputes any lost shuffle data or cached partitions. The job usually finishes, but slower. This is why spot instances are acceptable for workers.
- Driver lost. The Spark application ends. Running commands fail, notebook state (variables, temp views, cached data) is gone, and the cluster is typically terminated or restarted. Keep the driver on an on-demand instance and write intermediate results to storage if a long run matters.
- Driver overloaded. Symptoms are a notebook that hangs, a "driver not responding" or out-of-memory message, or a cluster that restarts under load. Adding workers does not fix this. A larger driver or less driver-side work does.
Single-node clusters
A single-node cluster has a driver and no workers, so num_workers is 0. The driver runs Spark in local mode, with tasks running as threads on the same machine. It suits small data, exploratory work, and single-machine libraries, and it avoids paying for idle workers. It cannot scale out, and one node's memory and cores bound all work. Databricks also has a "Single node" option in the cluster UI that sets the required Spark configuration for you. You rarely write that configuration by hand.
Common mistakes
- Scaling workers to fix a driver problem. If a
collect()fails with out-of-memory, more workers will not help. Reduce what you send to the driver, or enlarge the driver. - Running pandas on large data and expecting it to distribute. Plain pandas runs only on the driver. Use Spark DataFrames, or the pandas API on Spark, for distributed work.
- Putting the driver on spot capacity. A reclaimed driver kills the application. Use on-demand for the driver.
- Treating workers as storage. Executor local disk and cache are temporary. They disappear when the cluster terminates or a worker is lost.
- Sharing one small driver among many heavy notebooks. Each attached user adds load to the same machine.
Exercise
A notebook on a cluster with 8 large workers fails with an out-of-memory error on the line pdf = df.toPandas(), where df has 400 million rows. The Spark UI shows the workers are mostly idle. Which node is the bottleneck, why will adding more workers not fix it, and name two ways to fix it.
Show answer
The driver is the bottleneck. toPandas() collects all rows from the workers into the memory of the single driver node, so driver memory limits it, not worker count. Adding workers adds task slots and executor memory but leaves the driver unchanged. Fixes: (1) reduce the data before collecting, for example filter, aggregate, or sample in Spark first; (2) keep the work distributed, using Spark DataFrame operations or the pandas API on Spark instead of plain pandas; (3) choose a larger driver_node_type_id if you must hold the data on the driver.
Exercise
In the Clusters API, a cluster is configured with "autoscale": {"min_workers": 1, "max_workers": 4} and a worker type with 4 cores. What are the minimum and maximum numbers of tasks that can run in parallel, and does the driver count toward them?
Show answer
Minimum 4 tasks (1 worker with 4 cores) and maximum 16 tasks (4 workers with 4 cores each). The driver does not count, because tasks run in executors on the workers. The exception is a single-node cluster, where the driver runs tasks itself in local mode.