All the queries you have written so far finish in a second or two. That makes sense: 38 MB fits comfortably in your computer's memory. But the code from the previous lesson, launched as it stands over a year of NovaMarket's events, could take ten minutes or four hours depending on a handful of details: how the data is distributed, which type of join Spark chooses, how many files are written. In the cloud, where you pay per minute of cluster time, that difference is money, plain and simple.
This lesson teaches you to see what Spark does and to step in when it gets it wrong. You will learn to read an execution plan, to understand why the shuffle is the dominant cost, to control partitions, to choose the type of join, to detect skewed data and to avoid the most common memory errors. It also settles a debt from lesson 02-04: what to do with columns that are filtered on a lot but have too many values to partition by.
A word of warning before you start: with 38 MB the differences in time are minimal, and sometimes misleading. Do not focus on the seconds, but on the plans. What you learn to read in them is what makes the difference at real scale.
Reading an execution plan
When you launch an action, the Catalyst optimiser transforms your query in four steps:
flowchart LR
A[Your code<br/>DataFrame or SQL] --> B[Analysed<br/>logical plan]
B --> C[Optimised<br/>logical plan]
C --> D[Physical plan]
D --> E[Execution<br/>in stages and tasks]
- The logical plan describes what has to be computed: filter, join, aggregate.
- The optimised logical plan is the same computation reordered: filters pushed forward, surplus columns removed.
- The physical plan decides how: which join algorithm, where the shuffles are, how the files are read.
df.explain() shows the physical plan; df.explain(True) shows all four. Create ~/novamarket/optimise.py:
import time
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
SILVER = LAKE / "silver"
SCRATCH = Path.home() / "novamarket" / "lake_scratch"
spark = SparkSession.builder.master("local[*]").appName("optimise").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.parquet(str(SILVER / "orders_complete"))
customers = spark.read.parquet(str(SILVER / "customers"))
events = spark.read.parquet(str(SILVER / "web_events"))
sales_by_province = (
orders.where("status <> 'returned'")
.join(customers, "customer_id")
.groupBy("province")
.agg(F.round(F.sum("total_amount"), 2).alias("sales"))
)
sales_by_province.explain()
spark.stop()The physical plan, with the read lines abbreviated:
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[province#9], functions=[sum(total_amount#3)])
+- Exchange hashpartitioning(province#9, 200), ENSURE_REQUIREMENTS
+- HashAggregate(keys=[province#9], functions=[partial_sum(total_amount#3)])
+- Project [total_amount#3, province#9]
+- BroadcastHashJoin [customer_id#1], [customer_id#7], Inner, BuildRight
:- Project [customer_id#1, total_amount#3]
: +- Filter ((isnotnull(status#4) AND NOT (status#4 = returned)) AND isnotnull(customer_id#1))
: +- FileScan parquet [customer_id#1,total_amount#3,status#4] ... PushedFilters: [IsNotNull(status), Not(EqualTo(status,returned)), IsNotNull(customer_id)], ReadSchema: struct<customer_id:int,total_amount:double,status:string>
+- BroadcastExchange HashedRelationBroadcastMode(...)
+- Filter isnotnull(customer_id#7)
+- FileScan parquet [customer_id#7,province#9] ... ReadSchema: struct<customer_id:int,province:string>A plan is read from the bottom up and from the inside out: the leaves (the FileScans) are the beginning and the first line is the end. The branches marked with :- and +- under a join are its two inputs. Essential vocabulary:
| Operator | Meaning | What to look at |
|---|---|---|
FileScan |
Reading files | ReadSchema (column pruning), PushedFilters (predicate pushdown), PartitionFilters (partition pruning) |
Filter, Project |
Filtering rows, selecting or computing columns | That the filter is as low down as possible |
HashAggregate |
Aggregation | It usually appears twice: partial and final |
Exchange |
Shuffle | How many there are and by which key |
BroadcastHashJoin |
Join that sends the small table to every executor | No shuffle of the large table |
SortMergeJoin |
Join that sorts both sides | One Exchange and one Sort per side |
BroadcastExchange |
Sending the small table | It is not a shuffle |
Sort, Window |
Sorting, window function | They are usually preceded by an Exchange |
AdaptiveSparkPlan |
The plan can change during execution (AQE) | isFinalPlan |
Catalyst's work can be seen in this plan. Only 3 of the 7 columns of orders are read, and 2 of the 4 of customers. It has added an isnotnull(customer_id) filter of its own accord: since nulls never match in an inner join, it discards them as early as possible. And the filter on status has been taken all the way down to the read itself. None of that was in your code.
The numbers after the hash sign (province#9) are internal column identifiers; they change on every run and you can ignore them.
The shuffle: narrow and wide transformations
Transformations fall into two classes according to how they treat partitions:
| Narrow | Wide | |
|---|---|---|
| What they need | Each output partition depends on one input partition | Each output partition depends on many input partitions |
| Do they move data between partitions? | No | Yes: shuffle |
| Examples | select, filter, withColumn, union, coalesce |
groupBy, join*, orderBy, distinct, dropDuplicates, repartition, windows |
| In the plan | No Exchange |
With Exchange |
| Effect on execution | They are chained in the same stage | They open a new stage |
* Except the broadcast join, as you will see shortly.
A shuffle redistributes the rows so that all those with the same key end up in the same partition. It is the same mechanism as in MapReduce (lesson 03-01), and it is expensive for the same reasons:
- Each row is serialised and written to local disk on the source executor.
- It travels over the network to the destination executor.
- There it is read, deserialised and, often, sorted.
Filtering a billion rows is fast: each executor works on its own share. Grouping them requires almost all of them to change machine. That is why the general rule of optimisation in Spark is: fewer shuffles, and with less data. Anything that reduces rows and columns before a shuffle multiplies into savings.
In-memory partitions: repartition, coalesce and spark.sql.shuffle.partitions
The number of partitions determines parallelism: one task per partition. Too few, and each task handles so much volume that it runs out of memory and wastes cores; too many, and the cost of coordinating thousands of tiny tasks outweighs that of the work.
Where does that number come from?
| Moment | Who decides it |
|---|---|
| When reading files | The size of the data: chunks of up to 128 MB (spark.sql.files.maxPartitionBytes), grouping small files together |
| After a shuffle | The spark.sql.shuffle.partitions parameter, 200 by default |
| When you ask for it | repartition and coalesce |
print(events.rdd.getNumPartitions()) # 11 (depends on your computer)
print(events.repartition(8).rdd.getNumPartitions()) # 8
print(events.coalesce(2).rdd.getNumPartitions()) # 2repartition(n) or repartition(n, col) |
coalesce(n) |
|
|---|---|---|
| Can increase partitions | Yes | No |
| Does it trigger a shuffle? | Yes, a full one | No: it merges neighbouring partitions |
| Resulting distribution | Balanced; by key if a column is given | It can end up uneven |
| Typical use | Balancing data, distributing by a key before writing | Reducing the number of output files |
Their plans confirm it: events.repartition(8).explain() shows Exchange RoundRobinPartitioning(8); events.coalesce(2).explain() shows Coalesce 2, with no Exchange.
The 200 parameter
The default value of spark.sql.shuffle.partitions does not adapt to the size of the data: for a computation over 1 TB, 200 partitions mean 5 GB per task, far too much; for our tables, 200 partitions of a few kilobytes. For years it was the first parameter that had to be tuned by hand, with a guideline of between 100 and 200 MB per partition:
Today, adaptive execution (AQE, below) corrects the excess automatically. Check it:
by_session = events.groupBy("session_id").count()
print("With AQE:", by_session.rdd.getNumPartitions()) # 1
spark.conf.set("spark.sql.adaptive.enabled", "false")
by_session = events.groupBy("session_id").count()
print("Without AQE:", by_session.rdd.getNumPartitions()) # 200
spark.conf.set("spark.sql.adaptive.enabled", "true")With AQE, Spark sees that the output of the shuffle is tiny and merges the 200 partitions into one. Without AQE, all 200 remain.
Joins: sort-merge versus broadcast
Spark has several physical strategies for the same join. The two main ones:
Sort-merge join. This is the general strategy for two large tables. Both are redistributed by the key (two shuffles), sorted and traversed in parallel, pairing up equal keys.
Broadcast hash join. When one of the tables is small, Spark loads it in full in the driver, sends it complete to each executor and each one joins its part of the large table with that local copy. The large table does not move: there is no shuffle.
flowchart TB
subgraph SMJ[Sort-merge join]
direction TB
G1[Large table] -->|shuffle by key| O1[Sort]
G2[Another large table] -->|shuffle by key| O2[Sort]
O1 --> J1[Pair up]
O2 --> J1
end
subgraph BHJ[Broadcast hash join]
direction TB
P[Small table] -->|copy to each executor| J2[Join in each partition]
G3[Large table<br/>does not move] --> J2
end
Spark chooses broadcast automatically when it estimates that a table takes up less than spark.sql.autoBroadcastJoinThreshold, 10 MB by default. That is what happened with customers in the previous plan. To see the alternative, disable the threshold:
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
(
orders.where("status <> 'returned'").join(customers, "customer_id")
.groupBy("province").agg(F.sum("total_amount"))
.explain()
)+- SortMergeJoin [customer_id#1], [customer_id#7], Inner
:- Sort [customer_id#1 ASC NULLS FIRST], false, 0
: +- Exchange hashpartitioning(customer_id#1, 200), ENSURE_REQUIREMENTS
: +- Project [customer_id#1, total_amount#3]
: ...
+- Sort [customer_id#7 ASC NULLS FIRST], false, 0
+- Exchange hashpartitioning(customer_id#7, 200), ENSURE_REQUIREMENTS
+- Filter isnotnull(customer_id#7)
...Two Exchanges and two Sorts have appeared that were not there before: the plan goes from one shuffle to three. When you know a table is small and Spark does not work it out (for example, because it is the result of filters and aggregations whose output it cannot estimate), you can tell it so:
With that hint, the plan goes back to BroadcastHashJoin even though the threshold is disabled. Afterwards, restore the value with spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 10 * 1024 * 1024).
At NovaMarket, this is the pattern of almost every analytical query: a huge fact table (web_events, fact_sales) joined with small dimensions (products, dim_date). The dimensions are broadcast and the facts do not move. The limit is set by memory: the broadcast table must fit in the driver and in every executor, so broadcasting tables of several gigabytes ends in a memory error.
Data skew
Lesson 01-04 introduced skew: a distribution by key in which a few keys accumulate a disproportionate share of the data. Since a shuffle sends all the rows for a key to the same partition, a giant key produces a giant partition. The symptom is unmistakable: 199 tasks finish in seconds and one takes minutes or hours, or runs out of memory.
NovaMarket has a textbook case in its own data:
+-----------+-----+ |customer_id|count| +-----------+-----+ | NULL|60684| | 66| 269| | 610| 258| | 162| 255| +-----------+-----+
A typical customer has about 140 events; the null key, that of the anonymous visitors, has 60,684: 30% of the table. Look at how the partitions turn out when distributing by that key:
(
events.repartition(8, "customer_id")
.groupBy(F.spark_partition_id().alias("partition")).count()
.orderBy("partition").show()
)+---------+-----+ |partition|count| +---------+-----+ | 0|15549| | 1|20380| | 2|78074| | 3|20774| | 4|15673| | 5|15826| | 6|14856| | 7|18868| +---------+-----+
Partition 2 has four or five times as many rows as the others. At real scale that would be 12 million anonymous events a day in a single task.
How to detect it
- In the data: a count by the join or aggregation key, sorted from highest to lowest, like the one above.
- In the Spark UI: in the detail of a stage, the Summary Metrics table shows the duration and volume of the tasks by percentile. If the maximum is far above the median, there is skew.
How to mitigate it
| Technique | What it consists of | When |
|---|---|---|
| Handle the problem key separately | Filter out the nulls (or the giant key), process them separately and combine the results | When the skewed key is known; the simplest and most effective |
| Broadcast join | With no shuffle there is no giant partition | When the other side is small |
| AQE | Spark detects and splits the skewed partition in joins | Automatic; the first option |
| Salting | Add a random component to the key to spread it out | Aggregations and joins that the above does not solve |
Salting the key adds a column with a random number between 0 and N−1. You aggregate first by the key and the salt, which spreads the giant key across N pieces, and then by the key alone:
N = 8
salted = events.withColumn("salt", (F.rand(seed=1) * N).cast("int"))
partial = salted.groupBy("customer_id", "salt").agg(F.count("*").alias("n"))
total = partial.groupBy("customer_id").agg(F.sum("n").alias("events"))The result is identical (60,684 anonymous events), but in the first shuffle the null key is spread across eight groups, and the second only moves a few rows that are already summarised. It has a price: one more shuffle and less readable code. For a simple count it is not worth it, because the partial aggregation Spark does before the shuffle already solves the problem; the technique pays off in joins and in aggregations that cannot be computed piecewise. In a join you also have to salt the other side, replicating each of its rows N times, one for each value of the salt.
Adaptive Query Execution
Catalyst decides the plan before running it, with size estimates that are often wrong. Adaptive Query Execution (AQE), enabled by default since Spark 3.2, replans during execution: when each shuffle finishes, Spark knows the real size of each partition and adjusts what remains to be done.
| What AQE does | Problem it solves |
|---|---|
| Merges small shuffle partitions | The fixed value of 200 partitions |
| Swaps a sort-merge join for a broadcast | Tables that turn out to be small after filtering, and that the prior estimate thought were large |
| Splits skewed partitions in joins | Skew, without touching the code |
That is why plans begin with AdaptiveSparkPlan isFinalPlan=false: what explain() prints is the initial plan. The plan actually executed can be consulted in the SQL / DataFrame tab of the Spark UI, where merged partitions appear as AQEShuffleRead.
AQE is no excuse for not understanding the above: it only acts after a shuffle (it cannot avoid the first one), its handling of skew covers joins but not every aggregation, and it does not fix a badly designed query.
cache and persist: when to use them and when not to
Remember lesson 03-02: each action recomputes the DataFrame from the source. If the same intermediate result feeds several actions, you can ask Spark to keep it:
sessions = events.groupBy("session_id").agg(F.count("*").alias("num_events"))
sessions.cache() # marked for keeping; nothing is kept yet
sessions.count() # first action: computes and keeps
sessions.where("num_events > 10").count() # reuses what was kept
sessions.unpersist() # releases the memorycache() is lazy: the data is kept during the first action that follows. It is equivalent to persist() with the default storage level (memory, and disk for whatever does not fit); persist(level) lets you choose another, such as disk only. What is kept can be seen in the Storage tab of the Spark UI.
Use cache when… |
Do not use it when… |
|---|---|
| The same DataFrame is used in several actions | It is used only once: it is cost with no benefit |
| Computing it is expensive (joins, aggregations, reading JSON or CSV) | It is a simple Parquet read with filters: rereading is usually just as fast and keeps column pruning |
| It fits in memory with room to spare | It is so large that it evicts memory needed for the computations |
| You are going to iterate over it (machine learning, interactive exploration) | "Just in case" |
The cache is not free: the first action is slower, because as well as computing it has to store, and the memory it takes up is no longer available for everything else. In a test with the bronze events (reading JSON and deduplicating, followed by three actions), the cached version was no faster than the uncached one on the machine where the lesson was prepared: with 38 MB, rereading costs less than storing. It is a good reminder that caching is a decision taken by measuring, not a habit.
High-cardinality columns: bucketing, sorting and clustering
Lesson 02-04 left a question open. Queries such as "all the events of customer 512" are frequent, but partitioning web_events by customer_id would create two million directories. The cardinality of a column is its number of distinct values, and directory partitioning only works when it is low. For high-cardinality columns there are three families of techniques.
| Technique | Idea | Benefit | Available in |
|---|---|---|---|
| Bucketing | Spread the rows across a fixed number of files according to the hash of the column | Avoids shuffles in joins and aggregations on that column | Tables registered in a catalogue |
| Sorting | Write the data sorted by the column | Parquet's min/max statistics make it possible to skip files and row groups | Any Parquet or ORC file |
| Z-order and clustering | Sorting that groups by several columns at once | The same, for filters on different columns | Table formats (Delta, Iceberg, Hudi) |
Bucketing
Instead of one directory per value, you set a number of buckets: each row goes to the bucket that results from applying a hash function to the column. Two million customers fit into, say, 64 buckets.
(
events.write
.bucketBy(8, "customer_id")
.sortBy("customer_id")
.mode("overwrite")
.saveAsTable("events_bucketed")
)
spark.table("events_bucketed").groupBy("customer_id").count().explain()+- HashAggregate(keys=[customer_id#1224L], functions=[count(1)])
+- HashAggregate(keys=[customer_id#1224L], functions=[partial_count(1)])
+- FileScan parquet spark_catalog.default.events_bucketed[customer_id#1224L] Batched: true, Bucketed: true, ... SelectedBucketsCount: 8 out of 8There is no Exchange. Spark knows that all the rows for a customer are already in the same bucket and aggregates without a shuffle. A join between two tables with the same buckets on the same key likewise saves both shuffles; and a customer_id = 512 filter reads a single bucket.
Bucketing requires saveAsTable, because the bucket information is stored in the catalogue, not in the files. If you try the snippet, Spark will create a spark-warehouse/ folder in the directory you run it from; you can delete it afterwards.
Sorting and statistics
Remember from lesson 02-02 that Parquet stores the minimum and maximum of each column in every row group. If the events are written sorted by customer_id, each file contains a narrow range of customers, and the customer_id = 512 filter discards almost all of them just by looking at their statistics. With the data unsorted, 512 could be in any file and they all have to be read.
# Illustrative: target_path would be the folder of the new table
(
events.repartition("date")
.sortWithinPartitions("customer_id")
.write.mode("overwrite").partitionBy("date").parquet(target_path)
)It is the simplest technique: it combines partitioning by date with sorting by customer_id within each day. Its limit is that an ordinary sort only favours the first column in the order.
Z-order and clustering in table formats
The open table formats from lesson 02-05 take this idea further. Z-order interleaves the values of several columns so that rows that are similar in any of them end up close together; that way, both a filter on customer_id and one on product_id can skip files. In Delta Lake it is applied with a maintenance command (illustrative):
Its evolution is clustering declared on the table itself (liquid clustering in Delta Lake; write and rewrite orders in Iceberg): you state which columns to group by and the format maintains it incrementally, without rewriting everything, and lets you change the columns later on. In new lakehouse projects, these techniques are replacing both bucketing and, in part, directory partitioning.
In short: partition by low-cardinality columns that are always filtered on (date); for high-cardinality ones, sort or cluster the data within the partitions; never partition by them.
Small files and compaction
When writing, Spark generates one file for each in-memory partition (and for each partition directory to which that partition contributes rows). After a shuffle without AQE, that means 200 files, whatever the size of the data:
spark.conf.set("spark.sql.adaptive.enabled", "false")
by_session = events.groupBy("session_id").count()
by_session.write.mode("overwrite").parquet(str(SCRATCH / "sessions_200"))
spark.conf.set("spark.sql.adaptive.enabled", "true")
by_session = events.groupBy("session_id").count()
by_session.write.mode("overwrite").parquet(str(SCRATCH / "sessions_aqe"))| Without AQE | With AQE | |
|---|---|---|
| Parquet files written | 200 | 1 |
| Total size | 375 kB | 178 kB |
| Write time (approximate) | 2.2 s | 0.3 s |
The same 30,759 rows take up twice the space when spread across 200 files, because each one carries its own header and footer and compresses worse, and they take several times longer to write. It is the small files problem from lesson 02-01, created this time by the process itself. At real scale, a table with millions of files of a few kilobytes becomes painfully slow to list and to read.
How to control it when writing:
| Situation | Solution |
|---|---|
| Small result | coalesce(1) or a few partitions before write |
| Table partitioned by directories | repartition("partition_column") before partitionBy, as in build_lake.py |
| Files that are too large | The maxRecordsPerFile write option |
| Table that receives many small writes (streaming, frequent loads) | Periodic compaction |
Compacting means rewriting many small files as a few large ones, with a usual target size of between 128 MB and 1 GB. With "plain" Parquet you have to do it by hand: read the partition, reduce its in-memory partitions and write it to another path. Table formats offer it as a maintenance operation (OPTIMIZE in Delta Lake, rewrite_data_files in Iceberg), safe even when there are concurrent reads.
Memory and OOM errors
OOM (Out Of Memory) is the most feared error in Spark. The first thing is to know who has run out of memory, because the causes and the remedies are different:
| Where | Typical causes | Remedies |
|---|---|---|
| Driver | collect() or toPandas() on a large result; broadcasting a table that is too large |
Do not bring data to the driver: aggregate or limit first, or write to disk. Only then, raise --driver-memory |
| Executor | A huge partition (skew); too few partitions for a lot of data; caching too much; UDFs that accumulate data | More partitions, handle the skew, release caches. Only then, raise --executor-memory |
The classic trap is collect(). The driver is a single process with modest memory; collect() asks it to receive all the rows from all the executors:
rows = events.collect() # 200,000 rows: it works here
# With 40 million events a day: java.lang.OutOfMemoryError in the driverThe alternatives: show(n) or take(n) to look, limit(n).toPandas() for a sample, a prior aggregation for a summary and write for everything else. toPandas() carries exactly the same risk as collect().
Raising the memory is the last resort, not the first: if the cause is a 50 GB skewed partition, no reasonable executor will cope with it.
Diagnosing with the Spark UI
Faced with a slow application, the Spark UI (lesson 03-02) lets you locate the problem by following an order:
- Jobs tab: which job accounts for the time?
- Stages tab, within that job: which stage is the slow one? Look at its Shuffle Read and Shuffle Write columns: they show how much data it has moved.
- Stage detail, Summary Metrics: compare the median and the maximum task duration and size.
- SQL / DataFrame tab: the plan actually executed, with the rows coming out of each operator.
| Symptom | Likely diagnosis |
|---|---|
| One task takes much longer than the rest | Skew |
| Thousands of tasks lasting milliseconds | Too many partitions or small files |
| Shuffle Read of many gigabytes | Avoidable shuffle: can you filter earlier or use broadcast? |
| Spill column (spilling to disk) with high values | Partitions too large for the memory |
| High GC Time in the executors | Insufficient memory or excessive caching |
| An operator in the plan produces far more rows than its input | A join multiplying rows because of duplicate keys |
The same FileScan is repeated across several jobs |
Recomputation: a candidate for cache |
Checklist
In order of usual impact:
- Read less. Parquet, filters on the partition column, only the columns you need. Check
PartitionFilters,PushedFiltersandReadSchema. - Filter and aggregate early, before the joins.
- Count the
Exchanges in the plan and ask yourself whether each one is necessary. - Broadcast the small tables in joins.
- Watch out for skew in join and aggregation keys, starting with the nulls.
- Leave AQE enabled and tune
spark.sql.shuffle.partitionsonly if you need to. - Avoid Python UDFs (lesson 03-03).
- Use
cacheonly for expensive results that are reused, and release them. - Control the output files: neither thousands of small ones nor one giant one.
- Do not bring data to the driver.
- Measure before and after. Optimising without measuring is guessing.
Common Mistakes and Tips
- Optimising by intuition. The plan and the Spark UI tell you where the time goes; it is almost never where you suspected.
- Drawing conclusions from times measured on small data. Locally, Spark's start-up and planning weigh more than the computation. What can be extrapolated is the plan, not the seconds.
- Using
repartition(1)to write one file. It triggers a full shuffle;coalesce(1)achieves the same without one. - Using
coalesce(1)before a heavy computation. As there is no shuffle, the reduction can propagate backwards and leave the whole computation in a single task. Use it just before writing small results. - Forcing a broadcast of a large table. It ends in OOM. The hint is for tables of a few megabytes.
- Caching everything. Every unnecessary cache takes memory away from shuffles and joins.
- Raising the memory as the first reaction to an OOM. Find out first whether it is the driver or an executor, and why.
- Tip: when a query is slow, start with
explain()and look for three things: what is read (FileScan), how manyExchanges there are and what type of join is used. That is enough to diagnose most cases.
Exercises
Exercise 1: reading a plan
This is the (abbreviated) plan of a query on the silver tables. Answer: which tables are read, and which columns of each? How many shuffles are there? What type of join is used, and why? Is the partitioning of web_events being taken advantage of?
+- HashAggregate(keys=[category#30], functions=[count(1)])
+- Exchange hashpartitioning(category#30, 200), ENSURE_REQUIREMENTS
+- HashAggregate(keys=[category#30], functions=[partial_count(1)])
+- Project [category#30]
+- BroadcastHashJoin [product_id#15L], [cast(product_id#28 as bigint)], Inner, BuildRight
:- Filter (isnotnull(event_type#17) AND (event_type#17 = purchase) AND isnotnull(product_id#15L))
: +- FileScan parquet [product_id#15L,event_type#17,date#18] PartitionFilters: [isnotnull(date#18), (date#18 = 2026-06-15)], PushedFilters: [IsNotNull(event_type), EqualTo(event_type,purchase), IsNotNull(product_id)]
+- BroadcastExchange
+- FileScan parquet [product_id#28,category#30]Exercise 2: output files
Write the count of events by session_id to lake_scratch/ in three ways: with repartition(50), with coalesce(1) and without specifying anything. Count the .parquet files in each folder and explain the result.
Exercise 3: skew in a join
Laura wants to add the customer's province to each event with events.join(customers, "customer_id", "left"), at NovaMarket's real scale (40 million events a day; 2 million customers, which take up about 80 MB in Parquet). What is the risk? Propose two solutions.
Solutions
Exercise 1
web_eventsis read (columnsproduct_idandevent_type, plus the partition column,date), as isproducts(product_idandcategory). The remaining columns are not even touched.- There is one shuffle: the
Exchangebycategory, needed for the final aggregation.BroadcastExchangedoes not count as a shuffle. - The join is a broadcast hash join:
productsis tiny (200 rows) and is sent to every executor. - Yes:
PartitionFilterscontainsdate = 2026-06-15, so only one directory out of the 31 is opened. In addition, the filter onevent_typeis applied inside the files (PushedFilters).
The query counts the purchases on 15 June by product category. It is a plan that is hard to improve. The cast(product_id as bigint) reveals a detail: the column is long in events and int in products, and Spark has had to convert one of them. Here it is harmless, but unifying the key types in silver avoids surprises.
Exercise 2
import os
by_session = events.groupBy("session_id").count()
variants = {
"repartition_50": by_session.repartition(50),
"coalesce_1": by_session.coalesce(1),
"default": by_session,
}
for name, df in variants.items():
path = str(SCRATCH / f"sessions_{name}")
df.write.mode("overwrite").parquet(path)
files = [f for f in os.listdir(path) if f.endswith(".parquet")]
print(name, len(files))You get 50, 1 and 1 files. repartition(50) forces 50 partitions, and therefore 50 tiny files; coalesce(1), one. In the default case, AQE has merged the 200 shuffle partitions into a single one because the result is small; with AQE disabled there would have been 200. The lake_scratch/ folder is disposable: you can delete it when you finish.
Exercise 3
The risk is skew from the null key. 30% of the events, about 12 million a day, have a null customer_id. In a left join those rows are kept and, if the join is resolved with a shuffle, they all go to the same partition: a gigantic task, slow and a candidate for OOM. And it is pointless work, because a null will never find a match.
Solutions:
-
Separate out the anonymous events. Join only the events with a non-null
customer_idand then combine the anonymous ones with the province set to null:identified = events.where("customer_id IS NOT NULL").join(customers, "customer_id", "left") anonymous = ( events.where("customer_id IS NULL") .withColumn("name", F.lit(None).cast("string")) .withColumn("province", F.lit(None).cast("string")) .withColumn("signup_date", F.lit(None).cast("date")) ) result = identified.unionByName(anonymous) -
Broadcast
customers:events.join(F.broadcast(customers.select("customer_id", "province")), "customer_id", "left"). At 80 MB it exceeds the automatic 10 MB threshold, but it is perfectly manageable when indicated by hand, especially if only the necessary columns are selected. With no shuffle there is no skewed partition.
The second is the simpler one and the one that would be used here. AQE's automatic splitting of skewed partitions would also help if the join were sort-merge, but it is better not to depend on it when there is a direct solution.
Conclusion
Optimising Spark starts with looking. The execution plan produced by Catalyst shows what is read (FileScan), where the shuffles are (Exchange) and which join strategy is used. The shuffle, triggered by wide transformations, is the dominant cost: it is reduced by reading and moving less data, by broadcasting small tables in joins and by choosing the number of partitions well with repartition, coalesce and spark.sql.shuffle.partitions. Skew concentrates the work in a few tasks and is countered by handling the problem keys separately, with broadcast, with salting or by letting AQE act, which also corrects the number of partitions and the join strategy on the fly. Caching only pays off for expensive, reused results. High-cardinality columns are not partitioned on: you use bucketing, sorting or the clustering of table formats. And when writing you have to watch out for small files and, at all times, the memory of the driver and the executors.
So far, all the processing you have seen is batch processing: you start from a closed dataset, process it and obtain a result. But two of NovaMarket's use cases cannot wait for the nightly batch: detecting a fraudulent payment is of little use the next day, and the "live" sales dashboard has to be genuinely live. In the next lesson, Real-Time Processing, you will see how data is processed as it arrives: what changes when the dataset never ends, how events are transported with Apache Kafka and how the same Spark you already know can work in streaming mode.
