QUICK ANSWERA Spark OutOfMemoryError means the driver or an executor ran out of JVM memory. Driver OOM usually comes from
collect(), toPandas() or broadcasting a big table. Executor OOM usually comes from partitions that are too large, data skew, wide aggregations or caching too much. Find which side failed in the Spark UI, then reduce data per task (more partitions, filter early), fix skew, avoid pulling data to the driver, and only then add memory.
Driver or executor?
| Sign | Where | Typical cause |
|---|---|---|
| Error in the notebook / driver log right after collect() | Driver | collect(), toPandas(), large broadcast |
| ExecutorLostFailure, "Container killed by YARN for exceeding memory limits" | Executor | Huge partitions, skew, too many cached tables |
| One task in a stage runs far longer and then dies | Executor | Data skew on a join or groupBy key |
| GC overhead limit exceeded | Either | Memory almost full, JVM spends time in garbage collection |
Fix it step by step
- Open the Spark UI → Stages: find the failed stage and look at task input sizes and shuffle read sizes.
- Remove
collect()andtoPandas()on big data; write results to storage or uselimit()/take()to inspect. - Filter and select only needed columns as early as possible (predicate and projection pushdown with Parquet/Delta).
- Raise the number of shuffle partitions for big shuffles (
spark.sql.shuffle.partitions), or let Adaptive Query Execution coalesce and split them (spark.sql.adaptive.enabled=true, on by default in Spark 3.2+). - Check for skew (see the data skew tutorial) and use AQE skew join handling or salting.
- Unpersist cached DataFrames you no longer need; cache only what is reused.
- Only now increase memory: bigger executor memory or memory overhead, or a larger worker type on Databricks/EMR/Synapse.
Settings that matter
| Setting | What it controls |
|---|---|
spark.executor.memory | JVM heap per executor |
spark.executor.memoryOverhead | Off-heap memory (Python workers, native buffers) |
spark.driver.memory / spark.driver.maxResultSize | Driver heap and how much collect() may return |
spark.sql.shuffle.partitions | Partitions after a shuffle (default 200) |
spark.sql.autoBroadcastJoinThreshold | Max table size Spark broadcasts automatically |
PySpark specifics
Python UDFs move rows between the JVM and Python, which costs memory and time. Prefer built-in functions in pyspark.sql.functions, or pandas UDFs (Arrow-based) when you need Python logic. When an executor is killed for exceeding memory with PySpark, raising memoryOverhead often helps because Python workers live outside the JVM heap.
Questions
Is adding more memory the right fix?
Sometimes, but first make sure the job does not pull data to the driver or have a skewed key. Those problems come back at any memory size.
How big should a partition be?
A common target is roughly 100-200 MB of data per partition after a shuffle; AQE helps reach this automatically.