Sub topic 11
What distribution costs: shuffles, startup, and operations
This chapter assumes you know the execution models from earlier in the tutorial (eager, lazy, single-node, distributed) and can read a basic PySpark query. Spark is the only tool of the four that spreads work across machines. That ability has costs that appear even when the data is small. Knowing them helps you decide when a cluster pays for itself.
Where the costs come from
A single-node engine such as DuckDB or Polars reads data from local disk or memory, and its threads share one address space. A distributed engine splits data into partitions and sends them to executors, which are separate processes, usually on separate machines. Anything that has to cross a process boundary now costs serialization, network transfer, and coordination.
The costs fall into three groups:
- Per-job overhead: starting the session, acquiring executors, planning, and scheduling tasks.
- Data movement: shuffles, broadcasts, and skew.
- Operations: running and paying for the cluster, tuning it, and debugging it.
Startup and scheduling overhead
Starting a Spark session launches a JVM (Java virtual machine) and, on a cluster, requests executors from a resource manager such as YARN or Kubernetes. Local mode takes a few seconds. A cluster can take from tens of seconds to several minutes if nodes must be provisioned. Each job is then split into stages and tasks, and the scheduler sends each task to an executor. A task has a fixed cost of milliseconds to tens of milliseconds, whatever its size.
On a small input, this overhead dominates. You can see it by timing the same query in Spark local mode and in DuckDB:
import time
import duckdb
from pyspark.sql import SparkSession, functions as F
path = "sales.parquet"
t0 = time.perf_counter()
duckdb.sql(f"SELECT region, sum(revenue) FROM '{path}' GROUP BY region").fetchall()
print(f"duckdb: {time.perf_counter() - t0:.2f}s")
t0 = time.perf_counter()
spark = SparkSession.builder.master("local[*]").appName("overhead").getOrCreate()
print(f"spark session start: {time.perf_counter() - t0:.2f}s")
t0 = time.perf_counter()
spark.read.parquet(path).groupBy("region").agg(F.sum("revenue")).collect()
print(f"spark query: {time.perf_counter() - t0:.2f}s")On a file of a few megabytes, the Spark session start alone usually takes longer than the whole DuckDB query. The first Spark query also pays for class loading and plan compilation, so run it more than once before drawing conclusions. Chapter 13 covers how to do that fairly.
Shuffles
A shuffle redistributes rows across partitions so that rows sharing a key end up on the same executor. Operations that need all rows for a key in one place trigger one: groupBy, join (unless broadcast), distinct, and window functions with partitionBy. Narrow operations such as filter, select, and column arithmetic work on each partition independently and need no shuffle.
A shuffle has several steps:
- Each task computes its partial output and partitions it by key.
- The partitioned data is written to local disk as shuffle files.
- The next stage's tasks fetch their slices from every upstream executor over the network.
- Each task sorts or hashes the fetched data and continues.
This makes a shuffle the most expensive common step in Spark. It uses disk, network, and serialization, and the next stage cannot start until the previous stage finishes.
Spark reduces the cost of this particular query by doing a partial aggregation before the shuffle, so each map task sends one row per region instead of every input row. Joins have no such shortcut. A shuffle join sends both tables across the network.
Inspecting shuffles
An Exchange node in the physical plan marks a shuffle. You can count them before running anything expensive:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[*]").appName("plan").getOrCreate()
df = (
spark.read.parquet("sales.parquet")
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
df.explain()In the output, look for Exchange hashpartitioning(region, ...). The Spark UI shows the same thing as a stage boundary, with "Shuffle Read" and "Shuffle Write" sizes per stage.
Reducing shuffle cost
- Filter and select columns early so less data is shuffled. Spark's optimizer pushes many filters down on its own, but it cannot fix a query that selects every column.
- Use a broadcast join when one side is small. Spark copies the small table to every executor, and the large side is never moved. The default threshold is 10 MB (
spark.sql.autoBroadcastJoinThreshold), and you can raise it or hint withF.broadcast(small_df). - Avoid repeated shuffles on the same key. Data already partitioned by a key does not need to be reshuffled by an identical key in a later step.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[*]").appName("bcast").getOrCreate()
sales = spark.read.parquet("sales.parquet")
regions = spark.createDataFrame(
[("eu", "Europe"), ("us", "United States")], ["region", "region_name"]
)
joined = sales.join(F.broadcast(regions), on="region", how="left")
joined.explain()The plan should show BroadcastHashJoin and no Exchange on the sales side.
Partition count and skew
After a shuffle, the number of output partitions is set by spark.sql.shuffle.partitions, which defaults to 200. That is a poor fit for both extremes. On a small dataset, 200 tiny tasks add scheduling overhead for no benefit. On a very large dataset, 200 partitions can be too big to fit in executor memory, which causes spills to disk or failures. Recent Spark versions enable adaptive query execution (AQE) by default, which can merge small post-shuffle partitions and split skewed ones at run time. Check that it is enabled in your version and managed platform rather than assuming.
Skew means one key holds a disproportionate share of rows. If 60 percent of your sales rows have region = "us", one reduce task receives 60 percent of the data while the others finish early. The stage lasts as long as its slowest task, so adding executors does not help. Typical signs in the Spark UI are one task with a much longer duration and a much larger shuffle read than the median.
A single-node engine does not have this problem in the same form. DuckDB and Polars aggregate with shared in-memory hash tables across threads, with no network step.
What a cluster costs to run
Beyond a single job, a cluster adds recurring work that the other three tools do not need:
| Area | Spark on a cluster | DuckDB, Polars, pandas |
|---|---|---|
| Provisioning | Cluster manager, node images, autoscaling rules | A Python environment |
| Dependencies | Same Python and library versions on every executor, plus a compatible JVM | One `pip install` |
| Cost model | Pay for nodes while they run, including idle time | Pay for one machine |
| Tuning | Partition counts, executor memory, broadcast thresholds, skew handling | Mostly none |
| Debugging | Logs spread across executors, Spark UI, serialization errors | A local stack trace |
| Failure modes | Executor loss, shuffle fetch failures, out-of-memory in one task | Out-of-memory in one process |
Managed services (Databricks, EMR, Dataproc, and similar) remove much of the provisioning work but add a bill and a platform to learn. They do not remove the tuning and debugging work, because shuffle and skew behavior come from the engine, not from the hosting.
Spark also gives you something in return: fault tolerance. If an executor dies, Spark recomputes the lost partitions from the plan. A single-node job that dies loses all progress unless you checkpoint to disk yourself.
When the cost is worth paying
A cluster is justified when a single machine cannot do the job in acceptable time, even with an efficient engine. Check these in order before you commit:
- Does the data fit on one machine's disk and, for an out-of-core engine, is the working set manageable? Modern single servers offer hundreds of gigabytes of RAM and many cores, and DuckDB and Polars can process data larger than memory.
- Is the data already in Parquet, so a single-node engine can skip columns and row groups?
- Does the job need to be shared with many concurrent users or other Spark workloads on an existing platform?
- Is the data already stored in a distributed system, such as a data lake that your organization runs Spark against?
If the answer to the first two is yes and to the last two is no, a single-node engine usually costs less to build and run. If the data is many terabytes, must be processed within a strict window, or the organization already operates Spark well, the overhead becomes a cost you are already paying.
Summary of the costs
- Startup and scheduling are fixed costs that matter on small and medium data.
- Shuffles move data across disk and network, and they appear with group-bys, joins, distinct, and windows.
- Skew makes one task the bottleneck, and more machines will not fix it.
- Operations add provisioning, dependency management, tuning, and debugging work.
- In return, you get scale beyond one machine and recovery from node failures.
Exercise
A team runs a nightly job that joins a 40 GB Parquet fact table with a 5 MB lookup table, then groups by customer_id and sums amounts. The job runs on a 20-node Spark cluster. (a) Which steps in the Spark plan are likely to trigger shuffles, and how can the team avoid one of them? (b) Name one reason to keep Spark and one reason to consider moving to a single-node engine.
Show answer
(a) The group by customer_id triggers a shuffle, and a join triggers one too unless it is broadcast. The 5 MB lookup table is below the default 10 MB broadcast threshold, so a broadcast join (or an explicit F.broadcast hint) avoids the join shuffle. The group-by shuffle remains, though partial aggregation reduces its volume. (b) Reasons to keep Spark: the job is already operated on the platform, other jobs share the cluster, or data is expected to grow to many terabytes. Reasons to move: 40 GB fits on one machine for DuckDB or Polars reading Parquet, which would remove cluster cost, shuffle tuning, and startup time. The team should benchmark both on the real job before deciding.
Exercise
In the Spark UI, a stage with 200 tasks takes 12 minutes. 199 tasks finish in under 20 seconds, and one task runs for the full 12 minutes with a shuffle read 50 times larger than the median. What is the likely cause, and why does adding more executors not help?
Show answer
The likely cause is data skew: one key (for example a dominant region or a null value) holds most of the rows, so a single reduce task receives most of the data. A stage finishes only when its slowest task finishes, and one key cannot be split across tasks by a plain hash partition, so extra executors sit idle. Remedies include enabling or tuning adaptive query execution skew handling, salting the key, filtering or handling the dominant key separately, or using a broadcast join if the skew comes from a join.