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.
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.
| Idea | What it means | Why interviewers care |
|---|---|---|
| RDD → DataFrame → Dataset | RDD: 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 actions | Transformations (filter, select, groupBy, join) build a plan. Actions (count, collect, show, write) run it. | Every action = at least one job. |
| Lazy evaluation | Nothing 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 wide | Narrow: 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 tolerance | Spark 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
| Component | Role |
|---|---|
| Driver | Runs 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 manager | Hands out resources (containers or pods). YARN ResourceManager, Kubernetes API server, or the Spark Standalone master. It doesn't run your code. |
| Executor | A 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. |
| Task | The 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
- spark-submit parses options, packages your code and dependencies, and contacts the cluster manager (here, the YARN ResourceManager).
- 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.
- The driver starts and creates the SparkSession / SparkContext, the entry point that talks to the cluster.
- The driver asks for executors (4 × 5 cores × 19 GB + overhead). The ResourceManager grants containers, and the NodeManagers launch executor JVMs.
- Executors register with the driver and start sending heartbeats.
- 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.
- 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).
- 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).
- 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.
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.
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 JVM | None | Good | High |
| Broadcast copies / overhead | One per core: wasteful | Reasonable | Minimal |
| HDFS/S3 client throughput | OK | Good (the classic "5 cores" rule) | Degrades with too many threads |
| GC pauses | Small heaps | OK | Huge heaps: long GC |
6. Executor memory management
Since Spark 1.6, executors use the unified memory manager. Here is the breakdown, made exact:
| Region | Size | Holds |
|---|---|---|
| Reserved | 300 MB fixed | Spark's internal objects |
| User memory | (heap − 300 MB) × (1 − 0.6) | Your data structures, UDF objects, RDD operations' internal metadata |
| Storage | Spark memory × 0.5 (a soft line) | Cached partitions, broadcast variables |
| Execution | Spark 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 |
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