Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 2

Lab: Using the Spark UI to Fix a Slow Job

Run a report that is slow because 70% of its rows share one join key, find the straggler task and its spill in the Jobs, Stages and SQL tabs of the Spark UI, fix it twice, with AQE skew-join splitting and with a broadcast join, measure each fix, and decide when caching a DataFrame pays off.

Contentsand lesson path

What you will learn

  • Diagnose data skew, excess shuffles and spills in the Spark UI and fix them with broadcast joins, repartitioning, adaptive query execution or caching where justified.

Prerequisites: Python Foundations

01. Goal and setup

A nightly report counts rides and revenue per customer segment. Since the app began storing every ride without an account under customer 0, guest, 70% of all rides share one join key. Nothing fails, but one task does most of the work. In this lab you find that task in the Spark UI, fix the job in two ways, measure each fix, and decide whether a cache helps a job that reuses its join.

The Spark UI is a web server inside the driver, on port 4040 by default, that lives as long as the application and shows every job, stage and task. Its REST API under /api/v1 serves the same numbers as JSON. You explore with the pages, and diagnose.py prints the numbers as text so runs can be compared.

Tested with PySpark 4.3.0, Python 3.12 and Temurin JRE 21.0.12.1 in local mode with 8 task slots. Use spark-lab/, its venv and session.py from the lab in lesson 2, two terminals, a browser and about 110 MB of disk. Times depend on your machine; row, task and record counts will match exactly.

Files added in this lab
spark-lab/
├── make_skew.py      step 1: 10 million rides, 70% of them for customer 0
├── slow_job.py       steps 2, 4, 5: the report, with a variant argument
├── diagnose.py       steps 3 to 5: stage list and Summary Metrics from the REST API
└── two_reports.py    step 6: two reports from one join, with and without a cache

02. Step 1: Generate skewed data

make_skew.py writes 10 million rides and 400,001 customers. Customer 0 is the guest placeholder; the others have one of four segments. The wide crm_ref column keeps Spark from broadcasting the customer table on its own, as with real customer tables.

Python · spark-lab/make_skew.py
from pyspark.sql import functions as F

from session import local_session

spark = local_session("make-skew")
n_rides, n_customers = 10_000_000, 400_000

# The app stores rides without an account under customer 0, "guest": 70% of all rides.
rides = spark.range(1, n_rides + 1, numPartitions=8).select(
    F.col("id").alias("ride_id"),
    F.when(F.rand(21) < 0.7, 0)
    .otherwise(1 + F.floor(F.rand(22) * n_customers))
    .cast("long")
    .alias("customer_id"),
    F.date_add(F.to_date(F.lit("2026-03-01")), F.floor(F.rand(23) * 31).cast("int"))
    .alias("ride_date"),
    F.round(3 + F.rand(24) * 40, 2).cast("decimal(8,2)").alias("fare"),
)
rides.write.mode("overwrite").parquet("data/rides")

segments = F.array(*[F.lit(s) for s in ("consumer", "business", "student", "senior")])
customers = spark.range(0, n_customers + 1, numPartitions=4).select(
    F.col("id").alias("customer_id"),
    F.when(F.col("id") == 0, "guest")
    .otherwise(segments[F.floor(F.rand(25) * 4).cast("int")])
    .alias("segment"),
    F.sha2(F.col("id").cast("string"), 256).alias("crm_ref"),  # a wide column
)
customers.write.mode("overwrite").parquet("data/customers")

rides = spark.read.parquet("data/rides")
customers = spark.read.parquet("data/customers")
print("rides:", rides.count(), "| customers:", customers.count())
rides.groupBy("customer_id").count().orderBy(F.desc("count")).show(3)
spark.stop()
Terminal
python make_skew.py
Expected output
rides: 10000000 | customers: 400001
+-----------+-------+
|customer_id|  count|
+-----------+-------+
|          0|7001027|
|     127997|     26|
|     333392|     25|
+-----------+-------+
only showing top 3 rows

03. Step 2: Run the slow job and keep its UI open

slow_job.py joins rides with customers and aggregates per segment. Its argument picks a variant, so every run uses the same code; baseline is the job as it is today. It sets a job description for the Jobs tab, times the action and waits for Enter to keep the UI up.

Python · spark-lab/slow_job.py
import sys
import time

from pyspark.sql import functions as F

from session import local_session

# Settings for each run: python slow_job.py [baseline|skew-join|broadcast]
variant = sys.argv[1] if len(sys.argv) > 1 else "baseline"
conf = {"spark.ui.port": "4040"}
if variant == "skew-join":
    conf |= {
        "spark.sql.adaptive.advisoryPartitionSizeInBytes": "4MB",
        "spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes": "8MB",
    }
spark = local_session(f"rides-{variant}", cores=8, conf=conf)

rides = spark.read.parquet("data/rides")
customers = spark.read.parquet("data/customers")
if variant == "broadcast":
    customers = F.broadcast(customers.select("customer_id", "segment"))

report = (
    rides.join(customers, "customer_id")
    .groupBy("segment")
    .agg(F.count("*").alias("rides"), F.sum("fare").alias("revenue"))
    .orderBy("segment")
)
spark.sparkContext.setJobDescription(f"segment report ({variant})")
start = time.perf_counter()
report.show()
print(f"{variant}: {time.perf_counter() - start:.1f} s")
print("Spark UI:", spark.sparkContext.uiWebUrl)
input("Press Enter to stop Spark and close the UI... ")
spark.stop()
Terminal 1
python slow_job.py baseline
Illustrative output
+--------+-------+------------+
| segment|  rides|     revenue|
+--------+-------+------------+
|business| 748089| 17187400.50|
|consumer| 749109| 17233121.56|
|   guest|7001027|160994755.60|
|  senior| 747866| 17194121.05|
| student| 753909| 17341659.36|
+--------+-------+------------+

baseline: 14.3 s
Spark UI: http://127.0.0.1:4040
Press Enter to stop Spark and close the UI...

The guest segment has 7,001,027 rides, the others about 750,000 each. Leave this terminal waiting.

04. Step 3: Diagnose the job in the Spark UI

Open http://127.0.0.1:4040 and work through the tabs in this order.

  1. Jobs: one action created several jobs, because AQE runs each shuffle stage as its own job. Open the last job described as segment report (baseline). Its DAG shows two scan stages feeding the join stage, and stages marked as skipped because earlier jobs already wrote their shuffle files.
  2. Stages: sort by Duration. The longest stage reads both shuffles; it is the join.
  3. Open it. Summary Metrics shows min, 25th percentile, median, 75th percentile and max over its tasks for duration, shuffle read size and records, and spill if any. Compare Max with Median. In the Tasks table, sort by duration: one task reads millions more records than the rest, and the Event Timeline shows it as one long bar.
  4. SQL / DataFrame: open the query. The graph shows the SortMergeJoin, an Exchange on each side, and AQEShuffleRead nodes with the partition count after coalescing.

In the second terminal, run the script that reads the same numbers from the REST API.

Python · spark-lab/diagnose.py
"""Print what the Stages tab and one stage's Summary Metrics show, via the REST API."""
import datetime as dt
import json
import sys
import urllib.request

ui = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:4040"
MIB = 2**20


def get(path):
    with urllib.request.urlopen(f"{ui}/api/v1/applications{path}") as response:
        return json.load(response)


def seconds(stage):
    times = [stage["submissionTime"], stage["completionTime"]]
    start, end = (dt.datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f%Z") for t in times)
    return (end - start).total_seconds()


app = get("")[0]["id"]
stages = sorted(get(f"/{app}/stages?status=complete"), key=lambda s: s["stageId"])
print("stage  tasks  duration (s)  input rows  shuffle read rows  shuffle write rows")
for s in stages:
    print(
        f"{s['stageId']:>5}  {s['numTasks']:>5}  {seconds(s):>12.1f}"
        f"  {s['inputRecords']:>10}  {s['shuffleReadRecords']:>17}"
        f"  {s['shuffleWriteRecords']:>18}"
    )

slow = max(stages, key=seconds)
path = f"/{app}/stages/{slow['stageId']}/{slow['attemptId']}/taskSummary"
q = get(path + "?quantiles=0,0.25,0.5,0.75,1.0")
print(f"\nSummary Metrics of stage {slow['stageId']} ({slow['numTasks']} tasks)")
print("metric                       min      25th    median      75th       max")
rows = [
    ("duration (s)", q["duration"], 1000, 1),
    ("shuffle read (MiB)", q["shuffleReadMetrics"]["readBytes"], MIB, 1),
    ("shuffle read records", q["shuffleReadMetrics"]["readRecords"], 1, 0),
    ("spill, memory (MiB)", q["memoryBytesSpilled"], MIB, 1),
    ("spill, disk (MiB)", q["diskBytesSpilled"], MIB, 1),
]
for name, values, unit, digits in rows:
    print(f"{name:<22}" + "".join(f"{v / unit:>10.{digits}f}" for v in values))

query = get(f"/{app}/sql?details=true")[-1]
print(f"\nSQL tab, query {query['id']}: {query['description']}")
for node in query["nodes"]:
    name = node["nodeName"]
    if "Join" in name or name == "AQEShuffleRead":
        wanted = ("number of partitions", "number of skewed partitions")
        metrics = [m for m in node["metrics"] if m["name"] in wanted]
        found = [f"{m['name']} {m['value']}" for m in metrics]
        print(f"  {name}: {', '.join(found)}" if found else f"  {name}")
Terminal 2
python diagnose.py
Illustrative output
stage  tasks  duration (s)  input rows  shuffle read rows  shuffle write rows
    0      1           1.0           0                  0                   0
    1      1           0.2           0                  0                   0
    2      8           1.9      400001                  0              400001
    3      8           3.5    10000000                  0            10000000
    6      5           7.6           0           10400001                  21
   10      1           0.1           0                 21                   0

Summary Metrics of stage 6 (5 tasks)
metric                       min      25th    median      75th       max
duration (s)                 1.7       1.8       2.0       2.0       7.6
shuffle read (MiB)           7.9       8.3       8.3       8.3      34.1
shuffle read records      797656    829968    834798    835558   7102021
spill, memory (MiB)          0.0       0.0       0.0       0.0     144.0
spill, disk (MiB)            0.0       0.0       0.0       0.0      25.1

SQL tab, query 0: segment report (baseline)
  AQEShuffleRead: number of partitions 5
  AQEShuffleRead: number of partitions 5
  SortMergeJoin
  AQEShuffleRead: number of partitions 1

Two stages scan the tables and shuffle their rows; stages 0 and 1 are small jobs that read Parquet footers. Stage 6 is the join, with 5 tasks after coalescing. Four read about 830,000 records each; the fifth read 7,102,021, about 8.5 times the median, and on the run shown took 7.6 seconds against a median of 2.0. Only that task spilled: 144 MiB of sorted rows did not fit in its execution memory, so Spark wrote 25 MiB to disk and read it back.

Max far above median in both duration and records means data skew: hash partitioning sends every row with the same key to the same partition, so all 7 million guest rides met in one task. Other patterns point elsewhere. Max close to median with everything slow means the stage is simply large. One slow task with a normal record count suggests a slow machine. Spill on every task means partitions too big for memory, which more partitions fix. The stage cannot finish before its slowest task, so most slots sit idle meanwhile. Press Enter in terminal 1; the UI stops with the job.

05. Step 4: Fix 1, let AQE split the skewed partition

AQE can split a skewed partition of a sort-merge join into several tasks, each joined with a copy of the matching partition of the other side. A partition counts as skewed when it is larger than 5 times the median and than spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes, 256 MB by default. AQE judges skew on the shuffle partitions before it merges them, not on the 5 coalesced tasks in the UI: among the 200 original partitions, the guest one is hundreds of times the median. At about 34 MiB it is below 256 MB, so only the byte threshold held it back. The skew-join variant scales the threshold down to 8 MB, and the target split size, advisoryPartitionSizeInBytes, to 4 MB. At production volumes the defaults often work.

Terminal 1
python slow_job.py skew-join
Illustrative output
+--------+-------+------------+
| segment|  rides|     revenue|
+--------+-------+------------+
|business| 748089| 17187400.50|
|consumer| 749109| 17233121.56|
|   guest|7001027|160994755.60|
|  senior| 747866| 17194121.05|
| student| 753909| 17341659.36|
+--------+-------+------------+

skew-join: 11.4 s
Spark UI: http://127.0.0.1:4040
Press Enter to stop Spark and close the UI...
Terminal 2
python diagnose.py
Illustrative output
stage  tasks  duration (s)  input rows  shuffle read rows  shuffle write rows
    0      1           0.9           0                  0                   0
    1      1           0.1           0                  0                   0
    2      8           2.9    10000000                  0            10000000
    3      8           3.3      400001                  0              400001
    6     18           4.8           0           10414008                  80
   10      1           0.1           0                 80                   0

Summary Metrics of stage 6 (18 tasks)
metric                       min      25th    median      75th       max
duration (s)                 0.4       0.7       1.5       3.8       4.4
shuffle read (MiB)           0.8       3.7       3.7       4.2       4.2
shuffle read records       83957    373017    376236    879445    879591
spill, memory (MiB)          0.0       0.0       0.0      16.0      16.0
spill, disk (MiB)            0.0       0.0       0.0       2.5       2.5

SQL tab, query 0: segment report (skew-join)
  AQEShuffleRead: number of partitions 18
  AQEShuffleRead: number of skewed partitions 1, number of partitions 18
  SortMergeJoin(skew=true)
  AQEShuffleRead: number of partitions 1

The result is identical, and the SQL tab shows SortMergeJoin(skew=true) with one skewed partition. The join stage ran 18 tasks; the largest read about 880,000 records instead of 7.1 million, and spill fell to 16 MiB. AQE splits skew in joins, not in a groupBy or a window. There you can salt the key: add a random number from 0 to N − 1, aggregate per salted key, then aggregate again without the salt. Press Enter in terminal 1.

06. Step 5: Fix 2, broadcast the customer side

The report needs only customer_id and segment. Without crm_ref, the customer side is small enough to copy to every task, so the broadcast variant selects the two columns and adds the hint. The rides then never shuffle, and the hot key stops mattering.

Terminal 1
python slow_job.py broadcast
Illustrative output
+--------+-------+------------+
| segment|  rides|     revenue|
+--------+-------+------------+
|business| 748089| 17187400.50|
|consumer| 749109| 17233121.56|
|   guest|7001027|160994755.60|
|  senior| 747866| 17194121.05|
| student| 753909| 17341659.36|
+--------+-------+------------+

broadcast: 6.5 s
Spark UI: http://127.0.0.1:4040
Press Enter to stop Spark and close the UI...
Terminal 2
python diagnose.py
Illustrative output
stage  tasks  duration (s)  input rows  shuffle read rows  shuffle write rows
    0      1           1.0           0                  0                   0
    1      1           0.1           0                  0                   0
    2      8           0.9      400001                  0                   0
    3      8           2.1    10000000                  0                  40
    5      1           0.2           0                 40                   0

Summary Metrics of stage 3 (8 tasks)
metric                       min      25th    median      75th       max
duration (s)                 1.9       1.9       2.0       2.0       2.0
shuffle read (MiB)           0.0       0.0       0.0       0.0       0.0
shuffle read records           0         0         0         0         0
spill, memory (MiB)          0.0       0.0       0.0       0.0       0.0
spill, disk (MiB)            0.0       0.0       0.0       0.0       0.0

SQL tab, query 0: segment report (broadcast)
  BroadcastHashJoin
  AQEShuffleRead: number of partitions 1

There is no join stage now. One stage reads the 10 million rides, joins and pre-aggregates them, and writes 40 rows to the shuffle, 8 tasks × 5 segments. Its tasks took the same time, nothing spilled, and the report ran in less than half the baseline time on the run shown. Both scans are now short and either may be slower, so diagnose.py may show the customer scan; then open the rides stage in the Stages tab. Press Enter in terminal 1.

Broadcast is the better fix here because it removes the shuffle of the large side, but only while the customer side stays small. AQE skew handling is the general fix when both sides are large. Also question the data: a placeholder key with 70% of the rows can go down its own branch, filtered out, aggregated without a join and added back with unionByName.

07. Step 6: Decide when a cache is justified

df.cache() asks Spark to keep a DataFrame in executor memory when an action first computes it, so later actions read the copy instead of the source. It is lazy: nothing is stored until an action runs. The script builds two reports from the same joined rides, without and then with a cache, and counts the rows read from Parquet and from the cache with the scan metrics of the SQL tab.

Python · spark-lab/two_reports.py
import time

from pyspark.sql import functions as F

from session import local_session, rest

spark = local_session("two-reports", cores=8)
rides = spark.read.parquet("data/rides")
customers = spark.read.parquet("data/customers").select("customer_id", "segment")
members = rides.join(F.broadcast(customers), "customer_id").filter("segment != 'guest'")


def rows_out(group, node_prefix):
    """Sum 'number of output rows' of matching plan nodes in the SQL tab."""
    total = 0
    for query in rest(spark, "sql?details=true"):
        if query["description"] != group:
            continue
        for node in query["nodes"]:
            if node["nodeName"].startswith(node_prefix):
                for m in node["metrics"]:
                    if m["name"] == "number of output rows":
                        total += int(m["value"].replace(",", ""))
    return total


def two_reports(group):
    spark.sparkContext.setJobGroup(group, group)
    start = time.perf_counter()
    members.groupBy("segment").agg(F.sum("fare")).collect()
    members.groupBy("ride_date").agg(F.sum("fare")).collect()
    took = time.perf_counter() - start
    print(f"{group}: {took:.1f} s")
    print("  rows read from Parquet:", rows_out(group, "Scan parquet"))
    print("  rows read from the cache:", rows_out(group, "InMemoryTableScan"))


two_reports("no-cache")
members.cache()
two_reports("cache")
for rdd in rest(spark, "storage/rdd"):
    size = rdd["memoryUsed"] / 2**20
    parts = rdd["numCachedPartitions"]
    print(f"Storage tab: {parts} partitions in memory, {size:.1f} MiB")
members.unpersist()
spark.stop()
Terminal
python two_reports.py
Illustrative output
no-cache: 7.6 s
  rows read from Parquet: 20800002
  rows read from the cache: 0
cache: 5.6 s
  rows read from Parquet: 10400001
  rows read from the cache: 5997946
Storage tab: 8 partitions in memory, 57.5 MiB

Without a cache, each report read and joined all 10.4 million input rows. With it, the first report read the input once and stored the 2,998,973 member rides, and both reports read them from memory. The Storage tab shows the cached DataFrame: 8 partitions, about 57 MiB.

A cache is justified when the DataFrame is used by more than one action, is expensive to recompute, and fits in memory you can spare. It is not justified for a DataFrame used once, because storing it adds work, or for a cheap Parquet read. A cache that does not fit is partly recomputed or, with a disk storage level, read from local disk, and it takes memory from shuffles and joins. Call unpersist() when you are done.

08. Check your understanding

Practice check · 3 questions

Reading the UI and choosing a fix

Each question describes what a Spark UI shows. Pick the best reading or fix.

Q1. A stage of 4,000 tasks takes 40 minutes on 100 cores. In its Summary Metrics, durations run from 50 to 70 seconds and shuffle read records differ by less than 10% between min and max. No task spills. What does this tell you?
Q2. In the baseline run, AQE skew-join handling was on, yet it did not split the 34 MiB guest partition. Why not?
Q3. A job reads a Parquet table, filters it and writes one aggregate. A colleague adds `.cache()` after the filter to make it faster. What do you expect?
Practice only: not graded, not saved, not evidence.

09. Apply it

The practice project asks for one tuning change and its measured effect in the Spark UI:

  1. Run your project job and record the Summary Metrics of its longest stage with diagnose.py.
  2. Make one change, such as a broadcast of the zone lookup, and record the same numbers.
  3. Write three sentences: what the UI showed, what you changed, how the numbers moved. Quote task and record counts, not only times, which vary between runs.

10. Review prompt

Without looking back, explain in your own words:

  • which numbers in the Summary Metrics table tell skew apart from a stage that is simply large, and from spill on every task;
  • why all guest rides ended up in one task;
  • why AQE ignored the skew until you changed two settings, and what each setting does;
  • why the broadcast fix removed the join stage, and when it would stop working;
  • the three conditions under which a cache is worth its memory.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check