Spark Internals

Spark Internals · the interactive interview guide

How Apache Spark actually runs your code, from spark-submit to the last task, explained for interviews. Every number on this page was checked on a real Spark 4.0 run.

This is the free starterIt has 7 core sections, 3 live simulators and 12 interview questions. The full guide adds partitions, memory deep-dives, caching, Catalyst, joins, shuffle, AQE & skew, tuning, 24 failure and incident stories, 7 verified PySpark labs, 45 interview questions, a quiz and a cheat sheet. See the full guide →

1. Why Spark, and the five core ideas

Hadoop MapReduce wrote intermediate results to disk between every map and reduce step. Spark keeps data in memory between steps where possible, plans the whole pipeline as a DAG before running it, and gives you one engine for batch, SQL, streaming and ML. That's why it's often 10–100× faster for multi-step jobs.

IdeaWhat it meansWhy interviewers care
RDD → DataFrame → DatasetRDD: low-level distributed collection of objects. DataFrame: distributed table with a schema, optimised by Catalyst. Dataset: typed DataFrame (Scala/Java only).Use DataFrames: the optimiser and Tungsten only help you there.
Transformations vs actionsTransformations (filter, select, groupBy, join) build a plan. Actions (count, collect, show, write) run it.Every action = at least one job.
Lazy evaluationNothing runs until an action. Spark first sees the whole pipeline, then optimises it (pushes filters down, prunes columns, picks join strategies).Explains why cache() does nothing on its own.
Narrow vs wideNarrow: each output partition needs one input partition (filter, map, coalesce). Wide: needs data from many partitions, so a shuffle (groupBy, join, repartition, orderBy).Wide transformations create stage boundaries.
Lineage & fault toleranceSpark remembers how each partition was computed. If an executor dies, it recomputes just the lost partitions from their lineage.No replication needed for intermediate data.

2. Architecture

Driver SparkSession / SparkContext DAGScheduler → stages TaskScheduler → tasks Spark UI (:4040) Cluster manager YARN · Kubernetes · Standalone 1. ask for executors 2. launch Executor 1 (JVM) · 5 cores task task task task task memory: cache blocks + shuffle data Executor 2 (JVM) · 5 cores … up to N executors on many nodes 3. send tasks (code + partition) 4. results / status / heartbeats
ComponentRole
DriverRuns your main(), builds the plan, splits it into jobs → stages → tasks, schedules tasks, tracks where cached and shuffle blocks live, and collects results. One per application. If it dies, the application dies.
Cluster managerHands out resources (containers or pods). YARN ResourceManager, Kubernetes API server, or the Spark Standalone master. It doesn't run your code.
ExecutorA JVM process on a worker node. It runs tasks in its cores (1 task per core at a time), stores cached partitions and shuffle files, and reports back to the driver.
TaskThe smallest unit of work: one task processes one partition through one stage.

Client deploy mode

The driver runs on the machine where you ran spark-submit (your laptop or an edge node). Logs and output appear in your terminal. Good for interactive work and notebooks. If you close the terminal, the job dies.

Cluster deploy mode

The driver runs inside the cluster (in the YARN ApplicationMaster container or a driver pod). The submitting machine can disconnect. Use it for production and scheduled jobs.

3. What happens when you run spark-submit

spark-submit --master yarn --deploy-mode cluster \
  --num-executors 4 --executor-cores 5 --executor-memory 19g --driver-memory 4g \
  --conf spark.sql.shuffle.partitions=200 \
  orders_job.py
  1. spark-submit parses options, packages your code and dependencies, and contacts the cluster manager (here, the YARN ResourceManager).
  2. The ResourceManager starts an ApplicationMaster container on some node. In cluster mode the driver runs inside it. In client mode the driver is on your machine and the AM only negotiates resources.
  3. The driver starts and creates the SparkSession / SparkContext, the entry point that talks to the cluster.
  4. The driver asks for executors (4 × 5 cores × 19 GB + overhead). The ResourceManager grants containers, and the NodeManagers launch executor JVMs.
  5. Executors register with the driver and start sending heartbeats.
  6. Your code runs on the driver. Transformations just build a logical plan. When an action is reached, Catalyst optimises the plan into a physical plan and a job is created.
  7. The DAGScheduler splits the job into stages at every shuffle boundary. The TaskScheduler sends one task per partition to free executor cores, preferring nodes that already hold the data (data locality).
  8. Executors run the tasks: they read input, write shuffle files for the next stage, and report status and metrics. Failed tasks are retried (4 attempts by default).
  9. When the last stage finishes, results go to the driver (collect) or storage (write). After the final action, spark.stop() releases the executors and the application ends.

4. Jobs, stages and tasks

Job

Created by an action. Some actions create extra jobs: orderBy runs a sampling job first, a broadcast join collects the small table in its own job, and with AQE every shuffle stage runs as a separate job.

Stage

A run of narrow operations with no shuffle in between. Every wide transformation (an Exchange in explain()) ends one stage and starts another.

Task

One per partition per stage. Stage 1 reading 8 partitions = 8 tasks. After a shuffle, spark.sql.shuffle.partitions (default 200) tasks, unless AQE coalesces them.

LabJob & stage builderrules checked against real Spark 4.0 runs (AQE off)
AQE on
Presets:

5. Cluster capacity, parallelism and task waves

Worked example: a 12-node cluster, each node 24 cores / 96 GB. Your job gets 6 executors of 5 cores and reads a 25 GB file. How many executors fit, how many tasks run, and how long does it take? Change any number to try your own cluster.

LabCapacity, partitions and waves calculator
Three things most sizing answers get wrong. (1) The memory per node divided by executors is the container. Spark adds spark.executor.memoryOverhead (max(384 MB, 10%)) on top of spark.executor.memory, so for a 23 GB container set --executor-memory ≈ 20g (23 ÷ 1.1 ≈ 20.9). (2) Leave 1 core and 1 GB per node for the OS and the NodeManager. (3) "File size ÷ 128 MB" is only the partition count when there are few cores. Spark sizes splits as min(maxPartitionBytes, totalBytes / defaultParallelism), so with all 240 cores the same 25 GB file becomes about 240 partitions of ~107 MB. This is verified in Lab 2.

Fat vs thin executors

Thin (1 core each)Balanced (~5 cores)Fat (all cores)
Parallelism inside one JVMNoneGoodHigh
Broadcast copies / overheadOne per core: wastefulReasonableMinimal
HDFS/S3 client throughputOKGood (the classic "5 cores" rule)Degrades with too many threads
GC pausesSmall heapsOKHuge heaps: long GC

6. Executor memory management

Since Spark 1.6, executors use the unified memory manager. Here is the breakdown, made exact:

LabExecutor memory calculator
Reserved 300 MBUser memoryStorage (cache)Execution (shuffle/join/sort)Overhead (outside heap)
RegionSizeHolds
Reserved300 MB fixedSpark's internal objects
User memory(heap − 300 MB) × (1 − 0.6)Your data structures, UDF objects, RDD operations' internal metadata
StorageSpark memory × 0.5 (a soft line)Cached partitions, broadcast variables
ExecutionSpark memory × 0.5 (a soft line)Shuffle buffers, hash tables for joins and aggregations, sort buffers
Overhead (outside heap)max(384 MB, 10% of heap)JVM internals, thread stacks, NIO buffers, Python workers for PySpark UDFs
The borrowing rules (interview favourite)Execution and storage share one pool. Execution can borrow free storage memory, and can evict cached blocks back down to the storage threshold. Storage can borrow free execution memory, but can never evict execution. Running tasks win over cache. Each of N running tasks gets between 1/(2N) and 1/N of execution memory. When a task can't get more, it spills to disk, which is slow but not fatal. OOM happens with things that can't spill: huge rows or arrays, collect(), oversized broadcasts, or too much user/overhead memory.

7. Interview questions

Filter by level, or search. The questions asked most often are tagged Most asked. Try to answer out loud before you open each one.

Flashcards: quick revision

Click a card to flip it.

Want the rest?

The full Spark Internals guide covers the topics that decide senior interviews: partitions & file sizing, executor memory, partial caching, Catalyst plans, all five join strategies, shuffle internals, AQE & data skew, aggregation strategies and a 12-step tuning playbook, plus 7 PySpark labs verified on Spark 4.0.1, 45 interview questions, 24 real failure stories, a quiz, a printable PDF and a flashcard deck.

Get the full guide