Spark & PySpark
Debugging Spark Failures Systematically - A Repeatable Process
When a Spark Job Fails, Most Engineers Start Guessing. Here Is a Systematic Process That Finds the Cause Every Time.

TL;DR
- Trace the exception chain to the most specific, actionable cause, then correlate it with the failing task and executor - the last “Caused by” is often useful, but it isn’t guaranteed to be the root cause
- One real failure frequently cascades into dozens of task retries and secondary errors — identify the first failure, not the twentieth
- The Spark UI tells you more than the stack trace does — check Stages for skew, Executors for GC and memory, SQL for the physical plan, before reading a single line of application code
- Executor logs and driver logs answer different questions — driver logs tell you what Spark decided to do, executor logs tell you what actually happened on the machine
- Spark failures cluster into recognizable failure classes - memory, skew, shuffle, serialization, resource contention, data/schema errors, dependency and library failures, network/external-system failures, and application logic bugs — treat this as a starting taxonomy, not an exhaustive one, and use it to narrow the investigation rather than declare a diagnosis
Guessing is slow because you are searching the wrong space. The failure is almost always visible if you look in the right order.
A job failed with: org.apache.spark.SparkException: Job aborted due to stage failureThe engineer spent forty minutes reading that line and every StackOverflow post matching it. It matched nothing. The error is too generic to search.
The actual cause was six lines further down the stack trace: Caused by: java.io.NotSerializableException: org.apache.spark.sql.SparkSessionA UDF had captured a reference to the SparkSession from the outer scope. Every task tried to serialize it to send to the executors. It cannot be serialized.
The fix was moving one variable inside the function. Forty minutes finding it. Ninety seconds fixing it. The forty minutes were spent reading the wrong line.
Why Most Engineers Start Guessing
A Spark failure produces a wall of text — often 100+ lines of stack trace, task retry logs, and executor warnings. Under pressure, the instinct is to read the first line, search it, and start trying fixes that seem plausible.
This works occasionally and wastes significant time the rest of the time, because the first line of a Spark error is frequently a generic wrapper exception — SparkException: Job aborted due to stage failure, ExecutorLostFailure — that describes the category of failure, not the cause.
The systematic process below moves from the noisy top-level failure toward the most specific actionable cause in a consistent order. Each step is designed to eliminate major categories of possibilities before you change code or configuration.
Step 1: Read the Actual Error, Not the First Line
The Exception Chain
Java and Scala exceptions chain — each exception can wrap another exception that caused it. Spark’s stack traces frequently show the wrapper exception at the top and the actual cause several Caused by: lines down.
org.apache.spark.SparkException: Job aborted due to stage failure:
Task 4 in stage 12.0 failed 4 times, most recent failure:
Lost task 4.3 in stage 12.0 (TID 892, executor 3):
org.apache.spark.SparkException: Task failed while writing rows.
Caused by: org.apache.spark.SparkException: Failed to execute user
defined function
Caused by: java.lang.NumberFormatException: For input string: "N/A"
at java.lang.NumberFormatException.forInputString(...)
at java.lang.Long.parseLong(...)
at com.mycompany.transforms.ParseAmount.apply(ParseAmount.scala:14)The actual, actionable cause is the last Caused by: block: a UDF at ParseAmount.scala:14 is calling Long.parseLong() on a string value "N/A" that isn't a valid number. Everything above it is Spark's machinery reporting that a task failed because of this.
Trace the exception chain toward the most specific actionable cause before forming a hypothesis. The deepest `Caused by:` is often useful, but it is not automatically the root cause. Some failures have no meaningful nested cause, and the most useful evidence may instead be in the task summary, executor logs, driver logs, or Spark UI.
Common Misleading Top-Level Errors
These top-level exceptions appear frequently and point to many different root causes — never diagnose from these alone:

All four require reading further before you know what to fix.
Step 2: Find the First Failure, Not the Cascade
How One Failure Becomes Twenty
Spark retries failed tasks by default (spark.task.maxFailures, default 4). When a stage fails, Spark may retry the entire stage. A single root cause - one bad executor, one corrupt file, one OOM — can produce dozens of log entries as Spark retries, redistributes, and re-fails across multiple attempts.
Reading the logs top to bottom in chronological order surfaces the cascade. But the first ERROR or Exception line in a log is not automatically the root cause — logs are frequently asynchronous, and independent components can emit errors on their own timeline that have nothing to do with each other. A blind grep | head can just as easily surface a downstream symptom that happened to log first as it can the actual origin.
The reliable approach: identify the specific failing task or stage first - from the Spark UI or the top-level SparkExceptionsummary (e.g., "Task 4 in stage 12.0 failed 4 times") — then correlate that exact task ID, executor, and timestamp across the logs, rather than trusting whichever error line happens to appear earliest in a raw search.
# Identify the failing task/stage first, from the UI or the
# top-level SparkException summary
# Then correlate that SPECIFIC task ID and executor across the logs —
# not just whatever error line appears first
grep "task 4.*stage 12" application.log
# Cross-reference the timestamp of that task's failure against
# executor-level logs for the same window. A naive first-occurrence
# grep can surface an unrelated, asynchronously-logged symptom
# from a completely different component.Reading the Driver Logs for the Origin
The driver log records the sequence of stage submissions, task failures, and retry decisions. This is where you find the first failing task ID and trace it back to the specific executor and partition.
25/05/12 09:14:02 WARN TaskSetManager: Lost task 4.0 in stage 12.0
(TID 812, executor 3): java.lang.NumberFormatException...
25/05/12 09:14:02 INFO TaskSetManager: Starting task 4.1 in stage 12.0
(TID 850, executor 7)
25/05/12 09:14:03 WARN TaskSetManager: Lost task 4.1 in stage 12.0
(TID 850, executor 7): java.lang.NumberFormatException...
25/05/12 09:14:03 INFO TaskSetManager: Starting task 4.2 in stage 12.0
(TID 891, executor 2)
25/05/12 09:14:04 WARN TaskSetManager: Lost task 4.2 in stage 12.0
(TID 891, executor 2): java.lang.NumberFormatException...The same task (partition 4 of stage 12) is failing repeatedly on different executors with the same exception. That strongly suggests a deterministic or data-dependent problem: the task is processing the same partition regardless of which executor runs it. Investigate the common input, transformation logic, and exception details before blaming a particular executor.
Step 3: Check the Spark UI Before Reading Code
The Spark UI contains diagnostic information that is not visible in the stack trace at all. Check it before assuming the problem is in your code logic.
Stages Tab — Duration and Skew
Click into the failing (or slowest) stage. Look at the task duration distribution.
Task duration distribution to check:
Min: 12s
25th: 14s
Median: 15s
75th: 16s
Max: 340s ← 20x the median — investigate uneven work
A large spread between the median and the slowest tasks is a signal,
not a diagnosis. Investigate:
• Partition sizes
• Skewed join or aggregation keys
• Input/output I/O
• GC and memory pressure
• Executor resource contention
• Scheduling or infrastructure variability
If one or a few tasks consistently do much more work than the rest,
data skew or uneven partitioning becomes a stronger hypothesis.This check tells you whether the workload is being processed uniformly or whether a small number of tasks are behaving differently. That distinction helps narrow the investigation, but you still need partition size, key distribution, I/O, and executor metrics to determine why.
Executors Tab - GC and Memory
Check GC Time relative to Task Time for each executor. Sustained or unusually high GC relative to task execution time is a warning sign for allocation or heap pressure, especially when accompanied by executor instability, long pauses, reduced throughput, or OOM symptoms. The useful signal is the pattern and context, not a universal percentage threshold.
Also inspect Storage Memory and Peak Execution Memory, where available. These metrics can help determine whether the executor was under significant memory pressure, but interpret them alongside the OOM type, GC behavior, executor configuration, and workload characteristics rather than treating any single metric as proof.
SQL Tab - The Physical Plan
For DataFrame and SQL jobs, the SQL tab shows the physical execution plan — which join strategy ran, where shuffles occur, whether predicate pushdown applied. If the failure is performance-related rather than a hard crash, this is often where the actual problem is visible: a sort-merge join that should have been a broadcast, a missing filter pushdown, an unexpected BroadcastNestedLoopJoin.
Step 4: Interpret Executor Logs Correctly
What to Search For
Executor logs (distinct from the driver log) contain the actual task execution output — including print statements, library warnings, and the full stack trace for exceptions that occurred during task execution.
# Find the specific executor log for the failing task
# From the Spark UI: Executors tab → click the executor ID → stderr/stdout
# Search for the actual error, not just "ERROR" (too broad)
grep -A 20 "NumberFormatException\|OutOfMemoryError\|NotSerializableException" \
executor_3_stderr.log
# Check what happened immediately before the failure
grep -B 10 "Exception" executor_3_stderr.log | head -30Distinguishing Executor Failure from Task Failure
These require different fixes:
Task failure: the executor remains healthy, but a specific task throws an exception. This usually points to something specific about the task’s input, application logic, serialization, dependencies, or an external system it contacted. Use the exception and surrounding executor logs to distinguish among them.
Executor failure: the executor process itself dies — for example because of an OS-level OOM kill, JVM crash, node failure, network loss, or another infrastructure event. An abrupt executor log can support this interpretation, but it does not by itself identify the underlying cause. Application code can also trigger executor death indirectly through excessive memory or resource consumption.
For a task failure, look for a complete exception stack trace tied
to a task attempt and evidence that the executor continued running afterward.
In the Spark UI, check whether other tasks on the same executor completed
successfully.
For an executor failure, correlate the executor's disappearance with its exit reason, driver logs, cluster-manager events, and the final executor log lines. An abrupt log ending is a clue, not proof of an OOM kill.
# Executor failure signature - log ends abruptly
tail -5 executor_3_stderr.log
# If the last lines show normal processing with no exception,
# and the Spark UI shows "ExecutorLostFailure" for this executor -
# the process was killed externally (OOM killer, node failure, spot reclaim)Step 5: Match the Symptom to a Failure Class
The Failure Classification Table
Spark failures cluster into a handful of recognizable classes, though this list is a starting taxonomy rather than an exhaustive one. Match the observed symptom pattern to narrow the investigation, and treat the match as a working hypothesis to confirm - not a diagnosis.

This table tells you where to look next, not what the answer is.
A Worked Example — End to End
A nightly job fails intermittently — succeeds most nights, fails roughly once a week with different error messages each time.
Step 1 - read the actual error. Three different failure nights show three different top-level exceptions: FetchFailedException, ExecutorLostFailure, and a timeout. Different top-level symptoms with no obvious common thread.
Step 2 - identify the originating failure. In each case, correlating the affected task/stage, executor, and timestamps shows the same pattern: one executor stops responding, other executors continue for 30–60 seconds, then a cascade of fetch failures and retries begins as tasks try to read shuffle data from the now-dead executor.
Step 3 - check the Spark UI. The Executors tab for the failed run shows one executor spending 94% of its recorded task time in GC in the minutes before it disappeared from the executor list. The other executors show normal GC. That combination makes severe memory/allocation pressure a strong hypothesis, which needs to be confirmed against executor and cluster-manager diagnostics.
Step 4 - check executor logs. The dead executor’s log ends abruptly with no clean shutdown message - consistent with the executor process being terminated externally rather than completing with a normal task-level exception. The exit reason and cluster-manager/container diagnostics should be used to distinguish an OOM kill from other causes of executor loss.
Step 5 - match to a failure class. One executor entering severe GC pressure, then dying without a clean shutdown, causing downstream fetch failures — this is the memory/GC failure class, manifesting as a shuffle failure because of when in the pipeline the executor died.
For this hypothetical incident, the investigation eventually reveals the following:
Root cause: a Python UDF that was building a large in-memory list per partition, with no bound on list size. On most nights, the partition sizes were small enough that this fit in the memory overhead budget. On nights with slightly higher event volume, the largest partition’s UDF memory usage exceeded the overhead budget and the OS killed the executor mid-task — producing a different top-level error depending on exactly which downstream operation was affected by the missing executor.
The fix: replace the list-accumulation pattern in the UDF with a native aggregation. The intermittent, seemingly random failures were a single deterministic cause that only manifested above a data volume threshold.
The Debugging Process as a Checklist
□ Trace the exception chain to the most specific actionable cause —
don't assume the deepest `Caused by:` is automatically the root cause
□ Identify the affected task/stage and correlate its task ID, executor,
timestamp and exception across driver and executor logs
□ Check whether the same task fails repeatedly across executors —
this strongly suggests a deterministic or data-dependent problem;
investigate the common input and exception
□ Check whether failures are isolated to one executor or cluster node —
this raises the probability of resource or infrastructure issues
□ Open Spark UI → Stages → inspect task duration,
input/output sizes, partition sizes, and stragglers
□ Open Spark UI → Executors → inspect GC, memory, executor losses,
and other resource signals
□ Open Spark UI → SQL → inspect the physical plan for join strategy,
exchanges, scans, and predicate pushdown when performance is involved
□ Pull the relevant executor logs and correlate them with the failing task
and timestamp
□ Distinguish task-level exceptions from executor-level loss,
then investigate the actual exit reason rather than inferring it from
the log ending alone
□ Match the observed pattern to a failure class —
treating the classification as a hypothesis, not a diagnosis
□ Form one testable hypothesis, change the minimum necessary,
and verify whether the evidence changesUse the steps as a decision sequence, not a rigid ritual. The early steps should narrow the search space: identify the actionable exception, isolate the affected task or executor, and use the Spark UI and logs to distinguish application, data, resource, shuffle, and infrastructure signals. Step 5 then gives you a useful working hypothesis to test.
Final Takeaway
Spark failures look chaotic because the tooling surfaces a lot of noise — retries, cascading errors, generic wrapper exceptions. The noise is not random. It follows a predictable structure, and that structure is navigable in a fixed number of steps if you know where to look and in what order.
Guessing wastes time because it searches the wrong space first. The systematic process traces the exception chain to the most actionable evidence, isolates the affected task or executor, correlates the relevant logs, and uses the Spark UI to narrow the failure class before changing application code or configuration.
Core Principle
The stack trace is not lying to you.
It is just not organized for a quick diagnosis.
Read it in the right order.
Correlate it with the task, executor, and Spark UI.
Then test one hypothesis at a time.Next in Series
Spark UI Masterclass - Reading Every Tab Like a Performance Engineer
You now have a systematic debugging process.
Next: a deep, production-grade walkthrough of every tab in the Spark UI -Jobs, Stages, SQL, Executors, Storage - not the beginner tour, but what each metric actually means, which ones signal real problems, and which ones are noise you can safely ignore.