The full answer
Memory problems in PySpark usually come from one of four places: pulling too much data to the driver, partitions too large for an executor's memory (often because of skew), Python processes using memory outside the JVM that the container doesn't allow for, or caching more than fits. The fix depends on which one it is, so read the error first.
Recognising the failure
| Symptom | Likely cause |
|---|---|
Driver OutOfMemoryError, or the notebook kernel dies after collect() or toPandas() | Too much data brought to the driver, or a large broadcast |
Executor OutOfMemoryError: Java heap space | Large partitions, skew, a huge row (big arrays or strings) |
| Container killed for exceeding memory limits (YARN or Kubernetes) | Off-heap use: Python workers, Arrow buffers, native libraries; overhead too small |
| Heavy spill to disk, long garbage collection | Executor memory too small for the partitions |
Causes and fixes
-
Data to the driver Avoid
collect()andtoPandas()on large data. Useshow(),take(), aggregate first, or write results to storage. Raisespark.driver.maxResultSizeonly if the result really is meant to be large. -
Partitions too large Each task holds its partition's working data. Increase the number of shuffle partitions so each is about 100–200 MB, and let adaptive query execution coalesce small ones. For file reads,
spark.sql.files.maxPartitionBytes(128 MB by default) controls split size. -
Skew One huge partition runs out of memory while the others are fine. AQE skew join handling, broadcast joins and salting spread the data.
-
Python memory Python UDFs and pandas UDFs run in Python worker processes outside the JVM heap. Increase
spark.executor.memoryOverhead(by default 10% of executor memory, at least 384 MB) or setspark.executor.pyspark.memory, and reduce Arrow batch sizes. Better: replace Python UDFs with built-in functions. -
Aggregations that build big collections
collect_list,collect_setand RDDgroupByKeygather all values of a key into memory. Use aggregations that combine as they go (sum,count,approx_count_distinct), orreduceByKeyinstead ofgroupByKeyon RDDs. -
Too much caching Cache only what is reused, and
unpersist()afterwards. A DataFrame'scache()uses MEMORY_AND_DISK, so partitions that don't fit go to disk rather than failing, but cached data still competes with execution memory. -
Large broadcasts Broadcasting a table that is too large can exhaust driver and executor memory; check sizes before forcing
broadcast(). -
Executor sizing Raise
spark.executor.memory, or keep memory the same and lowerspark.executor.cores, so each task gets more memory. Very large heaps (well over 64 GB) suffer long garbage collection pauses; more, medium-sized executors are usually better.
spark.memory.fraction (0.6 by default) rarely needs changing; partition sizing and avoiding driver collection solve most cases.
Last updated 16 October 2026
Sources