Apache Spark
Driver and executors, lazy evaluation, shuffles, join strategies, data skew, AQE, and job tuning.
12 questions
JuniorTheoryVery commonWhat do the Spark driver and executors each do, and why can collect() crash the driver?
What do the Spark driver and executors each do, and why can collect() crash the driver?
The driver builds the plan and schedules tasks; executors run those tasks on partitions, with resources from the cluster manager. collect() or toPandas() copies every row into the single driver process, so a large result exhausts its memory.
Common mistakes
- ✗Thinking
collect()keeps the data distributed and returns only a handle - ✗Believing the driver processes partitions itself instead of scheduling tasks
- ✗Adding executors to fix a driver OOM caused by
collect()
Follow-up questions
- →A 200 MB dataset: would you reach for Spark or pandas, and why?
- →Where does the driver run in client versus cluster deploy mode?
JuniorTheoryVery commonSpark transformations return instantly — what triggers execution, and why do errors surface later?
Spark transformations return instantly — what triggers execution, and why do errors surface later?
Transformations (filter, select, join) only add steps to a logical plan. An action — count, collect, show, write — makes Catalyst optimise the whole plan and run a job, so a runtime error, like a UDF failing on a row, surfaces there.
Common mistakes
- ✗Thinking
cache()runs the job, when it too waits for the next action - ✗Debugging the action line the trace points at instead of the transformation that broke
- ✗Assuming each transformation is optimised alone rather than the whole plan together
Follow-up questions
- →Why do two actions on the same uncached DataFrame read the source twice?
- →Which errors does PySpark raise at once, before any action runs?
JuniorTheoryVery commonNarrow vs wide transformations in Spark — which ones cause a shuffle, and why is it costly?
Narrow vs wide transformations in Spark — which ones cause a shuffle, and why is it costly?
Narrow (filter, select, withColumn): each output partition comes from one input partition. Wide (groupBy, distinct, orderBy, a non-broadcast join) needs rows from many, so Spark shuffles — disk write, network, re-read — and starts a new stage.
Common mistakes
- ✗Counting every
joinas wide, forgetting a broadcast join does not shuffle the large side - ✗Thinking a shuffle stays in memory and costs only CPU
- ✗Classifying operations by how many columns they touch, not where input rows come from
Follow-up questions
- →Is
unionnarrow or wide, and what aboutcoalesce? - →Why does
orderBylaunch an extra job before its shuffle?
MiddleDebuggingVery commonOne Spark join task runs for hours while the rest finish — diagnose it from the stage metrics
One Spark join task runs for hours while the rest finish — diagnose it from the stage metrics
Skew: the max task's shuffle read (46 GB) and time are hundreds of times the median, so a few user_id values hold most rows. Too few partitions would make every task slow and spill. Find the hot key with groupBy('user_id').count() sorted descending.
Common mistakes
- ✗Raising
spark.sql.shuffle.partitions, which cannot split a single hot key - ✗Reading the max alone without comparing it with the median and quartiles
- ✗Blaming executor memory when only one task spills
Follow-up questions
- →How would you fix this join if you cannot turn AQE on?
- →What would AQE's skew-join handling do with this 46 GB partition?
JuniorCodeCommonSet a DataFrame's partition count with repartition or coalesce
Set a DataFrame's partition count with repartition or coalesce
Read the count via df.rdd.getNumPartitions(). To lower it, coalesce(n) merges partitions without a shuffle but can only reduce (coalesce(50) on 10 stays 10); to raise it, repartition(n) shuffles fully. coalesce(1) squeezes upstream work into one task.
Common mistakes
- ✗Expecting
coalesce(50)to raise 10 partitions to 50 - ✗Putting
coalesce(1)before a write and making the whole stage single-threaded - ✗Thinking
repartitionavoids a shuffle because it only renumbers partitions
Follow-up questions
- →When is
repartition(n)the better way to lower the partition count? - →What does
repartition('col')give you thatrepartition(n)does not?
MiddleTheoryCommonWhat does adaptive query execution AQE change at run time, and what can't it fix?
What does adaptive query execution AQE change at run time, and what can't it fix?
On by default since 3.2, AQE re-plans after each shuffle from real sizes: it merges small partitions, swaps a sort-merge join for broadcast when a side proves small, and splits skewed join partitions (over 5× median and 256 MB). UDF cost and file layout stay.
Common mistakes
- ✗Believing AQE is off unless enabled, or that it became the default in 3.0
- ✗Expecting AQE to split a hot key in a window over that key
- ✗Assuming a run-time switch to broadcast is as cheap as planning one up front
Follow-up questions
- →Why can an AQE-converted broadcast join cost more than a planned one?
- →Which settings decide when AQE treats a join partition as skewed?
MiddlePerformanceCommonSpark skipped the broadcast join you expected for a small filtered table — why, and what does forcing it risk?
Spark skipped the broadcast join you expected for a small filtered table — why, and what does forcing it risk?
Spark broadcasts a side only if its size estimate is under spark.sql.autoBroadcastJoinThreshold (10 MB). Without CBO statistics a filter keeps the input's estimate, so a filtered 2 GB table still looks 2 GB. AQE may switch at run time; a hint forces it, risking OOM.
Common mistakes
- ✗Assuming the threshold is checked against the real post-filter size
- ✗Forcing
broadcast()on a side that later grows past executor or driver memory - ✗Raising the threshold globally instead of fixing statistics or hinting one join
Follow-up questions
- →How do
ANALYZE TABLEcolumn statistics change the planner's size estimate? - →Why can't Spark broadcast the left side of a left outer join?
MiddleCodeCommonCount the jobs, stages and tasks a short PySpark snippet launches
Count the jobs, stages and tasks a short PySpark snippet launches
Two actions, two jobs; transformations run nothing. write has 2 stages split at the groupBy shuffle: 40 scan tasks, then 200 for the final sum, filter and write. count() recomputes from the source in 3 stages: 40, 200, then 1 task for the global count.
Common mistakes
- ✗Counting one job per line of code instead of one per action
- ✗Assuming
count()reuses the write's work when nothing was cached - ✗Equating the task count with executor cores instead of partitions
Follow-up questions
- →How would the stage and task counts change with AQE left on?
- →What would
top.cache()before the write change for thecount()job?
MiddlePerformanceCommonWhy is a Python user-defined function udf so much slower than Spark's built-in functions?
Why is a Python user-defined function udf so much slower than Spark's built-in functions?
A Python UDF runs in Python workers beside the executor JVM: rows are serialised there and back, and Catalyst sees a black box — no codegen, no filter on its output reaching the scan. Rewrite it with built-ins; if Python is a must, a pandas UDF works on Arrow batches.
Open full question →Common mistakes
- ✗Blaming Python arithmetic speed instead of the per-row serialisation
- ✗Expecting a filter on the UDF's result to be pushed down to the scan
- ✗Reaching for a pandas UDF before checking whether built-ins express the logic
Follow-up questions
- →What does Arrow change for a pandas UDF compared with a plain Python UDF?
- →How would you spot a Python UDF's cost in the physical plan?
MiddleDebuggingCommonA daily Spark write leaves tens of thousands of tiny files — find and fix the cause
A daily Spark write leaves tens of thousands of tiny files — find and fix the cause
Each task writes one file per country it holds, so 2,000 mixed tasks × 30 countries ≈ 60,000 files. Add repartition('country') before the write so each country's rows meet in one task, and cap files with maxRecordsPerFile. Old files need compaction.
Common mistakes
- ✗Using
coalesce(1)and collapsing the scan and filter into one task - ✗Blaming
appendmode instead of the tasks × partition values product - ✗Repartitioning by country without capping file size for a dominant country
Follow-up questions
- →How would you compact files already written without a table format?
- →What does one dominant country do to this write after
repartition('country')?
SeniorDebuggingCommonSpark executors keep dying with OOM in one stage — triage the cause from the log
Spark executors keep dying with OOM in one stage — triage the cause from the log
A skewed data slice: task 37 fails on four hosts in a row, reading 52 GB against a 110 MB median. A bad node would fail on one host, a lost shuffle would show FetchFailedException, and the driver is healthy. Spread the key — salting or AQE's skew join.
Common mistakes
- ✗Doubling executor memory, which only moves the wall for a growing hot key
- ✗Raising shuffle partitions, which cannot split a single key's rows
- ✗Treating repeated failures of one task as flaky hardware
Follow-up questions
- →What would a
FetchFailedExceptionin this stage tell you instead? - →When does raising
spark.executor.memoryOverheadfix an executor kill?
SeniorCodeOccasionalSalt a Spark join on one hot customer key with AQE turned off
Salt a Spark join on one hot customer key with AQE turned off
Salt the hot key's orders with a random 0..N-1 (others get 0), copy the hot customer row once per salt, and join on (customer_id, salt): each order still matches exactly one row. Aggregate by customer_id from sums and counts, not by averaging per-salt means.
Common mistakes
- ✗Salting both sides randomly, so most orders never meet their customer row
- ✗Averaging per-salt averages, which overweights small salt groups
- ✗Replicating the whole 20 GB dimension N times instead of only the hot keys
Follow-up questions
- →How do you choose N, and what does too large an N cost?
- →What would AQE's skew-join handling do here if it were turned on?