Cutting Spark cost on EMR and Databricks
Executor sizing, file layout, shuffle settings and the platform choices that actually move a Spark bill on EMR and Databricks, ordered by payoff.
Spark cost work pulls hard towards the wrong end of the problem. Tuning JVM flags is more fun than asking why a job that reads four gigabytes runs for fifty minutes, so people arrive with a list of spark.executor.* settings and leave having saved nothing.
The bill has a simple shape. On EMR you pay instance-hours plus a per-instance EMR surcharge; on Databricks, instance-hours plus DBUs at a rate that depends on the product tier the compute runs under. Either way:
cost = (cores provisioned) x (wall-clock hours) x (price per core-hour)
Three levers, and only three. Everything below pulls one of them, in the order they actually pay, which is roughly the reverse of the order people try them.
1. Do less work
The largest savings never come from tuning. They come from not running the job.
Stop full-refreshing. A daily job that rebuilds a fact table from all of history costs O(history) every day and grows without bound. Rebuilding only the affected partitions turns that into O(a day). This is the single biggest lever in most platforms and it is a data modelling change, not a Spark setting.
Check the schedule against the consumer. Hourly pipelines feeding a dashboard that people open once a morning are common, and nobody ever revisits the cadence after launch. Halving frequency halves cost with no engineering at all.
Read fewer columns and fewer partitions. SELECT * on a 400-column Parquet table when you need nine columns pays for the other 391. Confirm the pruning actually happens: check PartitionFilters and PushedFilters in the physical plan rather than assuming.
df.explain("formatted") # look for PartitionFilters / PushedFilters, not just the join type
Materialise once. If three outputs each re-derive the same expensive intermediate, write it once to a table. Spark will not do this for you across actions.
2. Fix the file layout
Layout drives runtime more than any config in a mature pipeline.
Small files are the classic tax. Every file becomes at least one task, and each task carries scheduler overhead plus an S3 request. A stage of 50,000 two-megabyte files spends most of its life on overhead. This usually traces to over-partitioning: partitioning by day, then country, then device gives you a cross product of tiny directories.
The fix is boring and effective. Partition on the one or two columns that appear in nearly every predicate, keep partition counts in the thousands rather than millions, and aim for files in the 128 MB to 1 GB range. On the write side, control the fan-out explicitly:
(df
.repartition("dt") # one output file group per partition value
.sortWithinPartitions("user_id") # improves Parquet min/max pruning downstream
.write.mode("overwrite")
.partitionBy("dt")
.parquet(path))
If you are on a table format, let it do the compaction: Delta’s OPTIMIZE (with ZORDER BY or liquid clustering) or Iceberg’s rewrite_data_files. Both cost compute, so schedule them where they are cheapest rather than inline with a latency-sensitive job.
The read side has one setting worth knowing. spark.sql.files.maxPartitionBytes (default 128 MB) sets the target input split size; raising it to 256 MB on a job dominated by tiny tasks reduces task count directly.
3. Right-size the cluster and buy it cheaper
Executor sizing is where most people start. It matters, but it is a smaller lever than the two above.
The long-standing shape for JVM executors is around four to five cores each. Fewer cores and you lose the benefit of shared broadcast variables and pay per-JVM overhead many times over; more and you get HDFS/S3 client contention and long GC pauses on a large heap. Leave roughly one core and a gigabyte per node for the OS and node daemons, then divide.
Do not forget off-heap. spark.executor.memoryOverhead defaults to max(384 MB, spark.executor.memoryOverheadFactor * executorMemory) with a factor of 0.1, and PySpark workers live in that overhead, not in the JVM heap. Heavy Python UDFs or pandas UDFs are the usual cause of “container killed by YARN for exceeding memory limits” on a job whose heap looks fine.
spark.executor.cores 5
spark.executor.memory 18g
spark.executor.memoryOverhead 3g # raise this first for PySpark OOMs
spark.driver.memory 8g
Then make the hours cheaper:
- Spot for task nodes. On EMR, run the primary and core nodes on demand and put task nodes in a spot instance fleet with several instance types in the pool. On Databricks, keep the driver on demand and let workers be spot with fallback. The saving is large and the risk is bounded if the job can lose an executor without losing the run.
- Graviton. ARM instance families are cheaper per hour and Spark runs on them without changes, as long as every JAR in your dependency chain is architecture-independent. Test the ones that are not.
- Autoscale with a floor. Dynamic allocation only helps if the job’s parallelism actually varies. A job with one long uniform stage should be a fixed-size cluster; autoscaling it adds startup latency for nothing.
- Kill idle clusters. Auto-termination on interactive clusters, and instance pools to hide the startup cost of short jobs.
The Databricks-specific trap is worth stating plainly: running scheduled jobs on all-purpose compute instead of job compute. The DBU rate for all-purpose is substantially higher, and a workflow pointed at a shared interactive cluster can quietly cost several times what the same code costs on an ephemeral job cluster. It is one query against your usage data and often the largest single finding.
Photon deserves the same arithmetic rather than a default yes. It bills at a higher DBU rate, so it pays only when the speedup exceeds the multiplier. It does that reliably on scan-and-aggregate SQL over Delta, and much less so on jobs dominated by Python UDFs, which fall back to the JVM path anyway. Measure both on one representative job.
4. Then tune shuffle
Now the settings people wanted to start with.
Partition count, and letting AQE do it
spark.sql.shuffle.partitions still defaults to 200, a number chosen when laptops were the reference. On a 4 TB shuffle that is 20 GB per partition, guaranteeing spill; on a 200 MB shuffle it is 200 near-empty tasks.
Adaptive query execution largely solves this and has been on by default since Spark 3.2. AQE coalesces post-shuffle partitions at runtime, so the modern approach is to set the static value generously and let AQE shrink it:
spark.sql.adaptive.enabled true
spark.sql.adaptive.coalescePartitions.enabled true
spark.sql.adaptive.advisoryPartitionSizeInBytes 128m # default 64m
spark.sql.shuffle.partitions 2000 # upper bound; AQE coalesces down
Skew
Skew is the other shuffle killer, and it looks unmistakable in the Spark UI: one task in a stage running for twenty minutes while 1,999 finished in seconds. AQE splits skewed partitions automatically when a partition is both larger than spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes (default 256 MB) and more than spark.sql.adaptive.skewJoin.skewedPartitionFactor times the median. That factor’s default changed during the Spark 3.x line, so check the value on your build rather than trusting a blog post. When AQE cannot help, because the skew is a single hot key such as a null customer id, salt it: add a random suffix to the key on the large side, explode the small side to match, join, then aggregate away the salt.
Broadcast joins
Broadcasting the small side removes a shuffle entirely. spark.sql.autoBroadcastJoinThreshold defaults to 10 MB, which is conservative for a modern driver. Raising it to 64 MB or 128 MB converts a lot of dimension joins into broadcasts. Raise it too far and the driver dies collecting the table, so raise it deliberately and watch driver memory.
Commit protocol on S3
The default Hadoop committer emulates rename with copy, so the final commit of a large partitioned write can take longer than the computation. Use the EMRFS optimised committer on EMR (on by default for Parquet on recent releases, and easy to silently disable by writing in a format it does not cover) or the S3A magic committer elsewhere. Databricks handles this internally.
Cache deliberately
.cache() on a DataFrame consumed once is pure cost: you pay to serialise it and evict something useful. Cache only what is read multiple times across actions, and unpersist() when done.
Measure, then attribute
None of this is actionable without two things.
The first is the Spark UI, specifically the SQL tab and the stage detail: task duration distribution for skew, shuffle read and write sizes for partition sizing, spill for memory pressure. Spill to disk is the clearest single signal that a stage is under-provisioned or under-partitioned. Keep the Spark History Server available on EMR; a job you cannot inspect after the fact is a job you cannot tune.
The second is tagging. Tag EMR clusters, Databricks clusters, jobs and pools with a team and pipeline identifier, and the platform bill becomes a per-pipeline bill in Cost Explorer or Databricks system tables. Until that exists every optimisation is unattributable and the conversation stays about opinions. It is the least glamorous item on the list and the one that makes the rest possible.