Caching and persistence
Every time you run an action, Spark recomputes the DataFrame from the start. If you use the same result several times, caching keeps it in memory instead. This lesson shows how caching works, the storage levels, and when caching helps and when it only wastes memory.
Step 2 · Spark internals · Silver · Memory and resources, lesson 1 of 3
On this page
Show code in
Every code block on the page follows this.
Read first: Transformations vs actions (skip if you know it)
In plain words first
If you need the same figure from a long calculation five times, you write it on a sticky note after working it out once, instead of redoing the whole calculation each time. But a desk covered in sticky notes you never read again leaves no room to work.
cache() is the sticky note. Use it for results you really reuse, and remove it with unpersist() when you are done.
What it does
Without caching, every actionaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more → recomputes a DataFrame from its source. df.cache() tells Spark: the next time you compute this, keep the result. It is lazy: nothing is stored until an action runs.
clean = raw.filter(...).withColumn(...).cache() clean.count() # computes and caches clean.groupBy("a").count().show() # reads from cache clean.write.parquet("out") # reads from cache clean.unpersist()
CACHE TABLE clean AS SELECT ... FROM raw WHERE ...; SELECT a, COUNT(*) FROM clean GROUP BY a; UNCACHE TABLE clean;
Note the SQL difference: CACHE TABLE is eager by default and computes immediately; CACHE LAZY TABLE waits for the first use.
Storage levels
| Level | Where | Trade-off |
|---|---|---|
MEMORY_AND_DISK | Memory, spillingspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → to disk | Default for DataFrame.cache(). Safe choice. |
MEMORY_ONLY | Memory only | Partitionspartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → that do not fit are recomputed when needed. |
DISK_ONLY | Local disk | Cheap on memory; reading back costs I/O. |
..._2 variants | Two copies on two executorsexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → | Survives losing an executor; doubles the space. |
OFF_HEAP | Off-heap memory | Needs off-heap memory configured. |
DataFrames are cached in Spark's compressed in-memory columnar format, so cached data is often smaller than the same rows as plain objects. Use df.persist(StorageLevel.DISK_ONLY) to choose a level.
When caching helps
- The DataFrame is used by two or more actions, or two branches of the same job.
- It is expensive to compute (joins, wide aggregations, slow sources such as JDBC or APIs) and much smaller than its inputs.
- Interactive exploration, where you query the same subset repeatedly.
When caching hurts
- Caching something used once — You pay to write it to memory and gain nothing.
- Caching a plain read of ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → — Reading columnar files is already fast, and caching blocks filter pushdownpredicate pushdown: Applying a filter while reading files, so data that cannot match is skipped instead of read. Learn more → and column pruningcolumn pruning: Reading only the columns a query uses, which columnar files like Parquet make possible. Learn more → for later queries: they scan the whole cached data instead of skipping files.
- Caching huge DataFrames — Storage memory competes with execution memory for joins and aggregations, causing spills, evictions and slower jobs.
- Forgetting unpersist — Cached blocks stay until evicted or the application ends. In long-running sessions they accumulate.
Checking the cache
The Storage tab of the Spark UI lists cached DataFrames, the fraction cached and their size in memory and on disk. In the plan, cached data appears as InMemoryRelation / InMemoryTableScan.
checkpoint() is different: it writes the data to reliable storage and cuts the lineage, which helps with very long plans (iterative algorithms). localCheckpoint() does the same on executor storage, faster but not fault tolerant.Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Cache a result that two outputs reuse, so it is computed once, and release the memory afterwards.
from pyspark import StorageLevel from pyspark.sql import functions as F events = spark.range(0, 1_000_000).selectExpr( "id", "id % 1000 AS user_id", "id % 24 AS hour", "id % 97 AS amount") user_hours = (events.groupBy("user_id", "hour") .agg(F.count(F.lit(1)).alias("events"), F.sum("amount").alias("spend"))) user_hours.persist(StorageLevel.MEMORY_AND_DISK) # what cache() does for a DataFrame try: # Two outputs read the same expensive result: computed once, read twice. (user_hours.groupBy("hour").agg(F.sum("spend").alias("spend")) .write.mode("overwrite").parquet("lab/caching/spend_by_hour")) (user_hours.where("events > 41") .write.mode("overwrite").parquet("lab/caching/busy_user_hours")) finally: user_hours.unpersist() # give the memory back to the rest of the job print(spark.read.parquet("lab/caching/spend_by_hour").count(), "hours") print(spark.read.parquet("lab/caching/busy_user_hours").count(), "busy user-hours") spark.read.parquet("lab/caching/spend_by_hour").orderBy("hour").show(5)
Output from a real run
24 hours 3000 busy user-hours +----+-------+ |hour| spend| +----+-------+ | 0|2000243| | 1|2000200| | 2|2000157| | 3|2000114| | 4|2000071| +----+-------+ only showing top 5 rows
What to notice:
- Both outputs (24 hours, 3,000 busy user-hours) were built from the one cached
user_hours, not computed twice. unpersist()sits infinally, so the memory is given back even if a write fails.- While it is cached, the Spark UI's Storage tab lists it. Use
StorageLevel.DISK_ONLYfor large results when memory is needed for joins.
Goal: Measure how much a cache saves: recompute an expensive result, then read it from the cache.
import time from pyspark import StorageLevel from pyspark.sql import functions as F # Expensive to recompute: a Python UDF (slow on purpose) over 300,000 rows. slow_double = F.udf(lambda x: x * 2, "long") expensive = spark.range(0, 300_000).withColumn("doubled", slow_double("id")) def timed(label): t = time.time() # needs the UDF column, so it is computed expensive.agg(F.sum("doubled")).first() print(f"{label}: {time.time() - t:.2f}s") timed("no cache, first run") timed("no cache, recomputed") expensive.persist(StorageLevel.MEMORY_AND_DISK) print("cached:", expensive.is_cached, "|", expensive.storageLevel) timed("first cached action computes and stores") timed("later actions read the cache") expensive.unpersist()
Output from a real run
no cache, first run: 1.33s no cache, recomputed: 0.14s cached: True | Disk Memory Serialized 1x Replicated first cached action computes and stores: 0.38s later actions read the cache: 0.05s
What to notice:
- Ignore the first line: it includes starting the Python workers.
- Compare the recompute (
no cache, recomputed) with the last line: reading from the cache is several times faster. - The first cached action is not faster: it computes the result and stores it. Only later actions benefit.
Common mistakes
- Expecting cache() to compute immediately — It is lazy; the first action fills it.
- Caching after the last use — Cache before the DataFrame is reused, not after.
- Caching inside a loop without unpersisting — Memory fills with stale versions.
Key takeaways
- cache() is lazy; the first action stores the data.
- DataFrame.cache() uses MEMORY_AND_DISK in a compressed columnar format.
- Cache only data reused across actions and costly to recompute.
- Unpersist when done; cached data competes with execution memory.
Interview prep
THE QUESTION
"Should we cache every intermediate DataFrame to make the pipeline faster?"
Avoid: "yes, caching always makes it faster". The point is that caching costs memory and only pays off for reused, expensive results.
Follow-ups · answer out loud, then open
Follow-up"What is the default storage level of DataFrame.cache(), and how is it different from RDD.cache()?"
cache() use MEMORY_AND_DISK in a compressed columnar format. RDD.cache() uses MEMORY_ONLY, so partitions that do not fit are recomputed rather than spilled.Scenario"After caching a 500 GB DataFrame, a later join started spilling heavily and got slower. Why?"
DISK_ONLY, or do not cache.Trap"Caching the raw Parquet table speeds up every later query on it."
Check yourself
3 questionsWhen is the data of df.cache() actually stored?
Show the answer
At the first action that computes df. cache only marks the DataFrame; the first action fills the cache.
Default storage level of DataFrame.cache()?
Show the answer
MEMORY_AND_DISK. DataFrames default to MEMORY_AND_DISK.
Why can caching a raw Parquet read slow later filtered queries?
Show the answer
Queries on the cache cannot skip files and row groups using Parquet statistics. Once cached, queries scan the cached data and lose file-level pushdown and pruning.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · Memory and resources · lesson 2 of 3 · 7 min readBroadcast variables and accumulators
Why driver variables never change inside tasks, and the two shared variables Spark offers instead.
Related lessons
Transformations vs actionsSpark internals · 7 min read
The memory modelSpark internals · 7 min read
Jobs, stages and tasks
Previous: Broadcast joins
Primary sources: Caching data in memory · CACHE TABLE