Sub topic 7
Apache Spark: distributed processing on clusters
This chapter assumes you can write basic Python, read and write SQL (SELECT, WHERE, GROUP BY, JOIN), and have loaded data with pandas. It also assumes you have read the earlier chapters on eager versus lazy execution and on Parquet. Here you will learn how Spark works, what it is good at, and where it costs more than it returns.
What Spark is
Apache Spark is a distributed data processing engine. It splits a dataset into pieces called partitions and processes them in parallel on many machines. Those machines form a cluster. Spark is written in Scala and runs on the Java Virtual Machine (JVM). You usually use it from Python through PySpark, the Python API.
The key idea is that your data and your computation do not need to fit on one machine. If a dataset is 5 TB, you can spread it across 50 machines and let each one handle its share. No other tool in this tutorial offers this. pandas, Polars, and DuckDB all run on a single machine.
How Spark runs a job
A Spark application has three kinds of parts:
- The driver is the process that runs your Python program. It builds the query plan and coordinates the work.
- The executors are worker processes on the cluster machines. They hold partitions and run tasks.
- The cluster manager allocates machines. Common choices are YARN, Kubernetes, and managed services such as Databricks, Amazon EMR, and Google Dataproc. Spark also has a standalone mode and a local mode that runs everything on one machine.
Lazy execution, jobs, stages, and tasks
Spark DataFrame operations are lazy. Methods such as filter, select, groupBy, and join are transformations. They add steps to a logical plan but do no work. An action, such as show(), count(), or write, makes Spark run the plan.
When an action runs, Spark's optimizer (called Catalyst) rewrites the plan. It pushes filters down toward the data source, reads only the needed columns from Parquet, and picks join strategies. Spark then divides the work like this:
- A job is the work triggered by one action.
- A job is split into stages at points where data must move between machines.
- Each stage is split into tasks, one per partition.
Tasks within a stage run in parallel. A stage cannot start until the stage before it has finished.
You can inspect the plan before running anything:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("plan-demo").getOrCreate()
df = (
spark.read.parquet("sales.parquet")
.filter(F.col("revenue") > 0)
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
df.explain()In the printed physical plan, look for PushedFilters and a ReadSchema that lists only region and revenue. Those show that the Parquet reader skips data it does not need. You will also see an Exchange node. That is a shuffle, the topic of the next section.
Shuffles
A shuffle is a redistribution of data across the cluster so that rows with the same key end up on the same machine. A groupBy needs it, because all rows for one region must be combined in one place. Joins on large tables need it too, as do sorts and distinct.
Shuffles are the main cost in Spark. Each one writes intermediate data to local disk, sends it over the network, and reads it back. Most tuning work in Spark is about avoiding shuffles or making them cheaper. The distribution costs chapter covers this in more detail. For now, remember that a plan with many Exchange nodes will be slow no matter how many machines you add.
Spark reduces shuffle volume for aggregations by doing a partial aggregation on each partition first. In the sales example, each task sums revenue per region within its own partition, and only those small partial sums cross the network.
Running Spark locally
You can run Spark without a cluster. The default getOrCreate() call above starts a local session when no cluster is configured. You can also set the master explicitly:
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.master("local[4]")
.appName("local-demo")
.config("spark.sql.shuffle.partitions", "8")
.getOrCreate()
)
df = spark.range(1_000_000).withColumn("bucket", (spark.range(1).id * 0 + 1))
print(spark.conf.get("spark.sql.shuffle.partitions"))
spark.stop()local[4] uses four threads on your machine. The setting spark.sql.shuffle.partitions controls how many partitions a shuffle produces. Its default is 200, which is far too many for small data and often too few for very large data. Local mode is useful for learning and for testing code. It is not a good way to get speed, because you still pay for the JVM and for Spark's scheduling.
PySpark needs a Java runtime installed. A missing or mismatched Java version is the most common setup failure.
Strengths
- Scale beyond one machine. Spark handles datasets of many terabytes by adding machines.
- Fault tolerance. If an executor dies, Spark reruns its lost tasks on another machine. Long jobs survive hardware failures.
- Mature ecosystem. Spark reads and writes Parquet, ORC, JSON, CSV, and JDBC sources. Table formats such as Delta Lake and Apache Iceberg integrate with it. It also has Structured Streaming for continuous data and MLlib for machine learning.
- Managed platforms. Databricks, EMR, Dataproc, and similar services remove much of the cluster setup, and many companies already run one.
- Unified API. The same DataFrame and SQL code runs on a laptop and on a large cluster.
Limits and failure modes
Startup and overhead
Starting a Spark session, acquiring executors, and scheduling tasks takes seconds to minutes. For a 200 MB file, Spark is often slower than pandas, Polars, or DuckDB, which finish in well under a second. Spark pays a fixed cost that only pays off when the data is large.
Skew
Data skew means some keys have far more rows than others. After a shuffle, the executor that receives a very common key gets a huge partition, while the others finish early and sit idle. The stage then takes as long as that one slow task. Recent Spark versions have adaptive query execution (AQE), which can split skewed join partitions at runtime, but severe skew still needs attention, for example by salting keys or filtering out null keys.
Memory pressure and spilling
Each executor has limited memory. When a partition or a shuffle buffer is too large, Spark spills data to disk, which slows the job. If it still does not fit, the executor fails with an out-of-memory error. Calling collect() or toPandas() on a large result also moves all data to the driver, which can crash it. Only collect results you know are small.
Too many or too few partitions
Too few partitions leave machines idle and create oversized tasks. Too many create scheduling overhead, and tiny files if you write the output. A common starting point is partitions of roughly 100 to 200 MB.
Python overhead
DataFrame code using built-in functions from pyspark.sql.functions runs inside the JVM at full speed. A Python user-defined function (UDF) forces rows to be sent to a Python process and back, which is much slower. Prefer built-in functions. If you need Python logic, vectorized pandas UDFs, which exchange data in Arrow batches, cost less than row-at-a-time UDFs.
Operations
A cluster needs configuration, monitoring, version management, and cost control. Debugging means reading the Spark UI and executor logs rather than a local stack trace. This is real work, and a small team may not want to take it on.
Spark compared with the other tools
| Aspect | Spark | pandas / Polars / DuckDB |
|---|---|---|
| Scale | Many machines, terabytes and above | One machine |
| Small-data speed | Slow, fixed startup cost | Fast |
| Failure handling | Reruns failed tasks | Process fails, you rerun it |
| Setup | JVM, often a cluster | `pip install` |
| Debugging | Spark UI, logs | Local debugger and prints |
Spark is not simply a faster pandas. It is built for a different problem, and on one machine with moderate data, Polars and DuckDB often beat it. They can also process larger-than-memory files on one machine, which covers more cases than people expect. Spark becomes the right choice when the data, or the number of concurrent users and jobs, outgrows one machine, or when your organization's data platform already runs on it.
Exercises
Exercise
A PySpark job groups a 2 TB table by customer_id. In the Spark UI, one task in the shuffle stage runs 40 minutes while the other 199 finish in 2 minutes. What is the likely cause, and name two ways to address it?
Show answer
Data skew: one customer_id (possibly null) has far more rows than the others, so one partition after the shuffle is huge. Options: enable or check adaptive query execution so skewed partitions are split, filter out or separately handle null or very common keys, or salt the key (add a random suffix, aggregate partially, then combine).
Exercise
A teammate runs spark.read.parquet("events/").toPandas() on a 300 GB dataset and the driver crashes. Why does this happen, and what should they do instead?
Show answer
toPandas() collects every row to the single driver process, which does not have the memory for 300 GB. They should filter and aggregate in Spark first so the result is small, then convert, or write the result to Parquet and read it in a tool that can scan it lazily.
Exercise
You have a 1 GB CSV file and a laptop with 16 GB of RAM. Does Spark make sense, and why?
Show answer
Probably not. The data fits easily in memory on one machine, and Spark's JVM startup and scheduling overhead would exceed the processing time. pandas, Polars, or DuckDB would be simpler and faster.