Where to Put the Cache

Concepts covered: Caching & Persistence

Every action you call runs the full chain of transformations behind its DataFrame, starting from the source files. Spark keeps no result between actions unless you tell it to. A cache is that instruction: it stores the partitions of 1 DataFrame on the executors, so later actions start from the stored partitions and skip every step that built them. The decision that matters most is which DataFrame in the chain gets stored.

The board below plays 1 action on 7 orders split across 2 partitions. The filter keeps the 5 completed orders, the groupBy shuffles them by region across 3 tasks, and collect() returns 3 totals: West 210, East 120, North 60. Run kept.count() after it and Spark reads all 7 rows and filters them a second time, because nothing from the first run was kept.

kept = orders.filter(F.col("status") == "Completed")
totals = kept.groupBy("region").agg(F.sum("amount").alias("revenue"))
totals.collect()
orders
order_idregionstatusamount
1WestCompleted120
2EastCompleted80
3WestPending50
4NorthCompleted60
5EastCompleted40
6NorthCancelled30
7WestCompleted90

A job with 3 actions

Here is a daily job that reads click events, keeps 2 columns, joins them to users and runs 3 actions on the joined result. Suppose reading the event files takes 1.5 minutes, reading the user files takes 0.5 minutes and the join takes 5.

events = spark.read.parquet("/data/events/2024-03-15")
users = spark.read.parquet("/data/users")

clicks = events.filter(F.col("event_type") == "click").select("user_id", "page_id")
enriched = clicks.join(users, "user_id")

enriched.count()
enriched.groupBy("country").count().collect()
enriched.write.mode("overwrite").parquet("/reports/clicks_enriched")
Each action on the right runs every box to its left. The cache belongs on enriched, the last box all 3 actions share.
  • event files (source, daily files)
  • user files (source, daily files)
  • filter + select (transform, narrow)
  • join on user_id (transform, join)
  • enriched (storage, cache here)
  • count() (consumer, action 1)
  • country counts (consumer, action 2)
  • report write (consumer, action 3)
  • event files -> filter + select
  • filter + select -> join on user_id
  • user files -> join on user_id
  • join on user_id -> enriched
  • enriched -> count()
  • enriched -> country counts
  • enriched -> report write

Count the shared work

Without a cache, all 3 actions pay for the read and the join. Moving the cache earlier or later in the chain changes how much of that work repeats:

Where the cache sitsAction 1 runsActions 2 and 3 each runShared work in total
No cacheread + joinread + join21 min
On `clicks`read + joinusers read + join18 min
On `enriched`read + joina read of the cache7 min
On each action's own outputread + joinread + join21 min, plus 3 caches nobody reads again

The rule the table shows: put the cache on the last DataFrame every later action shares, the point where the chain branches. Cache earlier, and each action still repeats the steps between the cache and the branch. Cache later, on 1 branch, and only the action on that branch benefits.

Another way to read the table: for each later action, a cache saves the work between the source and the cached DataFrame. On clicks that is only the 1.5-minute events read, because the users read and the join still run after it. On enriched it is 7, because both reads and the join sit behind it. The wide steps usually dominate that number, so a cache placed right after a join or a groupBy saves the shuffle along with everything before it.

enriched = clicks.join(users, "user_id").cache()

These times leave out the cache's own costs, storing the partitions during the first action and reading them back in the later ones. Both are small next to a 5-minute join, and a later section of this lesson prices them.

Both actions read priced. Which DataFrame should carry .cache() to save the most work?

orders = spark.read.parquet("/data/orders")
paid = orders.filter(F.col("status") == "Completed")
lines = paid.join(order_items, "order_id")
priced = lines.withColumn("line_total", F.col("quantity") * F.col("unit_price"))

priced.groupBy("region").agg(F.sum("line_total")).collect()
priced.groupBy("product_id").agg(F.sum("quantity")).collect()

Narrow the cache before you store it

The branch point also decides how big the cache is, because a cache holds every row and every column of the DataFrame it sits on. If the 3 actions only read user_id, page_id and country, a select of those columns right before .cache() stores 3 columns instead of everything users carried. A filter placed before the cache shrinks it the same way, by rows.

About this lesson

This section is part of the Memory and Caching: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.