Spark Internals and Performance Tuning for Lake Pipelines
System DesignModel answerLast updated
Explain how Spark defers and runs work across a cluster, then show how that execution model guides a measured approach to tuning slow batch and streaming jobs on Parquet/Delta data.
You own several production pipelines built with PySpark (Spark 3.x, Adaptive Query Execution available). They read multi-terabyte Parquet/Delta tables on object storage, partitioned by date, and write curated tables for downstream consumers. Some pipelines are batch; others are Structured Streaming jobs with state. Clusters have tens to hundreds of executor cores, and the data mixes huge fact tables with small dimension tables.
Answer the following as you would in a technical discussion. The execution model in Parts 1 and 2 should be the reasoning behind your tuning choices in Part 3. The goal is lower wall-clock time and lower executor-hours, not just a job that finishes.
Before tuning, state which clarifying questions you would ask. Examples are: batch or streaming, and what the freshness target is; the source file format, partitioning and file sizes; whether the pain is one slow stage, the whole job, or intermittent OOM/spill; cluster shape and dynamic allocation; whether the job is read-, join- or write-heavy; and whether skewed keys are known.
Part 1: Laziness. What does it mean that Spark is lazy? Separate transformations from actions, explain why the engine is designed this way, and give a concrete optimization that laziness makes possible.
Part 2: Distributed execution. How does Spark spread work over a cluster? Describe the roles of the driver, cluster manager and executors, the job/stage/task hierarchy, how partitions relate to parallelism, and why some operations (shuffles) cost far more than others.
Part 3: Optimization. How would you speed up or cut the cost of a slow Spark job? Start with a methodology, then cover the main levers: execution plans, shuffles, joins, partitioning, caching, file layout, skew, Python/UDF overhead and streaming.
Hints
Hint 1
Tie everything to one idea: Spark builds a whole plan lazily, and the dominant cost is moving data between executors (shuffles). Plan building, stage boundaries and tuning all follow from that.
Hint 2
For tuning, begin with evidence: find the slow stage in the Spark UI (task time spread, shuffle read/write, spill), then read the physical plan with explain. Only then pick a lever.
Hint 3
For skew, distinguish symptoms (a few tasks far longer than the median) from fixes (AQE skew join, salting, isolating hot keys, broadcasting the small side). For streaming, think about bounded state, watermarks, triggers, and input rate versus processing rate.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing: one principle
Spark records what you want as a logical plan, optimizes the whole plan at once, and then runs it as parallel tasks over partitions. The expensive part is almost always moving data between executors (a shuffle). Every tuning decision below either shrinks the data earlier, avoids a shuffle, or makes the shuffle more even.
Clarifying questions
Ask first: batch or streaming and the freshness SLA; source format, partitioning, file sizes and volume; whether the problem is one slow stage, the whole job, or OOM/spill failures; executor count, cores, memory and dynamic allocation; read-, join- or write-heavy; known hot keys. The answers decide where to look.
Part 1: Lazy evaluation
- Transformations (
select,filter,withColumn,join,groupBy().agg) only extend the logical plan and return a new DataFrame. Nothing runs. - Actions (
count,collect,show,write,foreachBatchoutput) trigger execution of the accumulated plan.
Why: because Spark sees the full plan before running anything, Catalyst can optimize globally instead of executing each step literally. Examples:
- Projection pushdown / column pruning: if the final output needs 5 of 200 columns, only those are read from Parquet.
- Predicate pushdown and partition pruning:
filter(event_date = '2024-05-01')written after a join or a view still gets pushed down to the scan, so only one date partition is listed and read. - Reordering and combining: filters move before joins, adjacent projections collapse, and narrow operations are pipelined within one stage.
Caveat: lazy means a failure or a slow step shows up at the action, and an unpersisted DataFrame used by two actions is computed twice.
Part 2: Distributed execution
Roles. The driver holds the plan, builds the DAG and schedules tasks; it should not process bulk data (avoid collect() on large results). The cluster manager (YARN, Kubernetes, standalone) allocates resources. Executors are JVM processes that run tasks and hold cached data and shuffle files.
Hierarchy. An action creates a job. The job is split into stages at shuffle boundaries. Each stage is a set of tasks, one per partition. Task count equals the degree of parallelism, and total concurrency is bounded by total executor cores.
Narrow vs. wide. Narrow transformations (filter, select, map) need only one input partition and are pipelined inside a stage. Wide ones (groupBy, join, distinct, repartition, window with partitioning) need data from many partitions and force a shuffle.
Why shuffles dominate: map-side tasks write shuffle files to local disk (serialization, possibly sort), the data crosses the network, reducers fetch and merge, and memory pressure causes spill. A stage cannot start until the previous shuffle completes, and one oversized partition makes the whole stage wait on a straggler.
Part 3: Optimization
Methodology (measure first)
- Reproduce and identify the slow stage in the Spark UI: duration, task-time distribution (min/median/max), shuffle read/write sizes, spill, GC time, and failed or retried tasks.
- Run
df.explain("formatted")and read the physical plan: scan filters and pushed predicates, join strategy, number of exchanges. - Form a hypothesis, change one thing, re-measure. Repeat on the next dominant cost.
Reduce data early
Select only the needed columns, filter as early as possible, and filter on the partition column so pruning applies. Avoid wrapping partition or filter columns in functions or casts that block pushdown. Check the scan node for PartitionFilters and PushedFilters.
Joins
- Broadcast hash join when one side is small enough to fit comfortably in each executor's memory (and the driver, since it is collected there first). Default threshold is 10 MB; raise it deliberately or use a
broadcast()hint, but only when the table is genuinely small and bounded. A wrongly broadcast large table causes OOM. - Sort-merge join for two large sides. It shuffles and sorts both, so reduce both inputs first.
- Pre-aggregate before joining when you can. Avoid accidental cross joins and duplicate-key explosions.
Skew
Symptom: a few tasks run far longer than the median and carry most of the shuffle read. Fixes, in order of effort:
- Enable AQE (
spark.sql.adaptive.enabled, skew join handling, partition coalescing), which splits oversized partitions at runtime. - Isolate hot keys (such as null or a default id): handle them separately, or filter out nulls before the join.
- Salting: append a random suffix to the hot side's key and replicate the other side across salt values. It costs extra data, so use it only for confirmed hot keys.
- Broadcast the small side if possible, which avoids shuffling the skewed side at all.
Partitioning
Target roughly 100-200 MB per shuffle partition. Too few partitions means spill and idle cores; too many means scheduling overhead and tiny tasks. repartition(n) does a full shuffle and can increase or rebalance; coalesce(n) only merges partitions without a shuffle, which suits reducing before write but can leave imbalance. Let AQE coalesce shuffle partitions rather than hand-tuning spark.sql.shuffle.partitions for each job.
File layout
The small-file problem hurts both listing and task scheduling. Aim for files of about 128 MB to 1 GB. Compact periodically (Delta OPTIMIZE, or a rewrite job), and control output files with repartition or maxRecordsPerFile. Partition by a low-cardinality column used in filters (date), not by high-cardinality keys. Use bucketing or Z-ordering/clustering only when repeated joins or filters on the same key justify it.
Caching
Cache only a DataFrame that is reused by multiple actions and expensive to recompute, and check in the UI that it fits (use MEMORY_AND_DISK if not). Unpersist when done. Caching a one-use DataFrame wastes memory and can evict useful data.
Python and UDFs
Prefer built-in functions: they stay inside the JVM and Catalyst can optimize them. Row-at-a-time Python UDFs pay serialization to and from Python workers and are opaque to the optimizer. If custom logic is unavoidable, use pandas (Arrow) vectorized UDFs, which process batches, or push the logic into SQL expressions.
Streaming
- Use watermarks so state for windowed aggregations and stream-stream joins is eventually dropped; unbounded state eventually causes OOM and slow checkpoints.
- Choose the trigger (processing-time interval, or availableNow for incremental batch) to match the SLA and avoid producing many tiny files.
- Monitor input rate vs. processing rate and batch duration; if processing falls behind, scale, cap
maxOffsetsPerTrigger/maxFilesPerTrigger, or reduce shuffle width. - Tune state store settings (such as RocksDB) for large state, and keep shuffle partition count fixed per checkpoint, since it cannot easily change.
Common mistakes
- Changing configs without looking at the UI or plan.
- Broadcasting a table that is not reliably small.
- Calling
repartitionorcachereflexively. - Using
collect()ortoPandas()on large data. - Using Python UDFs where a built-in exists.
- Ignoring file sizes and null/hot-key skew.
- Treating tuning as one-shot instead of a locate, fix, re-measure loop.