Skip to the page
Tecyfy

PySpark interview question · hard

Describe your strategy for enhancing the performance of Spark applications.

The short answerI start by measuring: find the slow stages in the Spark UI, see whether time goes to reading, shuffling, skew, spilling or Python code, and fix the biggest cause first.

The full answer

I start by measuring: find the slow stages in the Spark UI, see whether time goes to reading, shuffling, skew, spilling or Python code, and fix the biggest cause first. Most gains come from reading less data, shuffling less, and keeping work in Spark's optimised engine; configuration tuning comes after that.

1. Measure first

  • In the Spark UI, find the stages that take the most time, and look at task time distribution (one long task means skew), shuffle read and write sizes, spill to disk, and garbage collection time.
  • df.explain("formatted") shows the physical plan: join types, whether filters are pushed to the scan, and how many partitions are read.

2. Read less data

  • Columnar formats (Parquet, Delta, Iceberg) so only needed columns are read.
  • Filter early on partition columns and on columns with file statistics, so files are skipped.
  • Fix many small files: compact them (OPTIMIZE in Delta) or write fewer, larger files.

3. Shuffle less, and shuffle well

  • Broadcast small tables in joins (automatic under 10 MB by default, or with broadcast()).
  • Aggregate or filter before joins and before groupBy.
  • Keep adaptive query execution on (the default): it merges small shuffle partitions, switches joins to broadcast at runtime and splits skewed partitions.
  • Set spark.sql.shuffle.partitions sensibly for very large jobs, aiming at roughly 100–200 MB per partition.

4. Handle skew AQE's skew join handling covers most joins; for skewed aggregations or extreme cases, salt the hot keys or process them separately.

5. Stay in the optimised engine

  • Use built-in functions instead of Python UDFs; when a UDF is unavoidable, use a vectorised (pandas or Arrow) UDF.
  • Avoid collect() and toPandas() on large data.

6. Cache with purpose Cache only a DataFrame that is reused several times and expensive to compute, and unpersist() it afterwards.

7. Size the resources

  • Executors with about 4–5 cores each and enough memory per core to avoid spills; leave room for memory overhead, which Python processes use.
  • Dynamic allocation or autoscaling for variable workloads.
  • Check that the cluster actually is busy: idle cores mean too few partitions.

8. Write efficiently Partition output tables only by low-cardinality columns, avoid producing thousands of tiny files, and use table features such as clustering where the platform supports them.

9. Change one thing at a time Re-run with realistic data, compare stage times, and keep the change only if it helps.

Last updated 16 October 2026