E-NO
Apache Spark upgrade 7 Min Read

Apache Spark Upgrade and Migration: A Practical Operational Guide

calendar_today Published: 2026-10-21
update Last Updated: 2026-10-21
analytics SEO Efficiency: 100%
Technical guide illustration for Apache Spark Upgrade and Migration: A Practical Operational Guide.

Intro

Upgrading Apache Spark is rarely just swapping a JAR. It touches your build, cluster topology, serialization defaults, SQL behavior, and the downstream systems that feed or consume your jobs. This guide is written for developers, DevOps consultants, and technical startup teams who need a repeatable upgrade path: observe the current version, size the change, execute with a rollback plan, and verify with concrete commands rather than hope.

We focus on the operational workflow: version inventory, configuration changes, verification, failure recovery, and a pre-flight checklist. Examples use explicit placeholders such as <your-spark-home> and <driver-host> so you can adapt them without pasting secrets into documentation. Where relevant, we note interactions with Kafka, HDFS, and Apache Airflow, but only when they affect compatibility, security, observability, or recovery.

Version and Environment Inventory

Before touching any configuration, create an inventory of the current Spark distribution and the environment it runs in. This is the single most important step: a wrong assumption about the version or topology turns a minor upgrade into an unplanned outage.

Read-only discovery commands

First, record the Spark version and the components that matter. Run these from a node that can submit jobs, using the same environment variables your production jobs use.

# Spark version
spark-submit --version

# Java version Spark is running on
java -version

# Spark home and executable path
which spark-submit
ls -l $(which spark-submit)

Expected output for spark-submit --version includes a banner like:

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 3.4.1
      /_/

Using Scala version 2.12.17, Java 11.0.20 (Eclipse Adoptium)

If you run Spark on Kubernetes, YARN, or Mesos, document the cluster manager and the submission mode. A read-only check for YARN client mode:

yarn application -list -appStates RUNNING

For Kubernetes:

kubectl get pods -l spark-role=driver -n <your-namespace>

Capturing topology and dependencies

The upgrade path depends on where state lives. Check for external shuffle service, HDFS compatibility, and the location of spark-defaults.conf.

# Find configuration files
find /opt/spark/conf -name "*.conf" -o -name "*.properties" 2>/dev/null

# List HDFS compatibility mode or scheme
hdfs getconf -confKey fs.defaultFS
hdfs version

Record the output in a timestamped file. A good practice is to create a migration notes file:

{
  echo "Inventory: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  spark-submit --version 2>&1 | grep -E "version|Using Scala"
  java -version 2>&1 | head -1
  yarn version 2>/dev/null || true
} | tee spark-upgrade-inventory.txt

Minimum justified change

Once you know the current version, define the smallest version delta that resolves a known issue or unlocks a required feature. For example, if you are on Spark 3.2.1 and need the pandas API improvements in 3.3.0, do not jump to 3.5.0 unless you have tested the intermediate breaking changes. List the breaking changes for each intermediate version from the official release notes and validate each one against your jobs.

Safe Configuration Path

Configuration changes during an upgrade should be additive and reversible. Start by comparing the new distribution's default configuration with your existing overrides. Many production clusters carry long-standing custom settings that are either obsolete or incompatible with the new version.

Diff your configuration

Download the new Spark distribution and compare its spark-defaults.conf.template with your current spark-defaults.conf. The template contains only defaults and serves as a clean baseline.

# Assuming new Spark is extracted at /opt/spark-3.4.1
cp /opt/spark-3.4.1/conf/spark-defaults.conf.template /tmp/new-defaults.conf
diff -u /opt/spark-current/conf/spark-defaults.conf /tmp/new-defaults.conf | head -n 80

Look for keys you have overridden that no longer appear in the template, or whose default value has changed. For example, Spark 3.0 changed the default value of spark.sql.legacy.timeParserPolicy from EXCEPTION to CORRECTED. If your jobs rely on EXCEPTION behavior for malformed timestamps, you must explicitly set it back.

# spark-defaults.conf (override to preserve pre-3.0 behavior)
spark.sql.legacy.timeParserPolicy EXCEPTION

Environment variable scope

Never put secrets in spark-defaults.conf. Use environment variables or secret managers for credentials. For example, when connecting to Kafka over TLS:

# Instead of hardcoding in spark-defaults.conf, export before spark-submit
export KAFKA_SSL_KEYSTORE_LOCATION=/etc/security/kafka/keystore.jks
export KAFKA_SSL_KEYSTORE_PASSWORD=$(cat /run/secrets/kafka_keystore_password)

spark-submit \
  --conf spark.executorEnv.KAFKA_SSL_KEYSTORE_LOCATION=$KAFKA_SSL_KEYSTORE_LOCATION \
  --conf spark.executorEnv.KAFKA_SSL_KEYSTORE_PASSWORD=$KAFKA_SSL_KEYSTORE_PASSWORD \
  ...

One change at a time

After every configuration change, run a minimal job that exercises the affected code path. For example, if you change spark.sql.shuffle.partitions, run a small aggregation query and confirm the number of output partitions.

spark-sql -e "SELECT count(*) FROM parquet.`/data/sample_table`"

Then inspect the Spark UI to verify the plan and shuffle partitions. If the change causes an error, revert the single line and rerun to confirm recovery.

Verification and Diagnostics

Verification answers two questions: does the upgraded cluster behave as expected, and does it fail loudly when something is wrong. Define expected signals before running the upgrade so you have something to compare against.

Baseline before upgrade

Create a baseline job output on the current version and store its metrics. For example, for a streaming job that ingests from Kafka and writes to HDFS:

# Save current metrics
spark-submit --class com.example.MetricsJob \
  --master yarn --deploy-mode cluster \
  your-app-baseline.jar \
  --kafka.bootstrap.servers <bootstrap-servers> \
  --output /tmp/baseline-metrics.json

Expected output in /tmp/baseline-metrics.json:

{
  "avgBatchDurationMs": 2100,
  "recordsPerSecond": 1420,
  "shuffleReadBytes": 180000000
}

Post-upgrade comparison

After upgrading Spark, run the same job with the same inputs and compare the metrics. A helper script can diff the JSON files:

python - <<'PY'
import json, sys
with open('/tmp/baseline-metrics.json') as f:
    baseline = json.load(f)
with open('/tmp/post-upgrade-metrics.json') as f:
    post = json.load(f)
for key in baseline:
    old = baseline[key]
    new = post.get(key)
    if old != new:
        pct = ((new - old) / old) * 100 if old else 0
        print(f"{key}: {old} -> {new} ({pct:+.1f}%)")
PY

A healthy upgrade should show no regression in throughput and no increase in error rates. If latency increases by more than 20%, investigate before promoting the upgrade.

Diagnostic commands

When something looks off, use the Spark event logs and driver/executor logs. Enable event logging in spark-defaults.conf:

spark.eventLog.enabled true
spark.eventLog.dir hdfs:///spark-history

Then run a job and open the Spark History Server UI at http://<driver-host>:18080. For programmatic diagnostics, query the REST API:

curl -s http://<driver-host>:4040/api/v1/applications | jq '.[0].attempts[0].completed'

To check executor stderr for a specific application, use YARN logs:

yarn logs -applicationId application_<timestamp>_<id> | grep -i -E "exception|error" | head -n 50

Failure Modes and Recovery

Even a well-planned upgrade can fail in production. The following are the most common failure modes I have seen, why they happen, and how to recover without guessing.

Failure 1: Classpath conflicts with older dependencies

Symptom: Job fails with NoSuchMethodError or ClassNotFoundException after upgrade. For example:

java.lang.NoSuchMethodError: org.apache.spark.sql.catalyst.expressions.Expression.nullIntolerant()Z

Why it happens: The application JAR bundles a Spark library from an older version or a third-party library compiled against a different Spark API. Spark's classloader precedence may load the wrong class.

Recovery: Use the Spark UI's Environment tab to inspect the classpath entries. Identify which JAR contains the conflicting class:

# After extracting the fat jar
jar tf your-app.jar | grep "spark-sql"

Then either exclude the transitive dependency in your build (e.g., Maven exclusions) or use spark.jars to provide the correct version. Rebuild and resubmit.

Failure 2: SQL behavior changes silently

Symptom: A query returns different results after upgrade, or begins writing different schemas. For example, Spark 3.0 changed the default behavior of spark.sql.storeAssignmentPolicy from ANSI to LEGACY, which can allow implicit type conversions that fail later.

Why it happens: SQL semantic and parser changes across Spark versions are documented but often overlooked. Queries that relied on old defaults keep running but produce wrong data.

Recovery: Compare query plans using EXPLAIN before and after. Set the relevant SQL config flag back to the previous version's default and rerun the job. If you cannot restore exact behavior, rewrite the query to be explicit about types and semantics.

Failure 3: External shuffle service incompatibility

Symptom: Jobs fail during shuffle with errors like Failed to connect to external shuffle service or Invalid shuffle block id.

Why it happens: The external shuffle service is a cluster-level component that must match the Spark version. If you upgrade Spark but the shuffle service binary is still from an older version, protocol mismatches occur.

Recovery: Check the shuffle service version on each node:

strings /path/to/spark-shuffle-service-binary | grep -i "version" | head -n 3

Upgrade the shuffle service alongside Spark, or disable external shuffle service temporarily for testing (not recommended for production) by setting spark.shuffle.service.enabled false in the job configuration.

Failure 4: Serialization changes with Java 11 or later

Symptom: NotSerializableException or task failures with UnsupportedOperationException after moving to Java 11 or 17.

Why it happens: Spark uses Java serialization or Kryo; newer JDKs change reflection and module access rules, breaking serialization proxies.

Recovery: Test your serialization setup with a tiny job that forces a closure capture. If Kryo is used, ensure the Kryo version is compatible with the new Java. Consider switching to Spark's built-in org.apache.spark.serializer.KryoSerializer with explicit class registration for better stability.

Common Pitfalls and How to Avoid Them

In addition to the failure modes above, these anti-patterns repeat across teams and can be prevented with simple discipline.

Pitfall 1: Upgrading without a rollback window

Teams often schedule an upgrade during a maintenance window but fail to define what "rollback" means. If the new Spark version corrupts data or causes unpredictable failures, you need a tested path back.

How to avoid: Before starting, perform a dry run of the rollback on a staging cluster. For example, if you use symlinks for spark-current, switching back is trivial:

# Current version is a symlink
ls -l /opt/spark-current -> /opt/spark-3.4.1
# Rollback commands
ln -sfn /opt/spark-3.3.2 /opt/spark-current
systemctl restart spark-history-server

Test the rollback and time it. Document the exact commands and the person responsible for executing them.

Pitfall 2: Ignoring deprecated configuration keys

Spark deprecates many configuration parameters. An upgrade may emit warnings that get ignored, but those warnings often point to behavior changes in the next major version.

How to avoid: After upgrading, scan job logs for deprecation warnings:

grep -i "deprecated" /var/log/spark/spark-submit.log | sort -u

For each deprecated key, find the replacement in the Spark documentation and update spark-defaults.conf or job code. Run one job with spark.deprecation.redirect set to true to see if any direct replacements exist.

Pitfall 3: Not validating data integrity after schema evolution

Spark SQL and DataFrame operations can change how they handle schema evolution across versions. For example, mergeSchema defaults changed between Spark 2.x and 3.x.

How to avoid: After an upgrade, run a validation job that compares row counts and checksums on critical tables before and after the upgrade. Use spark.sql.parquet.mergeSchema explicitly in your jobs to avoid ambiguity. A simple checksum comparison:

spark-sql -e "SELECT sum(cast(crc32(concat_ws('|', *)) as bigint)) FROM table" > pre_upgrade_checksum.txt
# after upgrade
spark-sql -e "SELECT sum(cast(crc32(concat_ws('|', *)) as bigint)) FROM table" > post_upgrade_checksum.txt
diff pre_upgrade_checksum.txt post_upgrade_checksum.txt

Operations Checklist

Use this checklist as a pre-flight and post-upgrade gate. Assign each item to a single responsible person and review progress weekly until the upgrade is stable.

#TaskOwnerFrequency / DueValidation signal
1Record current Spark version, Java version, cluster manager, and topology in migration notesPriya Shah, Engineering LeadOnce, before upgradespark-submit --version output stored in Git
2List all custom spark-defaults.conf overrides and compare with new version templateMarcus Lee, Platform EngineerOnce, before upgradeDiff output reviewed and annotated
3Identify downstream systems (Kafka, HDFS, Airflow) and their compatibility constraintsSofia Ortega, Data EngineerOnce, before upgradeCompatibility matrix signed off
4Run baseline job on current version and save metricsDavid Kim, DevOpsOnce, before upgradeMetrics JSON in artifact repository
5Perform upgrade on staging cluster using the exact steps documentedPriya Shah, Engineering LeadOnce, during upgradeStaging job completes with no errors
6Run same job on upgraded staging and compare metricsMarcus Lee, Platform EngineerOnce, after staging upgradeRegression less than 20% on key metrics
7Upgrade production cluster with rolling restart or blue-green approachDavid Kim, DevOpsScheduled maintenance windowAll nodes show new Spark version
8Run post-upgrade validation job and data integrity checksSofia Ortega, Data EngineerImmediately after upgradeChecksums match baseline
9Monitor job failure rates for 7 days post-upgradePriya Shah, Engineering LeadDaily for 7 daysNo increase in error rate beyond 5%
10Document rollback decision criteria and test rollback procedureDavid Kim, DevOpsBefore upgradeRollback executed successfully on staging

Conclusion

Upgrading Apache Spark is an operational change that requires the same rigor as any infrastructure migration. The difference between a smooth upgrade and a weekend firefight is the quality of your inventory, the discipline of one change at a time, and a rollback path that you have already tested.

Start with the version inventory commands in this guide. Run them today and save the output. Then choose one low-risk job, run it on the new Spark version in a staging environment, compare the metrics, and document what you learned. That single iteration will teach you more about your cluster's upgrade behavior than any generic checklist.

Remember: the goal is not to be on the latest Spark version. The goal is to be on a version you understand, with an upgrade process you can repeat safely.

Related Research

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL