Skip to main content
Back to Academy💻 5. Distributed Compute & FinOps Optimization
5 min read
Try Hands-on Lab
VISUAL LESSON5. Distributed Compute & FinOps Optimization

Distributed Compute Mechanics: Spark Memory Overhead, Cores & Shuffles

Learn how Spark splits work across Drivers and Executors, how to size CPU cores and executor memory + 10% overhead without OOM crashes, and how to tune shuffles cleanly.

Apache Spark Executor SizingSpark Memory Overhead CalculationSpark Shuffle Spill Optimization5 Core Executor Sweet SpotAdaptive Query Execution AQEDatabricks FinOps Cluster Cost

Explain Like I'm New: Moving Furniture With Trucks & Teams

Imagine moving 100 heavy boxes across town: - Driver Node = The Foreman: Holds the clipboard, reads the route map, schedules trucks—does NOT carry heavy boxes unless you carelessly tell every truck to send all boxes back to the Foreman (df.collect())! - Executor = Moving Truck: Each truck has cargo space (Executor Heap Memory) and a team of movers inside (CPU Cores / Task Slots). - Partitions = Individual Boxes: Too few giant 20 GB boxes collapse one mover's back (OOM crash / Data Skew). One million tiny 1 KB matchboxes choke the clipboard scheduling forever (Overhead / Small Files)!

Key Beginner Takeaway: Great Spark cluster sizing balances ~5 CPU cores per executor, budgets 10% off-heap memory overhead, targets 128 MB–200 MB per partition, and eliminates giant Data Skew and unnecessary `collect()` calls.

Core Terminology & Memory Anatomy

Component / KeywordPlain-English MeaningBeginner Rule of Thumb
Driver MemoryForeman RAM managing Spark DAG, broadcast variables & collect() results.Never df.collect() multi-GB tables! Use .limit(20) or write directly to storage.
Executor Heap (`spark.executor.memory`)Main JVM working RAM shared across task slots in 1 executor.~4 GB RAM per CPU core (e.g., 5 cores -> ~20 GB heap).
Memory Overhead (`10%` or `384MB min`)Extra RAM outside the JVM heap for Python UDFs, Netty shuffle buffers, and off-heap Photon/Arrow memory.Container request = Executor Heap + max(384 MB, 0.10 * Heap).
5-Core Sweet SpotOptimal CPU threads per executor container (spark.executor.cores = 5).<= 5 cores avoids HDFS/S3 I/O bottleneck while keeping GC pauses low!
Shuffle (`Exchange`)Moving rows across network cables between trucks during JOIN or GROUP BY.The #1 slow & expensive operation in Spark! Minimize with Broadcast Joins & AQE.
Spill to DiskWhen an executor's RAM fills up during a giant sort/join, it dumps temp data to slow SSDs.Look for "Spill (Memory)" & "Spill (Disk)" in Spark UI to catch skew!

Step-by-Step Worked Calculation: Sizing a Cluster Cleanly

Suppose you have 4 Worker Nodes, each with 16 vCPUs and 64 GB RAM. How should you size Executors cleanly?

Step 1: Reserve OS & Cluster Agent Overhead (~1 vCPU & ~4 GB per node) - Available per node: **15 vCPUs**, **~60 GB RAM**.

Step 2: Apply the **5-Core Executor Sweet Spot** - `15 vCPUs / 5 cores per executor` = **3 Executors per node** (`12 Executors total` across 4 nodes, or **60 concurrent task slots**).

Step 3: Compute RAM & Memory Overhead per Executor - Total RAM budget per executor = `60 GB / 3 = 20 GB`. - Apply the **10% Memory Overhead Formula**: - `spark.executor.memory` = `20 GB / 1.10` ≈ **18 GB** - `spark.executor.memoryOverhead` = `0.10 * 18 GB` ≈ **1.8 GB** (fits cleanly inside 20 GB container without YARN/K8s OOM-kills!).


Tuning Shuffles & Eliminating FinOps Waste

1. Always Enable Adaptive Query Execution (`AQE`) Modern Spark 3+ / Databricks enables AQE by default to fix static partition guessing:

SET spark.sql.adaptive.enabled = true;
SET spark.sql.adaptive.coalescePartitions.enabled = true;
SET spark.sql.adaptive.skewJoin.enabled = true;

Why AQE saves 30–50% compute money: - Automatically merges 200 mostly-empty post-shuffle partitions down into crisp ~128 MB tasks! - Automatically splits massive skewed keys (e.g., customer_id = NULL or 'WALK_IN') across parallel tasks instead of letting 1 executor struggle for 45 minutes while 11 executors sit idle!

2. Broadcast Small Dimension Tables (`< 10–100 MB`) Instead of shuffling a 1 Billion-row `fact_sales` table across the network to join a 5 MB `dim_stores` table, copy `dim_stores` into every Executor's RAM (**Broadcast Hash Join** -> **ZERO shuffle on `fact_sales`!**):

from pyspark.sql.functions import broadcast

joined_df = fact_sales.join(broadcast(dim_stores), "store_id")

3. FinOps Spot/Autoscaling Rules - **Scheduled ETL batch jobs:** Use **Autoscaling + Spot Workers** (keep Driver On-Demand so losing a Spot driver never aborts progress!). - **Interactive BI / Serverless SQL:** Use **Auto-Termination (10 min)** so forgotten weekend clusters never burn dollars idling overnight.


Common Beginner Mistakes (And How to Fix Them)

  1. Massive 1-Executor-Per-Node Containers (e.g., 64-core / 256 GB heap): Garbage Collection freezes for 15+ seconds and concurrent S3 writes bottleneck. Split large machines into crisp 4–5 core executors!
  2. Row-by-row Python UDFs instead of built-in SQL / Spark functions: Serialization between JVM and Python process runs 10–50x slower and triggers off-heap OOM! Always prefer native SQL expressions (CASE WHEN, REGEXP_REPLACE) over custom @udf.
  3. Hardcoding `repartition(200)` on a tiny 5 MB table: Creates 200 tiny overhead files for zero speedup! Let AQE or coalesce(1) size output cleanly.

Quick Cheat Sheet

  1. Target 5 CPU cores per executor and subtract ~10% memoryOverhead from container RAM.
  2. Avoid `collect()` on large tables; let executors write Parquet/Delta straight to cloud storage.
  3. Broadcast small dimensions (< 100 MB) and keep AQE enabled (coalescePartitions + skewJoin).
  4. Match partition sizes (~128 MB) and auto-terminate idle clusters for maximum FinOps efficiency.

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. Why is 5 cores per Spark executor container considered the industry standard sweet spot?
2. Why should beginners check a table's grain before writing a JOIN?
3. Which Medallion layer is meant to store clean, deduplicated, standardized records?
Practice What You Learned

EX-1: Delta Lake DDL & Partitioning Strategy

Global DynaDatum Bank stores account balances at the end of every month for thousands of customers. A junior engineer previously saved these balances as plain text files with no rules, which caused balance numbers to get corrupted and queries to be painfully slow. We need an official Delta Lake table that stores balance dates, money amounts, and currencies accurately. We also want queries to run fast by organizing the files by date, and prevent duplicate balance records for the same account on the same day.

Solve Challenge