What You'll Learn
- 1Choose a Dataproc image and cluster mode that matches the Spark version your jobs need
- 2Write initialization actions that install packages without ballooning cluster startup
- 3Mix on-demand and spot workers so cost drops without risking the master node
- 4Tune shuffle, joins, and dynamic allocation against measurable job metrics
Dataproc is managed Spark and Hadoop on GCP: Google provisions the VMs, installs the image, wires YARN or Spark standalone, and meters per second. What you control is the machine shapes, the initialization actions that customise each node, the worker mix, and the Spark configuration every job inherits. This lesson focuses on the three levers that show up in cost reviews and interview loops: initialization actions, spot workers, and shuffle tuning.
Cluster Topology and Images
A Dataproc cluster has a primary node (or three in HA mode) and a worker group. Single-node mode runs Spark without YARN workers and suits lightweight jobs. Standard mode adds workers that execute tasks. Images 2.0 and 2.1 are the long-lived lines; 2.1 runs Spark 3.5 with Scala 2.12, and both lines ship Debian or Rocky variants. Image choice is effectively a Spark version pin, so test on the image your production cluster runs before adopting new SQL features.
HDFS is optional. Because Dataproc nodes are ephemeral, the durable pattern is to read from and write to Cloud Storage with the Hadoop connector, then delete or recreate clusters per job. Clusters that keep state in HDFS force you into longer-lived, more expensive node pools. The connector itself has knobs worth knowing: the read and write parallelism follows object listings, so a directory of millions of tiny objects is slow to list regardless of compute, while a handful of large Parquet files read at near line rate. Partitioned layouts on Cloud Storage, written by earlier jobs, also let Spark prune files at read time instead of discovering size at runtime.
# Standard cluster: 1 primary, 4 on-demand workers, image 2.1, GCS as the data plane.
gcloud dataproc clusters create spark-batch \
--region=us-central1 \
--image-version=2.1-debian12 \
--master-machine-type=e2-standard-4 \
--num-master-local-ssds=1 \
--num-workers=4 \
--worker-machine-type=e2-standard-8 \
--worker-local-ssds=1 \
--properties='spark:spark.executor.memory=8g,spark:spark.executor.cores=4,spark:spark.sql.adaptive.enabled=true' \
--initialization-actions=gs://my-bucket/init/install-deps.sh \
--metadata='INIT_ACTION_TIMEOUT=600'
Local SSDs on workers give Spark scratch space for shuffle spills; without them, spills hit the boot disk and slow stages that should have been I/O bound anyway.
Initialization Actions That Stay Fast
Initialization actions run on every node during cluster creation, before Spark or YARN start. They are the supported way to install Python packages, drop JARs into the Spark classpath, or tune YARN site files. Two properties matter: they run with a timeout, and they are not idempotent by default. A slow pip install pushes cluster creation past the point where the operator gives up; a package that half-installs on a preempted node and retries leaves the classpath in an unknown state.
#!/bin/bash
# install-deps.sh â keep it fast, idempotent, and network-light.
set -euxo pipefail
pip install --no-cache-dir 'pandas==2.0.0' 'pyspark==3.4.1' &
PIP_PID=$!
gsutil cp gs://my-bucket/jars/mysql-connector-j.jar /usr/lib/spark/jars/
cat > /etc/spark/conf/spark-defaults.conf.d/custom.conf << 'EOF'
spark.eventLog.enabled=true
spark.eventLog.dir=gs://my-bucket/spark-logs/
spark.history.fs.logDirectory=gs://my-bucket/spark-logs/
spark.sql.adaptive.enabled=true
spark.sql.adaptive.coalescePartitions.enabled=true
EOF
wait $PIP_PID
Pin every package version. An unpinned install makes two workers in the same cluster run different pandas builds, and the resulting errors appear as mysterious task failures hours later rather than as a startup problem. For heavyweight dependencies, bake a custom image with the Dataproc image builder instead of downloading gigabytes at boot.
Spot Workers Without Losing the Cluster
Spot VMs are preemptible compute with discounts that reach into the nineties percent range relative to on-demand pricing. Dataproc lets you add a pool of them beside on-demand workers, and the rule of thumb is to keep the primary node and a minimum slice of workers on on-demand so preemption cannot take out YARN resource management. Tasks that were running on a preempted node fail and retry on surviving nodes; Spark's stage retries handle this transparently as long as the job is not already at its retry limit.
gcloud dataproc clusters create spark-spot-mix \
--region=us-central1 \
--image-version=2.1-debian12 \
--master-machine-type=e2-standard-4 \
--num-workers=2 \
--worker-machine-type=e2-standard-8 \
--num-preemptible-workers=6 \
--preemptible-worker-machine-type=e2-standard-8 \
--properties='spark:spark.task.maxFailures=8,spark:spark.stage.maxConsecutiveAttempts=8'
The raised failure limits in that example are deliberate: with six of eight workers spot, a simultaneous preemption wave can kill several task attempts at once, and the defaults will abort the job even though the data is fine. Spot pools work best for batch jobs with idempotent writes and elastic completion times; never point a streaming or low-latency workload at them.
Autoscaling Against Backlog
Dataproc autoscaling policies scale workers on YARN pending containers or Spark executor demand, with cool-down periods that stop flapping. Define scale-up and scale-down rules explicitly rather than relying on cluster defaults, and set a cooldown long enough for a new node to finish bootstrapping before the policy evaluates again.
gcloud dataproc autoscaling-policies create spark-autoscale \
--region=us-central1 \
--policy="file://autoscale.yaml"
An autoscale policy yaml that grows to eight workers when more than five containers queue for two minutes, and shrinks when the queue stays empty for ten minutes, keeps a nightly batch cluster responsive to its own backlog without paying for idle workers between runs. Tie the policy to the cluster at creation with --autoscaling-policy=spark-autoscale.
Shuffle, Joins, and Adaptive Execution
Shuffle is where Dataproc jobs lose most of their wall time. The default of 200 shuffle partitions was chosen for medium datasets; a job shuffling 500 GB wants far more parallelism, while a job shuffling 2 GB wastes time scheduling hundreds of tiny tasks. A practical starting point is two to four partitions per executor core, then measure stage skew in the Spark UI.
Spark on image 2.1 enables Adaptive Query Execution by default, so verify the flag is on rather than assuming you must set it. AQE coalesces shuffle partitions after the shuffle map stage completes, converts sort-merges into broadcast joins when the build side turns out small, and rebalances skewed joins by splitting hot partitions at runtime.
from pyspark.sql import SparkSession
from pyspark.sql.functions import broadcast, col
spark = (
SparkSession.builder
.appName("orders-enrichment")
.config("spark.sql.adaptive.enabled", "true")
.config("spark.sql.adaptive.skewJoin.enabled", "true")
.config("spark.sql.adaptive.coalescePartitions.enabled", "true")
.config("spark.sql.shuffle.partitions", "400")
.config("spark.dynamicAllocation.enabled", "true")
.config("spark.dynamicAllocation.minExecutors", "2")
.config("spark.dynamicAllocation.maxExecutors", "40")
.getOrCreate()
)
orders = spark.read.parquet("gs://my-data-lake/orders/")
customers = spark.read.parquet("gs://my-data-lake/customers/")
# Small dimension table: broadcast it instead of shuffling both sides.
enriched = orders.join(broadcast(customers), "customer_id")
# Repartition the fact table before a heavy group-by so output tasks are even.
result = (
enriched
.repartition(200, col("order_date"))
.groupBy("order_date", "region")
.agg({"amount": "sum", "order_id": "count"})
)
result.write.mode("overwrite").partitionBy("order_date").parquet(
"gs://my-data-lake/output/enriched/"
)
When AQE cannot fix skew because one key genuinely dominates, salt the key: append a random bucket to the hot key, aggregate with the salted key, then aggregate again without the salt. Two-stage aggregation trades a little extra compute for balanced partitions.
Monitoring and Cost Review
Dataproc meters per second for each VM and its attached disk, so cluster lifetime is the cost driver. The Spark history server, enabled by the event log settings in the initialization action, replays completed jobs with per-stage timing. YARN ResourceManager shows live container demand, which is the signal autoscaling reacts to. When reviewing a bill, separate the hours the cluster was genuinely running jobs from the hours it sat idle waiting for a human; the second category is almost always the larger one, and it disappears the moment clusters become per-job resources with init actions fast enough to make creation boring.
| Cost lever | Typical saving | Trade-off |
|---|---|---|
| Spot workers for the fleet | up to about 90 percent per worker | preemption retries and slower tail latency |
| Shorter cluster lifetime via per-job clusters | whole idle hours removed | 2 to 4 minutes of startup per job |
| Right-sized executors with AQE | fewer wasted cores | tuning time per workload |
| GCS instead of HDFS | no idle replication capacity | connector I/O versus local disk |
Common Mistakes
Making the primary node preemptible or spot
Fix: Keep the primary on on-demand; losing it takes down the YARN resource manager and the whole cluster with it.
Downloading dependencies inside initialization actions on every cluster start
Fix: Bake heavy dependencies into a custom image and reserve init actions for configuration, which keeps cluster creation under a couple of minutes.
Leaving spark.sql.shuffle.partitions at the default for every job
Fix: Tune partitions to roughly two to four times executor cores and confirm with stage skew in the Spark history server.
Best Practices
- Store data in Cloud Storage so clusters stay ephemeral and cheap
- Raise task failure limits when spot workers exceed a third of the fleet
- Enable event logging from day one so post-mortems have stage-level evidence
Key Takeaways
- Dataproc image version pins the Spark version; 2.1 runs Spark 3.5 and AQE on by default
- Initialization actions are the supported customisation hook but must be fast, versioned, and idempotent
- Spot workers deliver the deepest discount, so keep the primary and a worker floor on on-demand and raise max task failures
- Shuffle tuning with AQE, broadcast joins, and salted aggregation recovers most of the wall time lost to skew
Interview Questions
Interview Questions
Q1: How do you optimize a Spark job that spends most of its time in shuffle stages?
Measure stage skew in the history server, tune shuffle partitions to core count, broadcast small dimension tables, enable AQE skew handling, and salt keys that still dominate partitions.
Q2: What breaks when you put all workers on spot?
Simultaneous preemption can exhaust task retries and abort the job, and a cluster with no on-demand capacity can fail to schedule the YARN node manager baseline; keep a floor of on-demand workers.
Q3: cache() or persist() for a DataFrame reused three times in a job?
cache() implies MEMORY_ONLY; persist() lets you choose MEMORY_AND_DISK when the frame exceeds executor memory. For large frames that spill anyway, persist to MEMORY_AND_DISK up front rather than discovering eviction mid-job.
Q4: Why prefer Cloud Storage over HDFS on Dataproc?
Ephemeral clusters cannot rely on local replication; GCS separates the durable data plane from compute so clusters can be created per job and deleted on completion without losing data.