Part IX - The Anatomy of a Spark Application — What the Driver, Executors, and Cluster Manager…
From the publisher’s feed, collected in the ZeroLabs newsroom.
Part IX - The Anatomy of a Spark Application — What the Driver, Executors, and Cluster Manager Actually OwnWhy “add more executors” fixed nothing: a component-by-component breakdown of the Spark runtime, and the failure mode each component ownsPart I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IXThe Cluster That Was 97% Idle While the Job “Ran”A nightly enrichment job on Kubernetes: 64 executors, 5 cores and 20GB each — 320 cores of paid compute. One night the job’s wall-clock time jumped from 38 minutes to 4 hours 51 minutes, and the Ganglia dashboard showed executor CPU utilization flatlined at ~3% for most of that window. No failed tasks. No spill. No skew.The on-call engineer did the reflexive thing: doubled the executor count to 128. Runtime got worse — 5 hours 12 minutes. The cluster was now 97% idle at twice the price.The real culprit never showed up in executor metrics because it wasn’t on the executors. A refactor had introduced a loop that called collect() on 1,400 small lookup results and re-broadcast a rebuilt 4.2GB map on every iteration — all driver-side work. The driver pod, sized at a default 4GB with 400MB overhead, was thrashing in GC for minutes at a time between jobs. 320 cores sat idle waiting for a single JVM to finish garbage collecting.The diagnosis took hours because the team’s mental model was “Spark = executors.” Nobody was watching the one component that schedules everything, holds every query plan, serializes every task, and receives every result.So: what does each component of a Spark application — driver, cluster manager, executors, and the scheduler stack inside them — actually own, which failure modes belong to each, and which metrics tell you which one is drowning?The Component Map: Three Processes, One ContractA running Spark application is not one program. It is a set of JVM (or Python-fronted JVM) processes with a strict division of labor:The driver — one process. Owns the SparkSession, builds and optimizes query plans, splits work into jobs, stages, and tasks, schedules those tasks, tracks shuffle map output, and receives results. It is a single point of failure and a single point of contention. It does not touch your data unless you force it to.Executors — many processes. Own task execution, cached partitions, and shuffle file writes. They do the actual data work and report back. They are disposable; the driver is not.The cluster manager — YARN, Kubernetes, or standalone. Owns container placement only: it grants CPU and memory to the driver and executors, then gets out of the way. It never sees a task, a stage, or a byte of your data.Component MapThe critical asymmetry: the cluster manager’s job ends once containers are placed. Every scheduling decision after that — which task runs where, in what order, with what locality — is made by the driver. Engineers coming from MapReduce or plain Kubernetes often assume the cluster manager is load-balancing work. It isn’t. If scheduling is slow, the problem is the driver, and no cluster-manager tuning will touch it.The Driver: One JVM That Does Five JobsThe driver is where an “application” exists as a coherent thing. Inside it, five subsystems matter operationally.SparkSession and the Planning StackThe SparkSession wraps the SparkContext and the Spark SQL machinery. Every DataFrame you build is a logical plan held in driver memory; every action triggers Catalyst analysis and optimization and whole-stage code generation — all driver-side CPU. A query over a table with tens of thousands of partitions or a plan with thousands of unioned branches can take minutes to plan before a single task launches. In the Spark UI this appears as a gap between job submissions with no running stages — the signature of a driver-bound workload.DAGScheduler: Actions Become StagesWhen an action fires, the DAGScheduler walks the RDD lineage backward from the result and cuts it at every shuffle dependency. Each cut produces a stage; stages form a DAG that executes in dependency order (Part IV of this series covered the job/stage/task hierarchy in depth). Two operational consequences:The DAGScheduler also tracks shuffle map output: for every map task, the sizes and locations of the blocks it wrote, held in the driver’s MapOutputTracker. With 20,000 map tasks × 20,000 reduce partitions, that metadata alone is gigabytes of driver heap. Very wide shuffles can OOM a driver that never touches a row of data.Stage retries on shuffle-fetch failure are a driver decision. When an executor dies and its shuffle files vanish, the DAGScheduler must recompute the parent stage — the “FetchFailed → resubmitting stage” churn in your logs is this component working as designed.TaskScheduler and SchedulerBackend: Tasks Meet ContainersThe TaskScheduler takes each stage’s task set and assigns tasks to free executor slots, honoring data locality (process-local for cached partitions, then node-local, then any) with a configurable patience of spark.locality.wait (default 3s) per level. The SchedulerBackend is the transport that actually talks to executors — and, for dynamic allocation, asks the cluster manager for more.The subtle production behavior: locality wait is a delay. A stage reading cached data whose executors are busy will hold tasks back for the wait duration before falling to a worse locality level. A job that “mysteriously” idles for a few seconds between task launches on a hot cache is often just this timer.The Result Path: Where collect() LivesEvery collect(), take(), toPandas(), and broadcast build routes data through the driver's heap. This is the single most common category of driver failure:collect() on a large DataFrame — the classic OOM.toPandas() without Arrow — serializes twice and materializes fully in the driver.broadcast() of a table built from driver-side data — the driver holds the full object and its serialized form while executors fetch it.Thousands of small actions in a loop — each one pays full planning + scheduling overhead in the single driver thread pool, serializing the whole application on one JVM, which is exactly what the opening incident did.Sizing the Driver Is Not OptionalDriver defaults (often 1–4GB) are calibrated for toy jobs. Real sizing pressure comes from plan complexity, task count, shuffle-state metadata, and the result path — none of which appear in executor dashboards:# Naive: default driver, then wonder why 320 executor cores sit idle# Optimized: size the driver for its actual jobs - planning, task state,# shuffle metadata, result collection - and watch its GC, not just executors'spark = ( SparkSession.builder .config("spark.driver.memory", "16g") .config("spark.driver.memoryOverhead", "2g") # off-heap, K8s kills on the SUM .config("spark.driver.maxResultSize", "2g") # fail fast instead of OOM on collect .config("spark.scheduler.listenerbus.eventqueue.capacity", "20000") .getOrCreate())spark.driver.maxResultSize deserves special mention: it converts a silent driver OOM (which kills the whole application and every cached dataset with it) into a clean, attributable exception on the offending action.Executors: Slots, Storage, and the Shuffle ContractAn executor is a JVM with three concurrent responsibilities.Task SlotsAn executor runs up to spark.executor.cores tasks concurrently — its task slots. Each running task gets a dynamically negotiated share of the unified execution memory pool (Part V covered the memory model). The slot count is a real trade-off, not a formality:More cores per executor: better broadcast reuse (one copy serves all slots), fewer JVMs to manage, but a single GC pause stalls all slots at once, and HDFS/S3 client throughput can saturate.Fewer cores per executor: better isolation and GC behavior, but N× the broadcast copies and more overhead per container. The long-standing production sweet spot of 4–5 cores per executor exists because both failure modes get expensive beyond it.BlockManager: Every Byte Has an AddressEach executor runs a BlockManager that owns cached RDD/DataFrame partitions, broadcast blocks, and shuffle data, all registered with the driver’s BlockManagerMaster. This is why losing an executor is not just losing compute: its cached partitions must be recomputed from lineage and its shuffle files are gone, triggering the DAGScheduler stage-retry path described above.Shuffle Files Outlive Tasks — Sometimes ExecutorsMap tasks write sorted shuffle files to local disk; reduce tasks fetch them later — possibly minutes later, possibly after the writing task’s slot has moved on. This is what makes naive downscaling dangerous: kill an executor whose shuffle files a future stage needs, and you pay a recompute. The mitigations are component-level, not config trivia:External / remote shuffle service — shuffle files served by a process that outlives the executor (YARN aux service, or a remote shuffle service on K8s).Shuffle tracking for dynamic allocation — spark.dynamicAllocation.shuffleTracking.enabled=true lets Spark hold executors alive until their shuffle data is provably unneeded.Decommissioning — spark.decommission.enabled=true migrates blocks off an executor before a spot/preemptible node dies, turning a stage retry into a non-event.The Cluster Manager: A Landlord, Not a ForemanThe cluster manager grants containers and enforces resource limits. Its production relevance is concentrated in three places:The overhead boundary. YARN and Kubernetes kill containers on total memory — heap plus spark.executor.memoryOverhead (off-heap allocations, Netty buffers, and the entire PySpark worker memory). The infamous "Container killed by YARN for exceeding memory limits" is almost never a heap problem; it's off-heap usage exceeding an overhead default of max(384MB, 10% of heap), which is far too small for Python-heavy or Arrow-heavy workloads.Dynamic allocation. The driver’s ExecutorAllocationManager requests executors based on the task backlog and releases idle ones. The cluster manager only fulfills the requests. If scale-up is slow, look at cluster capacity and pod scheduling; if executors churn away and shuffle recomputes spike, look at the shuffle-tracking settings above — a driver-side policy, not a cluster-manager one.Deploy mode. In cluster mode the driver itself runs in a managed container and gets supervision and restart semantics; in client mode it runs wherever you launched it — a laptop, a notebook kernel, an edge node — with whatever memory and network that host happens to have. Long-running production jobs in client mode on an undersized edge node are a recurring outage pattern.Tracing One Action Through Every ComponentThe full life of a single write():Every arrow is a distinct failure domain. Slow planning: driver CPU. Slow task launch: driver scheduling or locality wait. Slow tasks: executor-side (skew, spill, I/O). Lost shuffle files: executor lifecycle. Container kills: overhead sizing at the cluster-manager boundary. The Spark UI encodes this map — the gap before a job appears is driver planning; the gap between stages is scheduling and shuffle metadata; the bars inside a stage are executor work.The Fix, Component by ComponentBack to the opening incident. The loop was driver-bound by construction: 1,400 sequential collect() calls plus a 4.2GB broadcast rebuilt per iteration. The repair moved the work to the components designed for it:from pyspark.sql import functions as F# Naive: driver-side loop - 1,400 collect() calls + rebroadcast per iteration# for key in keys:# lookup = spark.sql(f"SELECT ... WHERE k = '{key}'").collect()# bmap = spark.sparkContext.broadcast(build_map(lookup))# result = df.filter(...).rdd.map(lambda r: enrich(r, bmap.value))...# Optimized: one distributed join - executors do the data work,# the driver plans exactly one joblookups = spark.read.table("dim.lookups") # all 1,400 keys at onceenriched = ( df.join(F.broadcast(lookups), "k") # single broadcast, built once .withColumn("enriched_val", F.expr("...")))enriched.write.mode("overwrite").parquet("s3://out/enriched/")Result: one job instead of 1,400; the broadcast built once and served from executor BlockManagers instead of rebuilt on a GC-thrashing driver; executor utilization back above 80%. Wall-clock time: 4h51m → 31 minutes, on the original 64 executors — and the panic-scaled extra 64 were returned.The lesson generalizes into a short diagnostic order:Executors idle but job “running”? Driver: planning, scheduling, GC, or a driver-side loop. Check driver GC time and the gap between jobs in the UI.Container killed, no heap OOM in logs? Cluster-manager boundary: raise memory overhead, especially with PySpark.Stage retries with FetchFailed? Executor lifecycle: shuffle files died with an executor — shuffle service, shuffle tracking, or decommissioning.Tasks slow, evenly? Executor sizing or I/O. Tasks slow, one straggler? Skew — Part VII’s playbook.Spark’s components are a contract: the driver thinks, executors work, the cluster manager houses them. Nearly every “mystery” Spark outage is one component quietly doing another’s job.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 IX - The Anatomy of a Spark Application — What the Driver, Executors, and Cluster Manager… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.