Spark Performance Tuning and Operations
Size clusters and executors, manage memory, cache wisely, control output file counts and debug common Spark failures in production.
Advanced · about 6 hours · difficulty 4/5
Learn first: Joins and Shuffles in Spark
A Spark job that works on a sample can fail or cost a fortune on full data. Tuning is about measuring, finding the bottleneck and changing one thing at a time.
Resources and memory
- Executor count, cores per executor and memory per executor decide parallelism. A common start is 4 to 5 cores per executor.
- Executor memory is split between execution (shuffles, joins, sorts) and storage (cache). When execution memory runs out, Spark spills to disk; too much spill means slow jobs or out-of-memory errors.
- Driver memory matters when you collect results or broadcast tables.
Caching
cache() or persist() helps only when a DataFrame is reused by several actions. Caching everything wastes memory. Unpersist when done.
Output files
repartition(n)does a full shuffle to n partitions;coalesce(n)reduces partitions without a full shuffle.- Control output so each partition folder gets a sensible number of reasonably sized files.
Common failures and what they mean
- OutOfMemoryError on executors: skew, huge partitions or too-large broadcasts.
- OutOfMemoryError on the driver:
collect()ortoPandas()on big data. - Stage stuck on one task: skew.
- Too many small files: over-partitioned writes.
- Lost executors: spot instance reclaimed or memory overhead too low.
Cost awareness
On Databricks, EMR or Dataproc, idle clusters burn money. Use autoscaling, auto-termination, job clusters instead of always-on clusters, and spot instances for fault-tolerant batch.
Pitfalls
- Copy-pasting tuning configs from blogs without measuring.
- Increasing memory to hide skew instead of fixing it.
You are ready to move on when you can take a failing or slow Spark job, use the Spark UI to name the cause (skew, spill, small files, driver collect), fix it and show the before and after.
Key concepts
- Executor sizing
- Memory model and spills
- cache and persist
- repartition vs coalesce
- Diagnosing OOM errors
- Autoscaling and spot instances
- Managed Spark: Databricks, EMR, Dataproc
Mini project
Take your PySpark taxi job and make it intentionally bad (collect, no filters, 2000 shuffle partitions, cache everything). Then fix it step by step, logging runtime, shuffle size and output file count after each change.
Check yourself
What is the difference between repartition(10) and coalesce(10), and when would you choose each before writing output?
Free resources
- Tuning Spark (Apache Spark)
- Spark configuration (Apache Spark)
- Spark SQL performance tuning (Apache Spark)