Part XIX — Spark on Kubernetes: Executor Sizing and Dynamic Allocation
From the publisher’s feed, collected in the ZeroLabs newsroom.
Kubernetes killed our executors every night for a week while the JVM insisted memory was fine. The JVM was telling the truth — it just wasn’t the memory Kubernetes was measuring.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVI | Part XVII | Part XVIII | Part XIXThe Executors That Kept Dying at 2 AMThe page came at 2:14 AM on a Tuesday: the overnight ETL had failed. Again. The third night in a row, and the fourth time that week if you counted Sunday’s partial run. Each time the same signature — executors dying mid-stage with exit code 137, the job restarting from the last shuffle boundary, and the whole thing stretching from its usual 90 minutes to 5 hours and 12 minutes before finally limping across the finish line or giving up.Here’s what made it maddening: the Spark UI showed nothing wrong. Executor heap usage hovered at 55–65%, GC looked healthy, no skew (Part VII’s playbook came back clean), no spill warnings. The driver was calm. By every metric Spark itself reported, the job was fine — and yet Kubernetes kept killing executors like it had a grudge.The kill count told the real story: 43 OOMKills in one night across 48 executors, each one forcing its shuffle outputs to be recomputed, each recompute triggering a retry storm that made the survivors work harder and die faster. We had configured each executor with 8 GB of heap, confident that was generous for the workload. Kubernetes disagreed, silently, at 2 AM, every night.So: why does Kubernetes kill a JVM that reports healthy memory — and how do you size executors for the scheduler that’s actually in charge?The Mechanic Underneath: The Pod Is the Unit of AccountingHere is the mental model: the JVM manages heap; Kubernetes manages the cgroup; and the cgroup always wins. When you set spark.executor.memory=8g, you've configured the JVM's heap ceiling — not the pod's memory footprint. The pod also carries everything off-heap: Netty shuffle buffers, direct byte buffers, native libraries, thread stacks, GC bookkeeping, and Spark's own memory overhead. Kubernetes sums all of it against the pod's memory limit, and when the total crosses the line, the OOM killer fires. Exit 137. No warning, no heap dump, no appeal.This is why Spark’s metrics lied to us. The UI reports heap. The killer measures the cgroup. Our executors were running at 60% heap and 104% of their pod limit — healthy by Spark’s books, dead by Kubernetes’.Part IX of this series broke down what the driver, executors, and cluster manager each own. On Kubernetes, add one more owner: the kubelet, which enforces the one limit Spark never sees.Memory Overhead Is Not a Tuning Knob — It’s PhysicsSpark knows about this gap, which is why spark.executor.memoryOverhead exists. The default is max(384MB, 10% of executor memory) — for our 8 GB executors, 800 MB of headroom above heap. The problem: off-heap usage doesn't scale politely with heap. Shuffle-heavy stages allocate large Netty buffers and direct memory that can spike well past 10%, especially with wide joins or big aggregations. Our 800 MB of overhead was being eaten by shuffle buffers alone during the join stage; the rest — thread stacks, native code, page cache pressure — pushed the pod over the limit.The rule that actually holds: size the pod limit as heap + measured off-heap peak + margin, not heap + 10% and hope. The 10% default is a starting guess for average workloads. Shuffle-heavy ETL is not an average workload.Big Executors Are a Scheduling TaxOur original instinct had been fat executors: 12 cores, 32 GB heap each, fewer pods to manage. On YARN that instinct is often fine. On Kubernetes it’s a scheduling tax with three line items:Bin-packing: a 12-core pod only schedules where 12 contiguous cores are free. On a busy cluster, fat pods sit in Pending while small pods flow around them. We watched executors wait 9 minutes for placement on nights the cluster was warm.Blast radius: one OOMKill on a 12-core executor loses 12 cores of shuffle output at once. The retry storm is proportional to executor size.Task granularity: Spark parallelizes at the task level; a 12-core executor needs 12 concurrent tasks to stay busy. Narrow stages and small partitions leave cores idle — the “97% idle cluster” failure mode from Part IX, wearing a Kubernetes costume.The sane band for K8s executors is boring on purpose: 4–5 cores, 12–16 GB heap each. Small enough to schedule anywhere, small enough that a kill is a flesh wound, granular enough to keep cores fed.Match the node pool to the pod shape while you’re at it. If your executors request 4 cores and 15 GB, a node with 16 cores and 64 GB fits exactly four of them with no stranded capacity. Nodes sized as clean multiples of your executor shape turn bin-packing from a scheduling lottery into arithmetic — and it’s the cheapest utilization win on this whole page.Dynamic Allocation on Kubernetes Is Not YARN’s Dynamic AllocationThis is the trap that bites every YARN veteran. On YARN, dynamic allocation leans on the external shuffle service — executors can be killed and their shuffle data survives. On Kubernetes there is no external shuffle service by default. If the autoscaler (or idle timeout) kills an executor holding shuffle output, that output is gone, and every downstream stage recomputes it.Spark 3.x added shuffle tracking on Kubernetes (spark.dynamicAllocation.shuffleTracking.enabled=true) as the answer: the driver tracks which executors hold shuffle data needed by running stages and refuses to decommission them. It works — but understand what it costs:Executors pin longer. Shuffle-tracking executors can’t be reclaimed until their data is consumed, so your “dynamic” allocation is stickier than the name suggests.Idle timeout still applies (spark.dynamicAllocation.executorIdleTimeout, default 60s) — but only to executors with no useful state.Scale-down is lazy, scale-up is eager. New executors appear fast; old ones linger. Budget for the tail.The alternative — running a shuffle service as a DaemonSet on K8s — exists but is operationally heavy and rarely worth it. Shuffle tracking plus sensible min/max executor bounds covers nearly every workload.One more K8s-specific wrinkle: scale-up requests go through the Kubernetes scheduler, not Spark’s. spark.dynamicAllocation.initialExecutors controls how many pods Spark requests at startup, but every scale-up beyond that is a pod-creation round trip — image pull, scheduling, JVM warm-up — typically 30–90 seconds before the executor registers. If your stages are short and bursty, that latency eats the benefit of elasticity entirely; you'll finish the stage on the initial executors before the reinforcements arrive. For bursty workloads, a higher initialExecutors with a tight idle timeout beats a low floor with aggressive scale-up.The Fix, and What It Cost# Naive: throw heap at the problem and hope the killer goes away.# The OOMKills continued — off-heap spikes don't respect heap settings.conf = ( SparkConf() .set("spark.executor.instances", "48") .set("spark.executor.cores", "12") # fat executors, slow scheduling .set("spark.executor.memory", "16g") # bigger heap, same 10% overhead guess .set("spark.kubernetes.executor.limit.cores", "12"))# Optimized: right-size the pod, make overhead explicit, let allocation breathe.# Naive: 48 fat executors, 16g heap, default overhead, static allocation.# Optimized: small executors, measured overhead, shuffle-tracked dynamic allocation.conf = ( SparkConf() # Small executors: schedule fast, die cheap .set("spark.executor.cores", "4") .set("spark.executor.memory", "12g") # Overhead sized from MEASURED off-heap peaks, not the 10% default .set("spark.executor.memoryOverheadFactor", "0.25") # 3g overhead on 12g heap # Pod limit = heap + overhead + margin; the kubelet enforces the SUM .set("spark.kubernetes.memoryOverheadFactor", "0.25") # Dynamic allocation with shuffle tracking (no external shuffle svc on K8s) .set("spark.dynamicAllocation.enabled", "true") .set("spark.dynamicAllocation.shuffleTracking.enabled", "true") # don't kill shuffle holders .set("spark.dynamicAllocation.minExecutors", "8") .set("spark.dynamicAllocation.maxExecutors", "64") .set("spark.dynamicAllocation.executorIdleTimeout", "120s") # let stragglers finish # Keep shuffle partitions proportional to the smaller executors .set("spark.sql.shuffle.partitions", "512") # 64 exec x 4 cores x 2)How we sized the overhead honestly: one canary run with the overhead factor at 0.4, watched the pod’s actual peak RSS via kubelet metrics, then set the factor to measured peak + 20% margin. No guessing.Results, measured over the following two weeks:OOMKills: 43/night → 0. Not reduced — eliminated.Job wall-clock: 5h12m (worst night) → 1h48m steady. The retry storms were the real cost, not the kills.Scheduling delay: 9-minute Pending waits → under 40 seconds. Small pods pack anywhere.Cluster utilization: 31% → 74% on the same node pool, because dynamic allocation actually released idle executors instead of holding 48 fat ones hostage.Cost: ~38% lower nightly spend on the same workload — fewer nodes held, no recompute storms.The Catch: What Right-Sizing Doesn’t FixDynamic allocation and streaming mix badly. Structured Streaming wants stable executors; aggressive scale-down fights the micro-batch cadence. For streaming on K8s, prefer fixed executor counts and tune from there.Shuffle tracking isn’t free. The driver does more bookkeeping, and pinned executors mean your “dynamic” floor is higher than minExecutors suggests during shuffle-heavy phases. Watch it; don't assume.Spot and preemptible nodes are shuffle Russian roulette. A preemption is an OOMKill with better PR — shuffle data on that node is gone either way. If you run executors on spot, keep maxExecutors generous and accept recompute as a line item, or keep shuffle-critical stages on on-demand.The driver is still a single point of failure. All of this is executor hygiene. Driver sizing, driver pod disruption budgets, and driver retry policy are a separate incident waiting to happen — and the kubelet will kill an oversized driver just as happily.TakeawaysThe kubelet measures the cgroup, not the heap: a JVM at 60% heap can still be OOMKilled if off-heap pushes the pod over its limit.Overhead is physics, not a default: max(384MB, 10%) is a starting guess — size it from measured pod RSS peaks plus margin.Small executors schedule faster and die cheaper: 4–5 cores and 12–16 GB heap beats fat pods on bin-packing, blast radius, and task granularity.No shuffle service on K8s by default: use shuffle tracking so dynamic allocation never kills an executor holding live shuffle data.Scale-up is eager, scale-down is lazy: budget for the sticky tail of shuffle-pinned executors.The retry storm is the real cost: one OOMKill is cheap; the recompute cascade it triggers is what turns 90 minutes into 5 hours.The scheduler is always in charge — the only question is whether you’ve sized for the one that’s actually enforcing the limits.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XIX — Spark on Kubernetes: Executor Sizing and Dynamic Allocation was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.