8 minute read

Dataproc removes much of the work of provisioning Hadoop and Spark, but it does not remove the need to design a batch system. Predictable completion depends on how data is partitioned in Google Cloud Storage, how much shuffle a query produces, whether joins are intentionally broadcast or partitioned, and how a failed run is retried without publishing duplicate or partial output.

Spark batch processing on Dataproc architecture

Choose a cluster only after defining the workload

Start with one representative input window and record:

  • compressed and uncompressed bytes;
  • input files, rows, and average file size;
  • shuffle write and read bytes;
  • stage duration and maximum concurrent tasks;
  • output files and their distribution;
  • peak driver, executor, and Python-worker memory.

These measurements distinguish a scan-limited workload from a shuffle- or join-limited workload. A tenfold increase in machines cannot correct a ten-to-one partition skew, and a memory-optimized worker does not make 50,000 tiny GCS objects cheap to list.

A Dataproc job can run on a persistent cluster, an ephemeral workflow cluster, or Dataproc Serverless for Spark. Use a persistent cluster when job concurrency or reusable initialization materially reduces total runtime and the operating team actually scales and terminates idle capacity. Prefer an ephemeral cluster when isolation and reproducibility are more important than cache reuse. Use Serverless when the workload benefits from automatic infrastructure lifetime and can stay within its networking, connector, logging, and supported-runtime model.

The selection should be made with successful-job cost:

successful-job cost
  = cluster or serverless compute
  + storage and storage operations
  + data transfer and BigQuery scan/load cost
  + retries
  + operator time for failures

An always-on cluster has to include its idle periods in that calculation. A serverless job has to include repeated connector startup and less direct control over the underlying nodes.

Lay out Google Cloud Storage for pruning and atomic publication

Partition prefixes to match useful filters:

gs://example-lake/bronze/orders/
  event_date=2022-01-18/region=us/
  event_date=2022-01-18/region=eu/
  event_date=2022-01-19/region=us/

Date, region, or another bounded low-cardinality dimension can help. Customer ID usually is not a good physical prefix because it creates huge numbers of small partitions and excessive metadata. A single object name should not encode every possible query; partition columns should represent the main scan boundaries.

Write to a run-specific staging location:

gs://example-lake/silver/revenue/_staging/run_id=20220119-01/

Validate counts and aggregates before exposing the output. Plain GCS objects are durable but not a transactional directory. If readers discover partial files, the run is not atomically published. Use a manifest, BigQuery table load, partition-aware replacement, or a transactional table format for the publication boundary.

For Parquet, a first production target is 128 to 512 MiB per file. Tiny objects increase task setup and object listing overhead; files many gigabytes in size constrain parallelism and replay granularity.

Create an ephemeral cluster with explicit properties

Use cluster labels, a regional subnet, only the required scopes, and a service account with object and logging permissions for the job. The regional subnet must also reach any private BigQuery or service endpoints required by the environment.

gcloud dataproc clusters create daily-spark \
  --region=us-central1 \
  --zone=us-central1-a \
  --image-version=2.0-debian10 \
  --master-machine-type=n2-standard-8 \
  --worker-machine-type=n2-highmem-8 \
  --num-workers=8 \
  --secondary-worker-type=preemptible \
  --num-secondary-workers=16 \
  --service-account=dataproc-jobs@PROJECT_ID.iam.gserviceaccount.com \
  --subnet=projects/PROJECT_ID/regions/us-central1/subnetworks/data \
  --no-address \
  --labels=environment=prod,workload=daily-revenue \
  --properties='spark:spark.serializer=org.apache.spark.serializer.KryoSerializer,spark:spark.sql.adaptive.enabled=true,spark:spark.sql.shuffle.partitions=800'

Preemptible secondary workers can lower cost but are not failure-free capacity. Ensure source inputs are durable in GCS, enable enough primary workers to make progress, and retry a Dataproc job under a clear attempt policy. For a stateful long stage, losing too many preemptible workers can cost more than the discount saves.

The gcloud properties above are a starting profile, not a substitute for executor sizing. Set executor memory and cores with enough overhead for PySpark, connectors, and native allocations. Avoid Xmx-only thinking: the total container or VM memory must include Spark memory, JVM metaspace, direct buffers, Python, and the operating system.

Size executors and partitions around tasks

A practical first approximation for 1.6 TiB of compressed Parquet is:

input tasks ~= input bytes / max partition bytes
             ~= 1.6 TiB / 128 MiB
             ~= 12,800 tasks

executor slots ~= executors x cores
shuffle partitions ~= max(2 x slots, shuffle bytes / 128 MiB)

Adaptive Query Execution coalesces shuffle partitions after shuffle, and skew join handling can divide a large partition. Neither feature replaces a good key distribution. If one customer accounts for 70 percent of input, salting or pre-aggregation is necessary.

A realistic PySpark job follows:

import argparse

from pyspark.sql import SparkSession, functions as F


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--input-date", required=True)
    parser.add_argument("--run-id", required=True)
    parser.add_argument("--bucket", default="example-lake")
    return parser.parse_args()


args = parse_args()
spark = (
    SparkSession.builder.appName(f"daily-revenue-{args.run_id}")
    .config("spark.sql.adaptive.enabled", "true")
    .config("spark.sql.adaptive.coalescePartitions.enabled", "true")
    .config("spark.sql.adaptive.skewJoin.enabled", "true")
    .config("spark.sql.files.maxPartitionBytes", str(128 * 1024 * 1024))
    .config("spark.sql.shuffle.partitions", "800")
    .getOrCreate()
)

orders_path = f"gs://{args.bucket}/bronze/orders/event_date={args.input_date}"
customers_path = f"gs://{args.bucket}/reference/customers"
stage_path = (
    f"gs://{args.bucket}/silver/revenue/_staging/"
    f"run_id={args.run_id}/event_date={args.input_date}"
)

orders = (
    spark.read.parquet(orders_path)
    .where("amount_cents >= 0")
    .select("order_id", "customer_id", "amount_cents", "event_ts")
)

customers = (
    spark.read.parquet(customers_path)
    .select("customer_id", "country_code")
)

daily = (
    orders.groupBy("customer_id")
    .agg(
        F.sum("amount_cents").alias("revenue_cents"),
        F.countDistinct("order_id").alias("order_count"),
    )
    .join(F.broadcast(customers), "customer_id", "left")
    .withColumn("event_date", F.lit(args.input_date).cast("date"))
    .select(
        "event_date",
        "customer_id",
        "country_code",
        "revenue_cents",
        "order_count",
    )
)

daily.write.mode("overwrite").option("compression", "zstd").parquet(stage_path)

counts = daily.agg(
    F.count("*").alias("row_count"),
    F.coalesce(F.sum("revenue_cents"), F.lit(0)).alias("revenue_cents"),
).first()
print({"run_id": args.run_id, **counts.asDict()})

The explicit broadcast is safe only while the dimension fits comfortably in the Spark driver and every executor. A reference dataset that is 2 GiB on disk can expand in memory. Remove the hint after it outgrows the memory budget; the default join then becomes an intentional sort-merge join.

Avoid a Python UDF in the hot row path if a Catalyst expression exists. PyUDF work crosses the Python boundary and adds serialization and worker-memory costs. Pandas UDFs can be appropriate for vectorized transformations but still require an explicit Python memory budget.

Control shuffle and skew

The Spark UI should validate decisions:

  • do input tasks use most executor slots without exploding in count;
  • is one shuffle stage responsible for most elapsed time;
  • does one task process substantially more bytes or records than the median;
  • do executors spill memory to disk;
  • does the output have an acceptable file count and size.

For a skewed account dimension, add a deterministic salt to the heavy side, replicate the small side when semantically safe, aggregate, and remove the salt:

orders = orders.withColumn(
    "salt",
    F.when(F.col("customer_id").isin("HOT-1", "HOT-2"),
           F.pmod(F.hash("order_id"), F.lit(32)))
     .otherwise(F.lit(0))
)

by_salt = orders.groupBy("customer_id", "salt").agg(
    F.sum("amount_cents").alias("revenue_cents"),
    F.countDistinct("order_id").alias("order_count")
)

result = by_salt.groupBy("customer_id").agg(
    F.sum("revenue_cents").alias("revenue_cents"),
    F.sum("order_count").alias("order_count")
)

countDistinct is itself shuffle-heavy. If the exact source guarantees order_id uniqueness, a count is sufficient. If exact distinctness is a requirement, keep the shuffle and measure it rather than silently accepting a lossy approximate number.

Load BigQuery intentionally

The Spark BigQuery connector can read a BigQuery table into Spark or use BigQuery as a sink. It exchanges an optimized Arrow/Avro representation and uses BigQuery Storage and load infrastructure underneath. Connector classes and supported Dataproc versions must be kept together; do not mix arbitrary Maven coordinates into an old image.

Read only selected columns and predicates:

customers = (
    spark.read.format("bigquery")
    .option("table", "PROJECT_ID.analytics.customers")
    .option("filter", "status = 'active'")
    .load()
    .select("customer_id", "country_code")
)

For a run-sized result, writing into a staging table is safer than a direct overwrite of a production table:

daily.write.format("bigquery") \
    .option("table", "PROJECT_ID.analytics_stage.daily_revenue_20220119") \
    .option("temporaryGcsBucket", "example-dataproc-temp") \
    .option("writeMethod", "direct") \
    .mode("overwrite") \
    .save()

Validate the staging relation and publish it with an explicit partition replacement or query. BigQuery table writes do not share a Spark transaction with a GCS manifest. The publication procedure must define which system is authoritative and how downstream readers detect run_id.

For narrow, partition-aligned BigQuery extracts, push filters to BigQuery. For a large join repeated in many jobs, materializing the result in GCS is often cheaper than rescanning BigQuery on every run.

Submit, observe, and retry

Submit the Python artifact and options with gcloud:

gcloud dataproc jobs submit pyspark \
  gs://example-code/jobs/daily_revenue.py \
  --region=us-central1 \
  --cluster=daily-spark \
  --properties='spark.executor.instances=32,spark.executor.cores=4,spark.executor.memory=16g,spark.executor.memoryOverhead=4g,spark.dynamicAllocation.enabled=false' \
  -- \
  --input-date=2022-01-18 \
  --run-id=20220119-retry-02

Disable dynamic allocation when a deterministic capacity envelope is required, or enable and measure it for variable workloads. A fixed executor number is easier to reproduce for a benchmark; dynamic allocation may reduce idle tails but can change behavior after executors are lost.

A serverless submission keeps the application interface similar:

gcloud dataproc batches submit pyspark \
  gs://example-code/jobs/daily_revenue.py \
  --region=us-central1 \
  --batch=daily-revenue-20220119 \
  --service-account=dataproc-jobs@PROJECT_ID.iam.gserviceaccount.com \
  --subnet=projects/PROJECT_ID/regions/us-central1/subnetworks/data \
  -- \
  --input-date=2022-01-18 \
  --run-id=20220119-serverless-01

Capture the job ID, run ID, application artifact hash, image/runtime version, configuration, input prefixes, output prefix, and expected volume in the job record. On a failure, preserve the Spark driver and event logs, identify failed stages and external side effects, and retry into a new staging path.

A retry should not append to yesterday’s output:

gsutil -m rm -r \
  "gs://example-lake/silver/revenue/_staging/run_id=failed-run/**" || true

Use an orchestrator-owned cleanup with an explicit dry run in production. Object deletion is irreversible unless the bucket has object versioning and a validated restore process. If the destination is BigQuery or another upsert sink, make the operation idempotent by business key and run ID rather than relying on directory cleanup.

Make cost and reliability visible

Report at least:

  • GiB read, GiB shuffled, and GiB produced;
  • driver, worker, and serverless runtime hours;
  • preemptible interruptions;
  • input and output operation counts;
  • median and p95 stage duration;
  • retries per successful logical batch;
  • cost per successful input TiB and output partition;
  • BigQuery bytes scanned and slot or load cost.

Budget alerts should trigger on a trend before the monthly invoice. Set a per-run dollar or runtime threshold in the orchestrator, but allow a reviewed override for known backfills.

An SLO can state that 99 percent of daily partitions finish by 06:00 with no more than one retry. Alert at 03:00 if less than half the input has completed, and page on failed output validation rather than on a single transient worker loss.

The release is ready when a non-production run demonstrates stage shape, output sizing, BigQuery publication, a worker interruption, and a clean rerun. The fastest single pass is not necessarily the most valuable production design; predictable reruns and controlled publication are part of performance.