DataEng Hub
PySparkadvancedArticle · 11 min read

PySpark Performance Tuning Checklist for Production Jobs

A field checklist for slow or expensive PySpark jobs: baseline first, then read less, shuffle less, balance the work, compute smarter, use memory well and write right.

Balaji S.
Lead Data Engineer

TL;DR

  • Measure first. Record runtime, cost, the slowest stage and its spill before changing anything. Change one thing at a time.
  • Most wins come from doing less work, not from configs: read fewer columns and files, shuffle less, avoid Python UDFs.
  • Then balance the work: AQE on, skew handled, partitions sized around 100–200 MB.
  • Use memory deliberately: cache only what's reused, size executors for the stage that needs it.
  • Write right: sensible file sizes and no repartition(2000) or coalesce(1) habits.
  • Configs come last. A job that reads 10× too much data won't be saved by a better shuffle.partitions.

The problem

NorthBridge's platform team inherited 140 PySpark jobs after a reorganisation. Monthly compute spend had doubled in a year. Nobody knew which jobs were slow because of data growth and which were slow because of code.

They needed a repeatable review: something a mid-level engineer could run against any job in an hour and come back with a ranked list of fixes. This is that checklist, in the order that paid off most across those 140 jobs.

Key concepts

Concept What it means Why it matters here
Baseline Runtime, cost and key metrics of the current job Without it, you can't tell if a change helped
Pruning Skipping columns and files you don't need Cheapest possible speed-up
Shuffle Moving data between executors Usually the most expensive step
Pushdown Filters evaluated in the scan, before rows reach Spark Turns a full scan into a targeted read
Photon Databricks' vectorized native engine Faster on SQL/DataFrame operators, not Python UDFs
Optimized writes Delta shuffling before write to make right-sized files Fixes small files at the source

The six areas of the checklist: read less, shuffle less, balance the work, compute smarter, memory and cache, write right Roughly in the order they pay off.

Step 0 — Baseline

Before touching code, record:

Measure Where
Wall-clock runtime, per task in multi-task jobs Job run page
Cost (DBUs) system.billing.usage filtered to the job
Slowest stage, its max vs median task time Spark UI → Stages (or query profile)
Shuffle read/write totals, spill Spark UI → Stages
Input bytes and files read SQL tab → scan node
Output files and average size DESCRIBE DETAIL on the target
-- Cost of one job over the last 30 days (Unity Catalog system tables)
SELECT usage_date,
       SUM(usage_quantity) AS dbus
FROM system.billing.usage
WHERE usage_metadata.job_id = '123456789'
  AND usage_date >= current_date() - INTERVAL 30 DAYS
GROUP BY usage_date
ORDER BY usage_date;

Then work through the areas below. After each change: re-run on the same input, compare with the baseline, keep or revert. The Spark UI walkthrough is in Reading the Spark UI.

1 · Read less

Select only the columns you use. Parquet and Delta are columnar; unused columns are never read if you don't ask for them.

# Databricks Runtime 16.4 LTS+, PySpark
from pyspark.sql import functions as F
 
sales = (spark.table("northbridge.silver.sales_lines")
              .select("sale_date", "store_id", "sku", "net_amount"))   # 4 of 62 columns

Filter early, on columns that can be pushed down. Filters on raw columns are pushed into the scan and use file statistics to skip files. Filters on expressions often aren't.

# Can skip files using min/max stats on sale_date
sales.where(F.col("sale_date") >= "2026-11-01")
 
# Usually can't: the function hides the column from data skipping
sales.where(F.date_format("sale_date", "yyyy-MM") == "2026-11")

Check the scan node in the SQL tab: files pruned vs files read, and the pushed filters list.

Lay the data out for the filters people use. Liquid clustering (or partitioning for very large tables) on the common filter columns makes skipping work. See Liquid Clustering vs Partitioning vs Z-Order.

No schema inference in production. inferSchema=true reads the data an extra time and can guess types differently from one day to the next.

schema = "store_id INT, sku STRING, qty INT, net_amount DECIMAL(18,2), sale_ts TIMESTAMP"
raw = spark.read.schema(schema).option("header", True).csv(path)

Avoid tiny input files. Planning and per-file overhead grow with file count. Compact upstream tables; see The Small Files Problem.

2 · Shuffle less

Broadcast small dimensions. If one side of a join is small (tens of MB, sometimes a few hundred), broadcasting it avoids shuffling the big side.

stores = spark.table("northbridge.silver.stores")          # 2,400 rows
enriched = sales.join(F.broadcast(stores), "store_id")

Spark does this automatically below spark.sql.autoBroadcastJoinThreshold (10 MB) when it has statistics, and AQE can switch at runtime. Details in Broadcast vs Sort-Merge vs Shuffle Hash Join.

Aggregate before joining. Join 3 million daily store-SKU totals, not 2 billion sales lines, to the product dimension.

daily = sales.groupBy("sale_date", "store_id", "sku").agg(F.sum("net_amount").alias("net"))
result = daily.join(F.broadcast(products), "sku")

Drop shuffles you don't need. Common ones: orderBy before a write nobody reads in order, distinct() "just in case", dropDuplicates() on data that's already unique, repartition() before a groupBy on the same key.

Don't shuffle the same thing twice. If three outputs each join sales to customers, join once, cache or write the result, then branch.

3 · Balance the work

AQE on, and read the final plan. It's the default, but confirm in the Environment tab and check isFinalPlan=true in the SQL tab. See Why AQE Coalesces Shuffle Partitions.

Size the shuffle. Start the partition count high enough for your largest shuffle (about shuffle size / 128 MB) and let AQE merge small ones; on Databricks, spark.sql.shuffle.partitions = auto.

Check max vs median. In the slowest stage, max task time more than ~5× the median is skew. Fix the key before you salt; see Data Skew in Spark.

Input partitions. spark.sql.files.maxPartitionBytes (128 MB) controls how big each scan task is. Lower it for very wide rows or heavy per-row work; raise it for cheap scans over many files.

4 · Compute smarter

Built-in functions over Python UDFs. A Python UDF serializes every row to a Python worker and back, and Photon can't accelerate it. Most string, date, JSON and array logic has a built-in.

# Slow: Python UDF
@F.udf("string")
def clean_sku(s):
    return s.strip().upper().replace("-", "") if s else None
 
# Fast: built-ins, optimizable, Photon-friendly
F.upper(F.regexp_replace(F.trim("sku"), "-", ""))

When you truly need Python, use a pandas (vectorized) UDF. Full comparison in PySpark UDF vs Pandas UDF vs Built-ins.

No withColumn in long loops. Each call adds a projection to the plan; hundreds of them make planning slow and can hit stack limits.

# Slow to plan
for c in cols:
    df = df.withColumn(c, F.trim(F.col(c)))
 
# One projection
df = df.withColumns({c: F.trim(F.col(c)) for c in cols})        # Spark 3.3+

Keep data in Spark. collect(), toPandas() and Python loops over rows move work to a single driver process. If the result is big, write it; if you need a value, aggregate first.

# Emptiness check: don't count 2 billion rows
if df.isEmpty():          # Spark 3.3+; stops at the first row
    ...

Use Photon for SQL- and DataFrame-heavy jobs on Databricks. It speeds up scans, joins, aggregations and writes; it doesn't speed up Python UDFs, and parts of a plan it can't run fall back to the regular engine. Check the plan for Photon operators.

Avoid actions you don't need. Every count(), show() or display() in a production job is a separate job that may recompute everything before it. Remove debug actions or cache the DataFrame they're computed from.

5 · Memory and cache

Cache only what's reused, and release it. A DataFrame used by two or more actions in the same job is a candidate; anything used once isn't.

base = enriched.where("sale_date >= '2026-10-01'").cache()
base.count()                           # materialize once
write_store_report(base)
write_sku_report(base)
base.unpersist()

Serverless compute doesn't support cache()/persist(); write an intermediate table instead. Full guide: cache vs persist vs checkpoint.

Watch spill and GC. Spill on most tasks means partitions are too big for memory per core: more partitions, a smaller AQE advisory size, or memory-optimized instances. High GC means memory pressure. See Spark Memory Management.

Right-size the cluster for the bottleneck stage. A job that spends 80% of its time in one shuffle-heavy stage needs memory and cores there, not a bigger driver. Autoscaling helps uneven jobs; fixed size suits steady ones.

6 · Write right

Aim for 128 MB – 1 GB files. Small files slow every reader; giant files limit parallelism.

ALTER TABLE northbridge.gold.daily_store_sku SET TBLPROPERTIES (
  'delta.autoOptimize.optimizeWrite' = 'true',
  'delta.autoOptimize.autoCompact'   = 'true'
);

Remove partition-count habits. repartition(2000) before a small write makes 2,000 small files; coalesce(1) before a big one makes a single-task stage. See repartition vs coalesce.

Write incrementally. Rebuilding a 3-year table every night to add one day is the most expensive pattern of all. Use MERGE, replaceWhere or Change Data Feed to process only what changed.

(daily.write.format("delta")
      .mode("overwrite")
      .option("replaceWhere", "sale_date = '2026-11-12'")
      .saveAsTable("northbridge.gold.daily_store_sku"))

Starting configuration

A sensible starting point for batch jobs on classic compute (most are already defaults on recent runtimes):

spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
spark.conf.set("spark.sql.shuffle.partitions", "auto")          # Databricks; elsewhere a number sized to your biggest shuffle
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128MB")   # tune per workload

Serverless compute manages most of these for you and only allows a short list of Spark configs to be set.

Code review anti-patterns

Pattern in the code Why it hurts Replace with
select("*") from a wide table Reads every column Explicit column list
inferSchema=True Extra pass, unstable types Explicit schema
Python @udf for string/date logic Row-by-row serialization, no Photon Built-in functions
withColumn in a loop Huge plans, slow planning withColumns / one select
count() to check emptiness Full scan isEmpty() / limit(1)
collect() / toPandas() on big data Driver OOM, single-threaded Aggregate or write
repartition(2000) before write Small files Optimized writes, AQE
coalesce(1) after heavy work One-task stage repartition(1) or more files
Joins without broadcast to small tables Shuffles the big side F.broadcast(dim) or table stats
Loop of per-day jobs N × job overhead, N × planning One job over the range
cache() everywhere, never unpersist() Evicts useful data, spills Cache only reused data
Full table rebuild every run Pays for unchanged data Incremental MERGE / replaceWhere

The result

NorthBridge ran the checklist against the 30 most expensive jobs first. Three findings covered most of the savings: full rebuilds that could be incremental (9 jobs), Python UDFs that had built-in equivalents (7 jobs), and missing broadcasts on small dimensions (6 jobs). Config changes alone accounted for less than 10% of the improvement.

Across those 30 jobs, total runtime fell by 58% and monthly DBUs by 47%.

From production: gotchas and lessons

  1. Symptom: A tuning change looked great in dev and did nothing in prod. Cause: Dev ran on 1% of the data; the bottleneck stage only appeared at full volume. Fix: Benchmark on production-sized data, or at least a representative day.

  2. Symptom: Runtime improved but cost went up. Cause: The team had doubled the cluster to get there. Fix: Track DBUs alongside runtime in the baseline. Faster and cheaper usually come together when you remove work.

  3. Symptom: Two "improvements" made in one deploy, job got slower. Cause: One helped, one hurt (a new cache that evicted shuffle memory). Fix: One change at a time, measured.

  4. Symptom: A job got slower every week with no code changes. Cause: Data growth plus a full rebuild pattern, and small files accumulating. Fix: Incremental processing and table maintenance. Trend the baseline weekly.

  5. Symptom: A broadcast hint caused driver OOM on month-end. Cause: The "small" dimension grew to 3 GB in memory. Fix: Don't hard-code broadcasts on tables that grow; keep stats current and let AQE decide, or broadcast a filtered subset.

Performance and cost notes

On classic compute, cost is roughly nodes × time; every minute of a straggler task bills the whole cluster. On serverless, you pay for what's used, so removing work translates even more directly into savings. In both cases the order of the checklist matters: removing work (areas 1, 2, 4, 6) beats balancing it (3), which beats adding resources.

When not to use this

A job that runs in 3 minutes once a day and costs a few dollars a month doesn't need an hour of tuning. Rank jobs by cost and business impact, and start at the top. For SQL warehouse or BI workloads, the principles carry over but the tools differ (query profile, warehouse sizing, result caching).

Checklist

Baseline

  • Runtime, DBUs, slowest stage, spill and file counts recorded

Read less

  • Only needed columns selected
  • Filters pushable and early; files pruned confirmed in the scan node
  • Clustering on common filter columns
  • Explicit schemas, no inferSchema

Shuffle less

  • Small dimensions broadcast
  • Aggregate before join where possible
  • No unnecessary orderBy, distinct, repartition

Balance

  • AQE on; final plan checked
  • Shuffle partitions sized (or auto)
  • Max vs median task time checked; skew fixed

Compute

  • No Python UDFs where built-ins exist
  • No withColumn loops; no collect on big data
  • Photon on where it fits; debug actions removed

Memory

  • Caches reused and released
  • Spill and GC acceptable

Write

  • Output files 128 MB – 1 GB
  • Incremental instead of full rebuilds

Practice

Further reading

#performance#tuning#cost#best-practices#photon

Keep going

Article10 min read

Data Skew in Spark: Detect It and Fix It

Find the hot key behind a stage that never finishes, then fix it with AQE skew joins, key cleanup, hot-key isolation or salting, in that order.

One practical note a week

Get new articles, problems and guides in your inbox.