A job that uses Python UDFs fails with:
org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)
Caused by: java.io.EOFException
at org.apache.spark.api.python.PythonRunner$$anon$3.read(...)
You may also see Python worker failed to connect back, BrokenPipeError, or a task retried four times before the stage fails. The message only means that the Python process the executor started for the task died. Spark does not see why. The cause is almost always one of three things: the operating system killed the process for using too much memory, a native library crashed, or the code exited on purpose.
How Python UDF memory works
Each task that runs Python code starts (or reuses) a Python worker process on the executor node. That process runs outside the JVM heap. With 8 cores per worker you can have 8 Python processes, each holding an Arrow batch or a whole pandas group, plus the executor JVM itself. Raising spark.executor.memory makes this worse, because it leaves less RAM for the Python processes. The process gets killed by the Linux OOM killer, not by Spark, so you see no Java OutOfMemoryError.
Step 1: find the real exit reason
- Open Spark UI > Stages > the failed stage, then Tasks. Note the executor ID and host of the failed attempts.
- Open Executors > that executor, then stderr. Look for:
| Text in executor stderr or error | Meaning |
|---|---|
exit code 137, Killed, SIGKILL | OOM killer, the node ran out of memory |
exit code 139, SIGSEGV, Segmentation fault | Native code crashed (C extension, Arrow, a driver library) |
Fatal Python error with a stack trace | Interpreter crash. The trace shows the module |
SystemExit or nothing at all | Code called sys.exit() or os._exit() inside the UDF |
Exit codes and log wording vary by runtime. If stderr is empty, use the next two checks.
- Check node memory at the time of the failure:
SELECT instance_id, start_time,
round(mem_used_percent, 1) AS mem_pct,
round(mem_swap_percent, 1) AS swap_pct,
round(cpu_user_percent + cpu_system_percent, 1) AS cpu_pct
FROM system.compute.node_timeline
WHERE cluster_id = '<cluster-id>'
AND start_time BETWEEN '<failure time - 15 min>' AND '<failure time + 5 min>'
AND driver = false
ORDER BY instance_id, start_time;
Memory near 100 % on the failing node just before the failure confirms the OOM killer.
- Turn on Python fault handlers so the next crash leaves a Python stack trace in the executor log:
spark.python.worker.faulthandler.enabled true
spark.sql.execution.pyspark.udf.faulthandler.enabled true
Set these in the cluster's Spark config, or on job compute, and rerun.
Step 2: match the pattern
| Pattern | Typical cause | Fix |
|---|---|---|
applyInPandas / groupBy().apply fails on a few tasks only | One group is huge. The whole group is loaded into one pandas DataFrame | Find the big keys (below), split them, or pre-aggregate |
pandas UDF (@pandas_udf) fails with wide rows or large strings/arrays | Arrow batch too big for memory | Lower spark.sql.execution.arrow.maxRecordsPerBatch |
mapInPandas loads everything into one frame | Code collects the iterator with pd.concat(list(it)) | Process and yield each batch as it arrives |
| Fails on all tasks soon after a library upgrade | ABI mismatch between numpy, pyarrow, pandas or a C extension | Pin versions that work together, and test on the target runtime |
| Segfault inside a UDF that calls a native SDK (ODBC, image, geospatial, ML) | Library not fork-safe or not thread-safe, or a client was shared across processes | Create the client inside the UDF/partition, not at module import on the driver |
Fails only on spot or memory-tight VM sizes | Too many cores per GB of RAM | Memory-optimized VMs, or fewer concurrent Python tasks per node |
| Stage fails on the same row every time | Bad input triggers a native crash, for example a corrupt image or an extreme value | Validate inputs before the UDF and wrap parsing in try/except |
Find oversized groups for applyInPandas
from pyspark.sql import functions as F
(df.groupBy("customer_id")
.agg(F.count("*").alias("rows"),
F.sum(F.length(F.to_json(F.struct("*")))).alias("approx_bytes"))
.orderBy(F.desc("approx_bytes"))
.show(20, truncate=False))
If one key has hundreds of MB to several GB of data, that group cannot fit in one pandas process however many workers you add. Common fixes:
- Add a second grouping key, such as
customer_id, month, if the logic allows it. - Pre-aggregate with Spark built-ins and pass only the reduced data to pandas.
- Handle the few huge keys separately with Spark-native logic, and use
applyInPandasfor the rest.
Shrink Arrow batches for pandas UDFs
# Default is 10000 records per batch. Lower it for wide or nested rows.
spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", "2000")
On recent runtimes you can also cap batches by size with spark.sql.execution.arrow.maxBytesPerBatch. Check whether your runtime supports it.
Stream batches in mapInPandas
def score(batches):
model = load_model() # once per task, inside the worker
for pdf in batches: # one Arrow batch at a time
pdf["score"] = model.predict(pdf[FEATURES])
yield pdf[["id", "score"]]
out = df.mapInPandas(score, schema="id long, score double")
Don't call list(batches) or pd.concat over the whole iterator.
Step 3: give Python room on the node
If the work per task is reasonable but the node still runs out of memory:
- Fewer concurrent Python tasks per node. Setting
spark.task.cpus 2on an 8-core worker runs 4 tasks at a time instead of 8, so 4 Python processes share the RAM. This is cluster-level Spark config. - Memory-optimized VM families (E-series) instead of general-purpose or compute-optimized for UDF-heavy jobs.
- Do not raise
spark.executor.memoryto fix a Python OOM. It takes memory away from the Python processes. - Repartition before the UDF if the input partitions are very large:
df.repartition(400). That gives smaller tasks and smaller batches.
Warning
Increasing retries (
spark.task.maxFailures) or adding job retries hides the problem and multiplies the cost. A deterministic OOM fails on every attempt. Fix the memory shape first.
Step 4: native library and environment crashes
# On the driver and in a UDF, compare versions
import numpy, pandas, pyarrow
print(numpy.__version__, pandas.__version__, pyarrow.__version__)
def versions(_):
import numpy, pandas, pyarrow
yield (numpy.__version__, pandas.__version__, pyarrow.__version__)
print(spark.sparkContext.parallelize(range(4), 4).mapPartitions(versions).distinct().collect())
If the executors show different versions from the driver, or a %pip install upgraded numpy or pyarrow beyond what the runtime ships with, pin them back. The supported versions are in the runtime release notes ("System environment").
Tip
On standard access mode and serverless, Python UDFs run in an isolated sandbox that has its own memory limits, and not all native libraries work there. If the crash happens only on those compute types, reproduce it on a dedicated cluster to tell a sandbox limit from a code problem.
Better than tuning: drop the UDF
Many crashing UDFs do things Spark already has built in: date parsing, regex, JSON, hashing or conditional logic. Built-in functions run in the JVM (and in Photon), so they avoid the Python process completely. Look for a built-in replacement before you tune memory.
Prevent it next time
- Load-test UDF jobs with the largest real group or partition, not a sample.
- Add a group-size guard before
applyInPandasthat fails fast with a clear message when a key goes over an agreed row count. - Pin numpy, pandas and pyarrow in job environments and in requirements files deployed with bundles.
- Keep the fault handler settings on in the job cluster policy for UDF-heavy jobs, so the next crash has a stack trace.
- Alert from
system.compute.node_timelinewhen worker memory stays above 90 % on UDF jobs.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get