Spark Tuning Cheatsheet

Apache Spark tuning reference: executor sizing, the memory model, shuffle and AQE keys, plus a symptom-to-knob table for the errors you actually hit.

SparkSpark 3.xEMRDatabricksYARNUpdated

Executor shape — where tuning starts

Cores and memory per executor set the parallelism and the heap available per task. Get this wrong and nothing downstream helps.

KeyWhat it actually doesWhen to change it
spark.executor.coresTask slots per executor. Each slot runs one task at a time and shares the executor heap with its neighbours.4-5 is the usual sweet spot. Above ~5, HDFS/S3 client throughput and JVM GC both degrade. Drop to 2-3 when tasks are memory-hungry.
spark.executor.memoryJVM heap size per executor (-Xmx). Does not include off-heap or the overhead region.Raise when you see disk spill in stage metrics or repeated GC pauses. Very large heaps (>32 GB) lose compressed OOPs and often perform worse than two smaller executors.
spark.executor.memoryOverheadNon-heap memory in the container: JVM metaspace, thread stacks, native libraries, netty buffers, Python interpreters.Defaults to max(384 MiB, 10% of executor memory). Raise it for PySpark, heavy off-heap Parquet/Arrow work, or "Container killed by YARN for exceeding memory limits".
spark.executor.instancesStatic executor count. Ignored once dynamic allocation is on.Set explicitly for predictable, repeatable batch jobs on a fixed cluster.
spark.executor.pyspark.memoryCaps memory of the Python worker processes (Linux only, via RLIMIT_AS). Unset by default.Set it only when you must bound runaway Python UDFs. Otherwise Python memory is charged to the overhead region instead.
spark.driver.memoryDriver heap. Holds the plan, broadcast relations before they are shipped, and anything you collect().Raise for wide plans, many partitions, large broadcasts, or notebook work that collects results.
spark.driver.maxResultSizeAborts a job whose collected results exceed this (default 1g). 0 means unlimited.Hitting it is nearly always a signal to stop collecting, not to raise the limit.
spark.memory.offHeap.enabled / .sizeMoves the execution and storage regions off the JVM heap into directly-allocated memory.Useful for very large executors where GC dominates. Off-heap size is separate from the heap rather than carved out of it, so the node has to have room for both.
A sane starting shape for a 5 x r5.4xlarge (16 vCPU, 128 GB) cluster
spark-submit \
  --master yarn --deploy-mode cluster \
  --executor-cores 5 \
  --executor-memory 18g \
  --conf spark.executor.memoryOverhead=3g \
  --conf spark.executor.instances=15 \
  --conf spark.driver.memory=8g \
  --conf spark.sql.shuffle.partitions=600 \
  job.py

# Reasoning: leave 1 core + ~1 GB per node for the OS and node manager,
# 15 usable cores per node / 5 cores = 3 executors per node,
# ~120 GB usable / 3 = ~40 GB per container -> 18g heap + 3g overhead
# leaves headroom for the container, not a number chosen to fill it exactly.

Container size is spark.executor.memory + spark.executor.memoryOverhead + off-heap size (+ pyspark memory when set). YARN and Kubernetes both kill on the container total, not the heap — which is why raising executor memory alone often makes the OOM kills more frequent, not fewer.

The unified memory model

How one executor heap is carved up. Knowing this is what turns "increase the memory" into a decision.

RegionSizeHolds
ReservedFixed 300 MiB, not configurable in practiceSpark internal objects. Subtracted before anything else.
Unified (execution + storage)(heap − 300 MiB) × spark.memory.fraction (default 0.6)Shuffle buffers, joins, sorts and aggregations (execution) plus cached blocks and broadcasts (storage). The two borrow from each other.
Storage floorunified × spark.memory.storageFraction (default 0.5)The slice of cached data execution may not evict. Above this line, cache blocks are evicted when execution needs room.
User memory(heap − 300 MiB) × (1 − spark.memory.fraction)Your own data structures, UDF state, and anything Spark does not manage. Not tracked or spilled by Spark.
  • Execution memory always wins a fight with storage: cached blocks get evicted, running tasks do not get starved.
  • Execution spills to disk when it cannot get room; storage simply drops blocks (recomputed on next access unless you used a DISK_ONLY level).
  • Raise spark.memory.fraction toward 0.7-0.8 only when you have confirmed the job holds little user-managed state — it is a fixed steal from user memory.
  • PySpark data lives outside the JVM heap entirely. For Python-heavy jobs the fix is nearly always overhead memory, not executor memory.

Partitions and shuffle

Partition count is the single most effective knob in Spark. Target roughly 128-200 MB of input per shuffle partition and most other problems shrink.

KeyDefaultWhat it does
spark.sql.shuffle.partitions200Partition count after every DataFrame shuffle (joins, aggregations, repartition-by-key). With AQE on, this is the pre-coalesce upper bound rather than the final count.
spark.default.parallelismTotal cores in cluster modeRDD-level equivalent. Does not affect DataFrame/SQL shuffles — setting it and expecting SQL to change is a classic wasted afternoon.
spark.sql.files.maxPartitionBytes128 MBTarget size of each input split when reading files. Lower it to get more read parallelism from a few big files; raise it to stop tiny-file explosions.
spark.sql.files.openCostInBytes4 MBThe cost Spark assumes for opening a file, used when packing small files into a split. Effectively decides how aggressively small files are merged.
spark.reducer.maxSizeInFlight48 MBData fetched concurrently per reduce task. Raising it costs memory per reducer but can help on high-latency networks.
spark.shuffle.file.buffer32 KBIn-memory buffer per shuffle map output file before hitting disk. Raising to 512k-1m measurably cuts disk seeks on shuffle-heavy jobs.
spark.shuffle.io.maxRetries / .retryWait3 / 5sRetries when a block fetch fails. Raise on spot/preemptible clusters where executors disappear mid-shuffle.
spark.shuffle.service.enabledfalseExternal shuffle service — shuffle files survive executor loss. Effectively required if you want dynamic allocation to scale down without recompute.
spark.io.compression.codeclz4Codec for shuffle, spill and broadcast blocks. zstd trades CPU for a smaller shuffle; worth testing when the network is the bottleneck.
spark.serializerJavaSerializerSet to org.apache.spark.serializer.KryoSerializer for RDD/Dataset work. DataFrame internals already use Tungsten encoders, so the win is smaller than folklore suggests.
Sizing shuffle partitions from the data, not from a default
# Rule of thumb: shuffle_partitions ~= shuffle_input_bytes / 150MB,
# rounded up to a multiple of (executors x cores) so the last wave is full.
#
#   1.2 TB shuffle read / 150 MB  =  ~8200 partitions
#   cluster has 15 executors x 5 cores = 75 slots
#   round to 8250 (110 full waves)

spark.conf.set("spark.sql.shuffle.partitions", 8250)

# Repartition explicitly before a wide join on a known key:
big = big.repartition(8250, "customer_id")

# Reduce output files WITHOUT re-shuffling (coalesce only merges):
out.coalesce(200).write.mode("overwrite").parquet(path)

# Note: coalesce(n) upstream of a wide transformation also limits the
# parallelism of the stage that produces the data. Use repartition when
# you need the parallelism back.

Read "Shuffle Spill (Memory)" and "Shuffle Spill (Disk)" in the Stages tab of the Spark UI. Non-zero disk spill on a stage means your partitions are too big for the memory each task gets — more partitions is usually cheaper than more memory.

Adaptive Query Execution

AQE re-plans a query between stages using the statistics it just observed. On by default since Spark 3.2 and it makes several older manual fixes unnecessary.

KeyEffect
spark.sql.adaptive.enabledMaster switch. Enables runtime re-optimisation between query stages. Default true on Spark 3.2+.
spark.sql.adaptive.coalescePartitions.enabledMerges small post-shuffle partitions into fewer, bigger tasks. This is why an over-large spark.sql.shuffle.partitions is now cheap: set it high and let AQE come back down.
spark.sql.adaptive.advisoryPartitionSizeInBytesTarget size AQE aims for when coalescing (default 64 MB). Raise toward 128-256 MB for large batch jobs to cut task-scheduling overhead.
spark.sql.adaptive.coalescePartitions.minPartitionSizeFloor for a coalesced partition, so AQE cannot produce absurdly tiny tasks.
spark.sql.adaptive.coalescePartitions.initialPartitionNumStarting partition count before coalescing, if you want it decoupled from spark.sql.shuffle.partitions.
spark.sql.adaptive.skewJoin.enabledDetects a skewed shuffle partition and splits it into several tasks, replicating the matching side. Handles moderate skew without salting.
spark.sql.adaptive.skewJoin.skewedPartitionFactorA partition counts as skewed when it exceeds this multiple of the median partition size AND exceeds the threshold below. Lower it to catch milder skew.
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytesAbsolute size floor for skew detection, so small partitions are never split.
spark.sql.adaptive.localShuffleReader.enabledWhen AQE demotes a sort-merge join to a broadcast join, this reads shuffle output locally and skips the network round trip.

AQE only re-plans at stage boundaries, so it cannot help a single stage that is already running. Extreme skew — one key holding 40% of the rows — still needs salting, a broadcast, or splitting the hot keys into a separate job.

Joins and broadcast

Key / hintEffect
spark.sql.autoBroadcastJoinThresholdTables with an estimated size below this (default 10 MB) are broadcast instead of shuffled. Set to -1 to disable broadcasting entirely when the planner keeps under-estimating and OOMing the driver.
spark.sql.broadcastTimeoutSeconds to wait for a broadcast to be built and shipped (default 300). A timeout here usually means the "small" side is not small.
BROADCAST hintSELECT /*+ BROADCAST(d) */ ... — force a broadcast hash join when you know the dimension is small but statistics say otherwise.
MERGE / SHUFFLE_HASH / SHUFFLE_REPLICATE_NL hintsForce sort-merge, shuffle-hash or replicated nested-loop join respectively. Use when the planner picks badly on a specific query, not as a global habit.
spark.sql.join.preferSortMergeJoinWhen true (default), the planner prefers sort-merge over shuffle-hash for large joins — safer on memory, slower when both sides are actually small.
spark.sql.cbo.enabledCost-based optimiser, off by default. Only helps if table and column statistics exist: run ANALYZE TABLE t COMPUTE STATISTICS FOR ALL COLUMNS.
Salting a genuinely skewed join key
from pyspark.sql import functions as F

N = 50  # salt cardinality: enough to spread the hot key across tasks

skewed = big.withColumn("salt", (F.rand() * N).cast("int"))
spread = (
    small
    .withColumn("salt", F.explode(F.array(*[F.lit(i) for i in range(N)])))
)

joined = skewed.join(spread, ["customer_id", "salt"], "left").drop("salt")

# Cost: the small side is replicated N times. Only worth it when a single
# key dominates a stage and AQE skew handling has not fixed it.

Dynamic allocation and cost

The cost lever on a per-job cluster: give executors back when the job stops needing them.

KeyNotes
spark.dynamicAllocation.enabledScale executors with pending-task backlog. Needs either the external shuffle service or shuffle tracking.
spark.dynamicAllocation.minExecutors / .maxExecutorsFloor and ceiling. Set the ceiling deliberately — an unbounded ceiling on a fast autoscaler is how a job costs 10x what it should.
spark.dynamicAllocation.initialExecutorsStarting count, so a short job does not spend its life ramping up.
spark.dynamicAllocation.executorIdleTimeoutHow long an idle executor is kept before release (default 60s). Lower it on spiky jobs to stop paying for idle nodes.
spark.dynamicAllocation.schedulerBacklogTimeoutHow long a backlog must persist before requesting more executors. Raise it to damp thrashing on bursty stages.
spark.dynamicAllocation.shuffleTracking.enabledLets executors holding shuffle data be released safely without an external shuffle service — the usual choice on Kubernetes.
spark.speculationRe-launches stragglers (off by default). Genuinely helps against a slow node; wastes cluster time when the real cause is skew, because every copy of the task is equally slow.

Writes, file layout and lakehouse

KeyNotes
spark.sql.sources.partitionOverwriteModeSet to dynamic so INSERT OVERWRITE replaces only the partitions the write touches instead of wiping the whole table path.
spark.sql.parquet.compression.codecsnappy by default; zstd gives noticeably smaller files at similar read speed and is a cheap storage win.
spark.sql.parquet.filterPushdownOn by default — pushes predicates into the Parquet reader so row groups are skipped. Verify it is actually happening in the physical plan under PushedFilters.
spark.sql.files.ignoreCorruptFiles / .ignoreMissingFilesSkip unreadable or vanished files instead of failing the job. Convenient, and a good way to silently lose data — log what you skipped.
spark.databricks.delta.optimizeWrite.enabledDatabricks / Delta: adds an adaptive shuffle before the write so you get fewer, right-sized files. The standard fix for small-file sprawl on Delta.
spark.databricks.delta.autoCompact.enabledDatabricks / Delta: compacts small files after a write commits. Pairs with optimize-write; costs a little write latency.
OPTIMIZE / ZORDER BY (Delta)OPTIMIZE tbl WHERE day >= ... ZORDER BY (customer_id) — compacts files and co-locates values so data skipping can prune. Re-run as data lands, not once.
VACUUM (Delta)Deletes files no longer referenced beyond the retention window. This is what actually reclaims S3 spend after months of rewrites.

Small files are a cost problem before they are a performance problem: on S3 each file is a LIST and a GET, and a table with a million 200 KB files can spend more on requests than on storage. Target 128 MB - 1 GB per file.

Symptom to knob

The table I actually reach for when a job is failing at 2am.

SymptomLikely causeWhat to try
Container killed by YARN for exceeding memory limitsContainer total exceeded, not the heap — usually Python, native buffers or too many cores per executor.Raise spark.executor.memoryOverhead; lower spark.executor.cores; raise partition count so each task holds less.
java.lang.OutOfMemoryError: Java heap space (executor)One task genuinely needs more heap than it has: huge partitions, a wide aggregation or a big broadcast.More shuffle partitions first, then more executor memory. Check for an accidental broadcast of a not-small table.
OOM or maxResultSize error on the drivercollect(), toPandas(), or a broadcast relation being assembled on the driver.Stop collecting; write to storage and read back. Lower spark.sql.autoBroadcastJoinThreshold or set it to -1.
Stage is 99% done, two tasks running for an hourData skew on the join or group key.Confirm AQE skew join is on; check the max-vs-median task duration in the UI; salt the key or broadcast the small side.
FetchFailedException / shuffle block missingThe executor holding shuffle output died, or the network dropped it.Enable the external shuffle service or shuffle tracking; raise spark.shuffle.io.maxRetries; look for the real executor failure earlier in the log.
Large Shuffle Spill (Disk) in stage metricsPartitions bigger than the memory each task gets.Increase shuffle partitions; raise spark.memory.fraction if user memory is genuinely unused.
GC time is a big share of task timeHeap too large, too many cached objects, or object-heavy RDD code.Prefer more, smaller executors; use Kryo for RDD work; unpersist what you no longer need; consider off-heap.
Thousands of tiny output filesOutput partition count equals shuffle partition count.coalesce() before write, or enable optimize-write on Delta. Repartition by the partition column for partitioned tables.
Job is fast in dev, slow in prod on the same codeDifferent file layout, statistics or config defaults — not the code.Compare the physical plans, the input file counts and the Environment tab side by side before touching anything.

Diagnostics

Things worth typing before changing any config
# What the cluster actually thinks the config is:
spark.sql("SET -v").show(500, truncate=False)
spark.conf.get("spark.sql.shuffle.partitions")

# Physical plan, with the readable formatting:
df.explain("formatted")          # also: "simple", "extended", "codegen", "cost"

# Is the join a BroadcastHashJoin or a SortMergeJoin? Are PushedFilters populated?
# Those two answers explain most surprise runtimes.

# Partition sizes as seen by the executors:
df.rdd.getNumPartitions()
(df.groupBy(F.spark_partition_id().alias("pid"))
   .count().orderBy(F.desc("count")).show(20))   # skew, one row per partition

# Table statistics for the cost-based optimiser:
spark.sql("ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS")
spark.sql("DESCRIBE EXTENDED orders").show(100, truncate=False)
  • Spark UI → Stages: sort tasks by duration. Max duration divided by median duration is your skew number.
  • Spark UI → SQL: click the query to see the plan with actual row counts per node — where the estimate diverges from reality is where the planner went wrong.
  • Spark UI → Environment: the ground truth for what config the job ran with, including everything the vendor set for you.
  • Spark UI → Executors: read GC time and shuffle read/write per executor. One executor doing all the work is skew; all of them at high GC is a heap problem.

Spark Tuning Cheatsheet · https://ctarunsai.github.io/cheatsheets/spark-tuning/ · updated 28 Aug 2026 · Tarun Chitta

About this cheatsheet

Most Spark tuning advice is either a wall of config keys with no explanation, or a blog post that tells you to "increase the memory". This sheet is the middle: every key that actually moves the needle, what it does mechanically, and the specific symptom that should make you reach for it.

The ordering is the order I use in practice. Start with executor shape — cores and memory per executor decide how much parallelism and how much heap each task gets, and almost every "out of memory" is really a shape problem. Then the memory model, because you cannot reason about spill or overhead kills until you know how a heap is carved up. Then partitioning and shuffle, which is where the wall-clock time lives: a stage that reads 400 GB through 200 shuffle partitions is moving 2 GB per task and will spill no matter how much heap you give it.

Adaptive Query Execution has changed the defaults enough that a lot of older tuning is now counterproductive — coalescing partitions, switching sort-merge joins to broadcast at runtime, and splitting skewed partitions all happen for you on Spark 3.2+. The AQE section says what each of those does so you can tell when to trust it and when to override it.

Numbers marked as defaults are the documented Apache Spark 3.x defaults. Vendor distributions override many of them — EMR, Databricks and Dataproc all ship their own values — so on a managed cluster, confirm with spark.sql("SET -v") or the Environment tab in the Spark UI before assuming.