🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cloud Dataproc for Spark/Hadoop Workloads

đŸŸĸ Free Lesson

Cloud Dataproc for Spark/Hadoop Workloads

Dataproc Cluster ArchitectureMaster NodeHDFS NameNodeWorker 1DataNode + ExecutorWorker 2DataNode + ExecutorWorker NDataNode + ExecutorExternal ServicesHive/HBase/PrestoGCS IntegrationCloud Storage ConnectorAuto-scalingDynamic Worker ManagementPreemptible VMsCost OptimizationInitialization ActionsCustom Setup Scripts

What You'll Learn

  • 1Describe the master and worker roles and where each daemon runs
  • 2Create clusters with the right image version, machine types, and initialization actions
  • 3Cut compute cost with preemptible workers, autoscaling, and cluster lifetimes
  • 4Submit and debug Spark jobs without SSH-ing into nodes unnecessarily

Dataproc exists for teams that already have Spark or Hadoop jobs and want them running on managed infrastructure without rewriting them. It is a thin control plane over Compute Engine: a cluster is a set of VMs with the right software image, HDFS and YARN configured, and Google APIs reachable, and you pay for those VMs while they exist. That last clause drives every design choice in this lesson, because a cluster left running between jobs is usually more expensive than the jobs themselves.

Dataproc Architecture

Cloud Dataproc is a managed Spark and Hadoop service for running Apache Spark, Apache Hadoop, and other data processing frameworks on GCP.

Core Components

Master Node:

  • Runs YARN ResourceManager
  • HDFS NameNode
  • Spark History Server
  • Jupyter notebook server (optional)

Worker Nodes:

  • Run YARN NodeManager
  • HDFS DataNode
  • Spark Executor containers
  • Handle data processing tasks

External Services:

  • Hive Metastore
  • HBase (optional)
  • Presto (optional)
  • Kafka (optional)

Two architectural facts matter more than the component list. First, HDFS is optional in practice: the GCS connector lets Spark read and write buckets directly, which removes the need to size disks for a replica of data that already lives in object storage. Second, the master node is a single point of coordination, so it should be a larger machine type than the workers but does not need disk capacity proportional to the dataset when data sits in GCS.

Cluster Creation

The first decision is lifetime, because that is the largest cost lever. A cluster that runs for a day to process twenty minutes of work pays for the difference, so Dataproc supports auto-deletion after an idle period and clusters created per job through Dataproc Serverless for Apache Spark. The second decision is machine shape: the master coordinates and runs the history server, while workers run executors, so memory per executor is what you are really buying. A useful starting point is a few standard workers, then measure executor memory pressure before resizing.

The third decision is storage. With the GCS connector in play, worker boot disks can stay small, and scratch space for Spark shuffle is better served by local solid state disks on the workers than by network-attached disks, because shuffle traffic is the busiest path in most jobs.

Basic Cluster Creation

# Create a basic cluster
gcloud dataproc clusters create my-cluster \
    --region=us-central1 \
    --zone=us-central1-a \
    --master-machine-type=n1-standard-4 \
    --worker-machine-type=n1-standard-4 \
    --num-workers=3 \
    --image-version=2.1-debian

# Create a cluster with autoscaling
gcloud dataproc clusters create my-autoscaling-cluster \
    --region=us-central1 \
    --master-machine-type=n1-standard-4 \
    --worker-machine-type=n1-standard-4 \
    --num-workers=2 \
    --max-num-workers=10 \
    --autoscaling-policy=my-autoscaling-policy

Advanced Cluster Configuration

# Create cluster with initialization actions
gcloud dataproc clusters create my-advanced-cluster \
    --region=us-central1 \
    --master-machine-type=n1-standard-8 \
    --worker-machine-type=n1-standard-8 \
    --num-workers=5 \
    --image-version=2.1-debian \
    --initialization-actions=gs://my-bucket/init-script.sh \
    --properties=spark:spark.dynamicAllocation.enabled=true \
    --properties=yarn:yarn.nodemanager.resource.memory-mb=12288 \
    --properties=spark:spark.executor.memory=8g \
    --properties=spark:spark.executor.cores=4

Python Client Library

python
from google.cloud import dataproc_v1 as dataproc
import time

def create_cluster(project_id, region, cluster_name):
    """Create a Dataproc cluster."""
    client = dataproc.ClusterControllerClient(
        client_info=dataproc.gapic.transports.cluster_controller_transports.ClusterControllerGrpcTransport
    )
    
    cluster = {
        'project_id': project_id,
        'cluster_name': cluster_name,
        'config': {
            'master_config': {
                'num_instances': 1,
                'machine_type_uri': 'n1-standard-4',
                'disk_config': {
                    'boot_disk_type': 'pd-ssd',
                    'boot_disk_size_gb': 100
                }
            },
            'worker_config': {
                'num_instances': 3,
                'machine_type_uri': 'n1-standard-4',
                'disk_config': {
                    'boot_disk_type': 'pd-standard',
                    'boot_disk_size_gb': 100
                }
            },
            'software_config': {
                'image_version': '2.1-debian',
                'properties': {
                    'spark:spark.dynamicAllocation.enabled': 'true',
                    'spark:spark.shuffle.service.enabled': 'true'
                }
            },
            'initialization_actions': [
                {
                    'executable_file': 'gs://my-bucket/init-script.sh'
                }
            ]
        }
    }
    
    operation = client.cluster(
        request={'project_id': project_id, 'region': region, 'cluster': cluster}
    )
    
    return operation.result()

# Create cluster
create_cluster('my-project', 'us-central1', 'my-cluster')

Image Versions

Dataproc uses image versions that bundle specific versions of Spark, Hadoop, and other components.

Pinning the image version matters because the image is a compatibility contract: it fixes the Spark major version, the Scala binary version that native jars must match, the Hive metastore schema, and the Python interpreter on the path. A job written against Spark 3.3 will not necessarily run on an image that ships Spark 2.4, and a jar compiled for Scala 2.11 will fail to link against an image built for 2.12. Cluster images also receive periodic component updates within a version line, so an image version is a floor rather than an exact bill of materials.

The upgrade path is worth planning before it is needed. New Dataproc versions are released on a schedule and older ones are eventually retired, so a cluster created with an unversioned default can disappear under you. Choose a version explicitly, record it in infrastructure code, and test the job against the next version before the retirement window rather than during it. When the stock image cannot carry a dependency, build a custom image and reference it by image uri.

Supported Image Versions

Image VersionSparkHadoopHivePython
2.1-debian3.3.23.3.63.1.33.10
2.0-debian3.2.33.3.23.1.23.9
1.5-debian2.4.83.2.32.3.93.7
1.4-debian2.3.42.10.12.3.72.7

Using Image Versions

# Specify image version
gcloud dataproc clusters create my-cluster \
    --image-version=2.1-debian \
    --region=us-central1

# Use custom image
gcloud dataproc clusters create my-cluster \
    --image-uri=projects/my-project/global/images/my-custom-image \
    --region=us-central1

Preemptible VMs

Preemptible VMs are short-lived, lower-cost instances that can be preempted by GCP for system needs.

The economics are simple and the constraints are specific. Preemptible capacity is offered at a steep discount but can be reclaimed with a short notice window, and it is never guaranteed to be available at all. That makes it appropriate for worker nodes running a fault-tolerant Spark job, because Spark retries lost executors, and inappropriate for the master node, whose loss takes the whole cluster with it. The recommended shape is therefore a small number of on-demand workers carrying the baseline with a larger pool of preemptible workers absorbing the burst.

Two settings make the pattern work in practice. Spark's dynamic allocation lets executors grow into the preemptible pool and shrink when it disappears, and YARN's node labels or Dataproc's secondary worker group can keep preemptible capacity isolated from baseline capacity. Budget with the assumption that some fraction of preemptible capacity will vanish mid-run, so the job must be correct when a stage is recomputed.

Preemptible VMs are short-lived, lower-cost instances that can be preempted by GCP for system needs.

Configuring Preemptible Workers

# Create cluster with preemptible workers
gcloud dataproc clusters create my-cluster \
    --num-workers=10 \
    --num-preemptible-workers=5 \
    --worker-machine-type=n1-standard-4 \
    --preemptible-worker-boot-disk-size=100 \
    --region=us-central1

Preemptible VM Configuration

python
# Configure preemptible workers
cluster = {
    'config': {
        'worker_config': {
            'num_instances': 10,
            'machine_type_uri': 'n1-standard-4',
            'is_preemptible': True,
            'disk_config': {
                'boot_disk_size_gb': 100,
                'num_local_ssds': 0
            }
        },
        'autoscaling_config': {
            'policy_uri': 'projects/my-project/regions/us-central1/autoscalingPolicies/my-policy'
        }
    }
}

Cost Optimization

python
# Monitor preemptible VM usage
from google.cloud import monitoring_v3
import time

def get_preemptible_usage(project_id, cluster_name):
    """Get preemptible VM usage metrics."""
    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{project_id}"
    
    interval = monitoring_v3.TimeInterval()
    interval.end_time = time.time()
    interval.start_time = time.time() - 3600  # Last hour
    
    results = client.list_time_series(
        request={
            'name': project_name,
            'filter': f'resource.label.cluster_name = "{cluster_name}" AND metric.type = "compute.googleapis.com/instance/preempted"',
            'interval': interval,
            'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
        }
    )
    
    for result in results:
        print(f'Preempted instances: {result.points[0].value.int64_value}')

Initialization Actions

Initialization actions are scripts that run on cluster nodes during cluster setup.

They run on every node, master and workers alike, and the cluster does not report healthy until they finish, which turns a slow script into a slow cluster start. That makes two properties non-negotiable: the script must be idempotent, because a retry runs it again, and it must be fast, because it sits on the critical path of every cluster creation. Anything heavy belongs in a custom image instead, so it is baked once rather than repeated on every boot.

The most common legitimate uses are installing a Python package that is not on the image, registering a Hive metastore, dropping a configuration file into place, or enabling a connector. Guard each with a check so a rerun is a no-op, write progress to a log that Dataproc captures, and keep the script in version control next to the cluster definition rather than in a bucket path nobody can diff.

Initialization actions are scripts that run on cluster nodes during cluster setup.

Creating Initialization Actions

#!/bin/bash
# init-script.sh - Install additional packages on cluster nodes

# Update package list
sudo apt-get update -y

# Install Python packages
pip install pandas numpy scikit-learn

# Install custom Spark packages
/opt/spark/bin/spark-shell --packages org.apache.spark:spark-avro_2.12:3.3.2

# Configure Spark
echo 'spark.executor.memory=8g' >> /etc/spark/conf/spark-defaults.conf
echo 'spark.executor.cores=4' >> /etc/spark/conf/spark-defaults.conf
echo 'spark.dynamicAllocation.enabled=true' >> /etc/spark/conf/spark-defaults.conf

# Mount additional storage
sudo mount -o discard,defaults /dev/sdb /mnt/scratch

Using Initialization Actions

# Upload initialization action to GCS
gsutil cp init-script.sh gs://my-bucket/init-script.sh

# Use initialization action when creating cluster
gcloud dataproc clusters create my-cluster \
    --initialization-actions=gs://my-bucket/init-script.sh \
    --region=us-central1

# Multiple initialization actions
gcloud dataproc clusters create my-cluster \
    --initialization-actions=gs://my-bucket/script1.sh,gs://my-bucket/script2.sh \
    --region=us-central1

Initialization Action Best Practices

python
# Best practices for initialization actions
best_practices = {
    'idempotency': 'Scripts should be idempotent and handle reruns',
    'error_handling': 'Implement proper error handling and logging',
    'timeout': 'Keep initialization actions under 10 minutes',
    'testing': 'Test initialization actions before production use',
    'logging': 'Use consistent logging for debugging',
    'dependencies': 'Check for dependencies before installing'
}

# Example initialization action with error handling
script = '''#!/bin/bash
set -e  # Exit on error

echo "Starting initialization..."

# Check if package is already installed
if ! dpkg -l | grep -q "package-name"; then
    sudo apt-get update
    sudo apt-get install -y package-name
fi

# Verify installation
if command -v package-name &> /dev/null; then
    echo "Package installed successfully"
else
    echo "Failed to install package"
    exit 1
fi
'''

Spark on Dataproc

Running Spark here means choosing between three submission styles, and the choice affects both latency and cost. Submitting a job to a long-lived cluster is the cheapest per job because the cluster is already warm, but it bills for the idle time between jobs. Creating a cluster per job through the Dataproc jobs API bills only while the work runs, at the price of a cluster startup on every invocation. Dataproc Serverless for Apache Spark removes the cluster entirely and bills by the second for the resources the job actually requests, which is the best fit for jobs whose size varies.

Whichever route you take, the tuning knobs are the same: partition count for shuffle sizing, executor memory relative to the data held in memory, and the number of shuffle partitions after a wide aggregation. Oversized executors waste memory to garbage collection, and undersized ones spill to disk, so measure the input size per partition before choosing rather than copying values from another workload.

Running Spark Jobs

# Submit Spark job
gcloud dataproc jobs submit spark \
    --cluster=my-cluster \
    --region=us-central1 \
    --class=org.apache.spark.examples.SparkPi \
    --jars=gs://spark-samples/spark-pi.jar

# Submit PySpark job
gcloud dataproc jobs submit pyspark \
    --cluster=my-cluster \
    --region=us-central1 \
    gs://my-bucket/my-spark-job.py

# Submit with dependencies
gcloud dataproc jobs submit pyspark \
    --cluster=my-cluster \
    --region=us-central1 \
    --py-files=gs://my-bucket/dependencies.zip \
    --packages=org.apache.spark:spark-avro_2.12:3.3.2 \
    gs://my-bucket/my-job.py

Spark Configuration

python
# Spark job configuration
from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName("My Dataproc Job") \
    .config("spark.executor.memory", "8g") \
    .config("spark.executor.cores", "4") \
    .config("spark.dynamicAllocation.enabled", "true") \
    .config("spark.shuffle.service.enabled", "true") \
    .config("spark.sql.shuffle.partitions", "200") \
    .config("spark.default.parallelism", "200") \
    .getOrCreate()

# Read data from GCS
df = spark.read.parquet("gs://my-bucket/data/*.parquet")

# Process data
result = df.groupBy("category").agg({"amount": "sum"})

# Write to BigQuery
result.write \
    .format("bigquery") \
    .option("table", "my-project:analytics.summary") \
    .option("writeDisposition", "WRITE_APPEND") \
    .save()

Spark SQL

-- Spark SQL on Dataproc
CREATE TEMPORARY VIEW sales
USING parquet
OPTIONS (
  path "gs://my-bucket/sales/*.parquet"
);

-- Analyze data
SELECT
  category,
  SUM(amount) as total_sales,
  COUNT(*) as transaction_count
FROM sales
WHERE sale_date >= '2024-01-01'
GROUP BY category
ORDER BY total_sales DESC;

Auto-scaling

Auto-scaling dynamically adjusts the number of worker nodes based on workload.

The policy reads YARN resource demand, so it reacts to queued containers rather than to CPU percentage, which is the right signal for Spark but means an idle cluster still keeps its minimum. The parameters that matter are the minimum and maximum bounds, the cooldown period between decisions, and the scale-down delay after demand falls. Set the minimum to zero only for clusters that are created per job, because a minimum of zero on a long-lived cluster turns every job into a cold start.

Autoscaling also interacts with preemptible capacity: secondary workers can scale independently, so the baseline stays small and the elastic portion comes from the discounted pool. The trap is a scale-up that cannot be satisfied because preemptible capacity is unavailable in the zone, which shows up as a cluster stuck in a resizing state rather than as an error. Keep a modest on-demand floor and let the policy burst above it.

Creating Autoscaling Policies

# Create autoscaling policy
gcloud dataproc autoscaling-policies import my-policy \
    --source=policy.yaml \
    --region=us-central1

Autoscaling Policy Configuration

# policy.yaml
autoscalingPolicy:
  basicAlgorithm:
    yarnConfig:
      gracefulDecommissionTimeout: "3600s"
      scaleUpFactor: 1.0
      scaleDownFactor: 1.0
    cooldownPeriod: "300s"
  workerConfig:
    minInstances: 2
    maxInstances: 10
  secondaryWorkerConfig:
    minInstances: 0
    maxInstances: 5

Auto-scaling Monitoring

python
# Monitor autoscaling
from google.cloud import dataproc_v1 as dataproc

def get_cluster_status(project_id, region, cluster_name):
    """Get cluster status including autoscaling."""
    client = dataproc.ClusterControllerClient()
    
    cluster = client.get_cluster(
        request={
            'project_id': project_id,
            'region': region,
            'cluster_name': cluster_name
        }
    )
    
    print(f'Cluster status: {cluster.status.state}')
    print(f'Master nodes: {cluster.config.master_config.num_instances}')
    print(f'Worker nodes: {cluster.config.worker_config.num_instances}')
    print(f'Secondary workers: {cluster.config.secondary_worker_config.num_instances}')
    
    if cluster.config.autoscaling_config:
        print(f'Autoscaling policy: {cluster.config.autoscaling_config.policy_uri}')

GCS Integration

Dataproc integrates seamlessly with Google Cloud Storage for data storage.

The GCS connector exposes buckets through the Hadoop filesystem API, so paths such as gs://bucket/path work in Spark, Hive, and Hadoop commands without a mount step. That removes HDFS from the critical path: worker disks shrink to shuffle space, nodes can be deleted without copying data out, and a cluster can be recreated against the same bucket with no migration. The trade-off is that object storage has higher per-operation latency than local disk, so many small files cost more to read than fewer large ones, and compaction before a job is worth the minute it takes.

Connector configuration is applied at cluster creation through properties, and authentication rides on the instance's service account, which keeps credentials out of code entirely. For teams that want local filesystem semantics for checkpoints, the gcsfuse utility can mount a bucket into the instance, though the connector remains the faster path for bulk reads.

Using GCS as HDFS

python
# Read from GCS using Spark
df = spark.read.parquet("gs://my-bucket/data/*.parquet")

# Write to GCS
df.write.parquet("gs://my-bucket/output/")

# Use GCS as primary storage
spark.conf.set("fs.gs.impl", "com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem")
spark.conf.set("fs.gs.auth.service.account.json.keyfile", "/path/to/key.json")

GCS Connector Configuration

# Configure GCS connector
gcloud dataproc clusters create my-cluster \
    --properties=google.cloud.dataproc.spark.dataproc.gcs.connector.enabled=true \
    --properties=fs.gs.impl=com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem

Monitoring and Debugging

Debugging a Spark job on a managed cluster starts with the driver log rather than the node. Dataproc captures stdout and stderr for every job and exposes them through the jobs API and the console, and the driver log is where the real error lives, because executor failures are usually reported there as a wrapped cause. Cloud Logging can filter on the cluster name, and the YARN and Spark history servers fill in what happened after the fact.

The metrics worth watching are cluster CPU and memory alongside the job queue depth, because a cluster at full CPU with an empty queue is simply oversized, while a growing queue at low CPU means the bottleneck is a single-threaded stage or an external dependency such as a rate-limited API. Tailing the wrong metric is the common wasted hour, so identify whether the constraint is compute, shuffle, or I/O before changing a single executor setting.

Cluster Monitoring

python
# Monitor cluster health
from google.cloud import monitoring_v3
import time

def monitor_cluster(project_id, cluster_name):
    """Monitor Dataproc cluster metrics."""
    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{project_id}"
    
    # Monitor YARN metrics
    interval = monitoring_v3.TimeInterval()
    interval.end_time = time.time()
    interval.start_time = time.time() - 3600
    
    results = client.list_time_series(
        request={
            'name': project_name,
            'filter': f'resource.label.cluster_name = "{cluster_name}" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
            'interval': interval,
            'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
        }
    )
    
    for result in results:
        print(f'CPU utilization: {result.points[0].value.double_value}')

Debugging Common Issues

# Check cluster logs
gcloud dataproc clusters describe my-cluster --region=us-central1

# Access Spark History Server
gcloud compute ssh my-cluster-m --zone=us-central1-a -- -L 18080:localhost:18080

# Check YARN logs
gcloud compute ssh my-cluster-m --zone=us-central1-a -- -L 8088:localhost:8088

# View HDFS status
gcloud compute ssh my-cluster-m --zone=us-central1-a -- -L 9870:localhost:9870

Best Practices

Most Dataproc cost and reliability problems come from a handful of habits rather than from anything exotic. Create clusters for the work and delete them when the work is done, keep data in GCS instead of copying it into HDFS, size executors from the measured partition size, and pin the image version in code. Everything else is tuning, and tuning rarely rescues a cluster that should not have been running in the first place.

  1. Use appropriate image versions - Match versions to your workload requirements
  2. Implement auto-scaling - Optimize costs with dynamic scaling
  3. Use preemptible VMs - Reduce costs for fault-tolerant workloads
  4. Leverage GCS integration - Use GCS as primary storage for flexibility
  5. Monitor cluster health - Track metrics and set up alerts
  6. Optimize Spark configuration - Tune memory, cores, and parallelism
  7. Use initialization actions - Customize clusters for your specific needs

Common Mistakes

Leaving an interactive cluster running overnight

Fix: Set an auto-deletion timeout or create the cluster per job, because idle VMs usually cost more than the jobs they run.

Replicating data into HDFS when it already lives in GCS

Fix: Read and write through the GCS connector so disks stay small and clusters stay disposable.

Putting preemptible workers in the primary worker group

Fix: Keep a small on-demand baseline and place preemptible capacity in secondary workers so a reclamation cannot empty the cluster.

Best Practices

  • Pin the image version in infrastructure code and test upgrades before retirement windows
  • Size executors from measured partition size rather than from another team's configuration
  • Use Dataproc Serverless for jobs whose size varies, so cluster lifetime stops mattering
  • Read logs through the jobs API and Cloud Logging instead of SSH-ing into nodes

Key Takeaways

  • A Dataproc cluster bills while it exists, so lifetime policy beats almost every other cost control
  • The GCS connector makes HDFS optional and turns clusters into disposable compute
  • Preemptible workers plus dynamic allocation is the standard cost shape, with an on-demand floor
  • Image version is a compatibility contract covering Spark, Scala, and Hive together

Interview Questions

Q1: Dataproc or Dataflow for a new pipeline?

Choose Dataflow for portable, serverless pipelines with unified batch and streaming semantics and no cluster to manage. Choose Dataproc when the workload is existing Spark or Hive code, needs a specific library version, or benefits from an interactive cluster during development.

Q2: How do you reduce a Dataproc bill without changing the job?

Delete clusters when idle or create them per job, set a minimum autoscaling bound of zero where possible, move bulk data reads to GCS instead of HDFS, and shift fault-tolerant workers to preemptible capacity. Those four changes usually dominate any code-level optimisation.

Q3: What does an initialization action guarantee?

It runs the given script on every node during cluster creation and the cluster stays in a creating state until it finishes. It must therefore be idempotent and fast; heavier setup belongs in a custom image baked once rather than executed on every boot.

Q4: When would you use Dataproc Serverless?

When jobs are intermittent or vary widely in size and you do not want to pay for a cluster between runs. It bills by the second for requested resources, removes cluster management, and still runs the same Spark code with minimal changes.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement