Apache Spark DataFrames: Inspect a Shuffle in PySpark

Trace one PySpark 4.3.0 aggregation from input through its physical plan, then use Spark UI metrics to inspect shuffle volume and task skew.

published: reading time: 8 min read author: Geek Workbench updated: November 4, 2026
Quick Summary

Build a small PySpark 4.3.0 aggregation with an explicit schema, inspect its formatted physical plan, and run it. Learn how to recognize the Exchange shuffle boundary, then use Spark UI runtime metrics to check data movement, spill, and skew on representative input.

Apache Spark DataFrames: Inspect a Shuffle in PySpark

Trace one DataFrame aggregation from input through its physical plan, then inspect the runtime metrics that explain its shuffle. The example uses a tiny in-memory dataset so you can run it locally. Its plan shows where Spark repartitions rows; only a representative workload can tell you how much that movement costs or whether one key is skewed.

The examples use Apache Spark 4.3.0, the latest release when checked on 2026-11-04. Apache announced the release on October 30. See the 4.3.0 release notice and Spark downloads page for version details.

Prepare a small DataFrame job

A PySpark DataFrame is a table-like collection with named columns. Spark SQL can use that structure to optimize the operations in your query. Here, the input is a fixed list of six sales rows. The schema is explicit, so the example does not depend on file inference or an external data source.

The PySpark 4.3.0 installation guide requires Python 3.11 or later and Java 17 or later, with JAVA_HOME set. Install the matching package in that environment, then save the code below as spark_shuffle_lab.py:

python -m pip install pyspark==4.3.0
from pyspark.sql import SparkSession
from pyspark.sql.functions import sum as spark_sum
from pyspark.sql.types import LongType, StringType, StructField, StructType

spark = (
    SparkSession.builder
    .appName("InspectDataFrameShuffle")
    .master("local[*]")
    .getOrCreate()
)

schema = StructType(
    [
        StructField("region", StringType(), nullable=False),
        StructField("amount", LongType(), nullable=False),
    ]
)

rows = [
    ("north", 120),
    ("north", 80),
    ("south", 30),
    ("south", 70),
    ("west", 50),
    ("west", 25),
]

sales = spark.createDataFrame(rows, schema)
regional_sales = sales.groupBy("region").agg(
    spark_sum("amount").alias("total_sales")
)

regional_sales.explain(mode="formatted")
regional_sales.show()
input("Review the Spark UI, then press Enter to stop this local app.")
spark.stop()

Run the saved script from the same environment:

python spark_shuffle_lab.py

It prints the physical plan, runs the aggregation, shows the totals, and then waits for input so the Spark UI remains available. Press Enter in the terminal after inspecting the UI to stop the local application.

The aggregation groups by region and sums amount. The expected totals are north: 200, south: 100, and west: 75; Spark may display them in a different order because the query does not sort the result. The .show() call is an action. It executes the query after explain() has printed the plan.

The Spark SQL, DataFrames, and Datasets guide covers DataFrame operations. DataFrame.explain(mode="formatted") prints a physical-plan outline with details for each node; the PySpark API reference lists the available formats.

Read the physical plan

The exact plan text varies with Spark configuration and runtime version. For this grouped aggregation, look for a plan with an Exchange between partial and final aggregation, similar to this abbreviated outline:

AdaptiveSparkPlan
+- HashAggregate(keys=[region], functions=[sum(amount)])
   +- Exchange hashpartitioning(region, ...)
      +- HashAggregate(keys=[region], functions=[partial_sum(amount)])
         +- Scan ExistingRDD

Exchange hashpartitioning(region, ...) is the shuffle boundary in this plan. Spark redistributes rows by region so all rows with the same key can reach a partition and be combined. The partial aggregate runs before the exchange and can reduce how many rows need to move; the final aggregate merges those partial sums.

The physical plan answers “where can data move?” It does not report how many bytes were shuffled at runtime, how much spilled to disk, or whether one task processed much more data than the others. Exchange is a useful place to look, not a performance diagnosis by itself.

The session uses .master("local[*]"), so this lab runs in one local process rather than across a cluster. With six rows, it makes the API and plan easy to follow, but it does not reproduce network transfer between executors or realistic task imbalance. A cluster run can have different plan details because its input partitions, statistics, settings, and AQE decisions differ. Read that run’s own plan and UI metrics instead of comparing its output text character by character with the outline above.

Diagnose the shuffle in Spark UI

While the script is paused, open the UI address printed in the logs; Spark uses port 4040 by default and selects another free port if needed. The Web UI guide describes the Jobs, Stages, SQL, and task metrics pages.

Find the SQL execution for the aggregation and open its physical plan. Then follow the associated stages and compare the task-level metrics. Useful signals include:

Signal What it tells you
Shuffle bytes and records written How much each upstream stage produced for the exchange.
Shuffle bytes and records read How much data reducers fetched locally and from other executors.
Shuffle fetch wait time How long tasks waited for remote shuffle data.
Memory and disk spill Whether shuffled data exceeded in-memory processing capacity for a task.
Task durations and shuffle reads by task Whether a few tasks handled far more work than the rest.

Spark exposes these in stage details and SQL execution metrics. Follow the SQL execution’s Exchange node to its stage and compare per-task distributions. A few tasks with much larger shuffle reads or longer durations may indicate key skew; check the frequency of grouping keys in the input. High shuffle volume alone does not mean the query is slow. Spill indicates that tasks moved data out of memory while processing. If the measurements point to an issue, test one change at a time, such as filtering rows or selecting fewer columns when the query semantics allow it.

Compare per-task shuffle reads and writes as well as the stage totals. If the input snapshot is larger than the baseline, larger totals may simply reflect more rows processed. Record input size with the query metrics so the runs have context.

For this example, the grouping key has only three values: north, south, and west. The final aggregation must bring rows for each region together. Adding more shuffle partitions cannot split one region’s final group across independent results without changing how the aggregation is performed. On a real workload, inspect the key distribution and query semantics first; then test a change against the same representative input and compare the SQL plan and stage metrics.

Account for adaptive query execution

Adaptive Query Execution (AQE) uses runtime statistics to revise a plan while the query runs. Spark SQL has enabled AQE by default since Spark 3.2. In Spark 4.3.0, AQE can coalesce post-shuffle partitions, handle certain skewed shuffle partitions, and adjust some join strategies when runtime statistics support a different choice. The Spark SQL performance tuning guide documents these rules and their configuration.

That matters when reading explain() output. Calling explain(mode="formatted") before the action shows the planned physical execution, while AQE may revise parts of it after Spark has runtime statistics. Inspect the executed plan in the SQL tab along with stage metrics after the action. Check whether the adaptive plan coalesced partitions or changed the number and shape of tasks; do not infer that from the initial Exchange alone.

The number of post-shuffle partitions in the initial plan can differ from the executed plan after AQE coalesces them. Record which plan you are looking at when you compare runs; otherwise a runtime adjustment can look like a configuration mismatch.

AQE does not make workload inspection unnecessary. It can adapt supported parts of a query using statistics Spark observes, but it cannot tell you whether your aggregation keys reflect the intended business grouping or whether the input data distribution matches the next run. Compare representative runs rather than applying a fixed partitions-per-core or partition-size rule to every workload.

Compare a proposed change

Keep a baseline before you tune: record the input snapshot and size, query, cluster shape, Spark version, and relevant settings. Change one thing, then compare the results for correctness and the SQL and stage metrics for execution behavior. If input volume or cluster shape changed too, the comparison cannot tell you which change caused the difference. Keep the query and configuration with the results so the next run can be compared fairly.

The six-row lab checks that the code runs, returns 200, 100, and 75, and shows a hash-partitioning exchange. It is too small for a performance comparison and says nothing about a throughput target or sizing rule. Use the same query shape on representative data in the target cluster to study runtime behavior. Check result values before interpreting runtime metrics; a plan that changes the grouping or drops valid rows is not a correct optimization.

Summary

Use explain(mode="formatted") to see the planned operations and locate an Exchange for the grouped aggregation. Then use the SQL and Stages pages in Spark UI to measure shuffle bytes, records, spill, and task imbalance. On representative data, those runtime measurements tell you whether the shuffle deserves attention; the plan node alone does not.

Further reading

For a Kafka source-to-sink example and checkpoint semantics, continue with the Structured Streaming guide. If you are comparing batch analytics with a streaming-first engine, see the Apache Flink guide.

Category

Related Posts

Apache Spark Structured Streaming: Kafka Pipeline Guide

Build a PySpark 4.3.0 Kafka pipeline, set up checkpoint recovery, and learn why the built-in Kafka sink can still write duplicate records.

#apache spark #structured streaming #kafka

Consistent Hashing for Load Balancing

Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.

#load-balancing #consistent-hashing #distributed-systems

Load Balancing Algorithms: Workloads and Benchmarks

Compare round robin, least-connections, and two-choice routing under mixed request durations with a reproducible workload and operational trade-offs.

#load-balancing #distributed-systems #performance