Caching and persistence
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 11:05 on Tuesday. The nightly report cleans SwiftKart's orders with three joins, then writes five summaries from the result. In the Spark UI you count the same three-join plan five times. So you add .cache() to eleven DataFrames, to be safe. The job gets slower, the Storage tab says 62% cached, and executors spill. Nora looks at the Storage tab: "Caching is not free. Find out what you bought."
You'll learn to
- Say what cache() keeps, where, and for how long
- Predict what happens to a cached partition that does not fit
- Choose between a cache, a checkpoint and a table
- Name the costs that make caching hurt
Learn
Five summaries, five full runs
Lesson 12.2 warned you: a DataFrame is a plan, and every action runs the plan again from the files. The nightly report has five actions on the same cleaned orders, so the three joins run five times.
You can ask Spark to keep a result once it has been computed. That is df.cache(), or df.persist(level) when you want to choose where it is kept.
Two things to know before you use it.
- It is lazy.
cache()only marks the plan. The first action that computes a partition stores it, and later actions read it back. - It is temporary. It lasts until you call
unpersist(), until Spark pushes it out of memory, or until the application ends. It is not a table: nothing survives the session.
Five summaries, without and with a cache
Two rows of a timeline: without a cache each of five summaries reruns the three joins for ten minutes; with a cache the first summary takes twelve minutes and the other four take two minutes each.
Made-up times. Top row: every summary pays for the three joins. Bottom row: the first summary pays a little extra to fill the cache, and the other four read it.
Cache in minispark
import minispark as ms
parsed = []
def parse(row):
parsed.append(row['order_id'])
return (row['customer_id'], 1)
pairs = ms.read_csv('data/orders.csv', 4).map(parse).cache()
print('after cache():', len(parsed), 'rows parsed')
print('orders:', pairs.count(), '| parsed:', len(parsed))
customers = pairs.reduceByKey(lambda a, b: a + b, 2).count()
print('customers:', customers, '| parsed:', len(parsed))
pairs.explain()
pairs.unpersist()
Read the three "parsed" numbers. After cache(): 0, because nothing ran. After the first action: 80. After the second action: still 80, because it read the parsed pairs from the cache. Without the cache it would be 160. The last line of output shows the plan now starts "from cache".
The trap: df.cache() on its own caches nothing. It only marks the plan. A notebook that calls df.cache() and then runs one action has paid for building the cache and used it zero times. People add df.count() right after cache() to fill it on purpose. Do that only when several actions follow. And cache the DataFrame you reuse, after the expensive work, not the raw read before it.
Where the kept data lives
A cache is not one big object on the driver. Each cached partition stays on the executor that computed it, as a block.
Every executor runs a BlockManager with two shelves: a MemoryStore for blocks in memory and a DiskStore for blocks in files on its local disk. A cached partition is a block named rdd_<rdd id>_<partition>, such as rdd_42_7. The driver keeps the index: its BlockManagerMaster records which executor holds which block.
The index feeds scheduling. A task over partition 7 is offered first to the executor that holds rdd_42_7 (PROCESS_LOCAL, Lesson 12.1). If that executor dies, its blocks are gone, and Spark recomputes those partitions from the plan.
Where cached blocks live
The driver's BlockManagerMaster tracks blocks; each executor's block manager holds some cached partitions in its memory store and others on its disk store.
One cached DataFrame of six partitions on two executors. Four partitions fitted in memory and two went to disk. The Storage tab of the Spark UI adds these up per DataFrame.
What a cached DataFrame looks like inside
A cached DataFrame is not kept row by row. Spark stores it in columns, in batches of 10,000 rows. Each column of a batch is compressed, and the batch remembers every column's min, max and null count, so a later filter can skip whole batches.
You never read the cache by name. Spark finds it by plan: when a later query contains a piece of plan that matches a cached one, that piece is read from memory. In explain() it shows as InMemoryTableScan over an InMemoryRelation.
So df.cache() helps every query built on df, even through a temp view.
What a cached plan looks like
Runs on your laptop:
clean = spark.read.parquet("orders").filter("currency = 'USD'")
clean.cache()
clean.count()
clean.filter("status = 'shipped'").select("customer_id").explain()
== Physical Plan ==
*(1) Project [customer_id#1]
+- *(1) Filter (isnotnull(status#3) AND (status#3 = shipped))
+- InMemoryTableScan [customer_id#1, status#3], [isnotnull(status#3), (status#3 = shipped)]
+- InMemoryRelation [order_id#0, customer_id#1, order_ts#2, status#3, currency#4, amount#5], StorageLevel(disk, memory, deserialized, 1 replicas)
+- *(1) Filter (isnotnull(currency#4) AND (currency#4 = USD))
+- *(1) ColumnarToRow
+- FileScan parquet [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] ...
Real Spark 3.5 in local mode, shortened. Read it from the bottom. The InMemoryTableScan reads 2 of the 6 cached columns and uses the status filter to skip batches. Now look at what was lost: the Parquet scan below the cache read all six columns, because the cache must be able to serve any later query.
Storage levels: what if it does not fit?
A storage level says where a block may be kept. Above all, it says what happens to a partition that does not fit in memory.
MEMORY_AND_DISK: what does not fit is written to local disk and read from there. This is the default ofcache()andpersist()on a DataFrame.MEMORY_ONLY: what does not fit is not cached at all. It is recomputed every time it is needed. This is the default ofcache()on an RDD.
The table lists the others.
Storage levels
| Level | Where, and in what form | A partition that does not fit |
|---|---|---|
| MEMORYONLY | Heap, as objects. RDD cache() default | Not cached: recomputed every time it is needed |
| MEMORYANDDISK | Heap, then local disk. DataFrame cache() and persist() default | Written to local disk and read from there |
| MEMORYONLYSER, MEMORYANDDISKSER | Serialised bytes (Java and Scala): smaller, more CPU to read | As above |
| DISKONLY | Local disk only | Always on disk |
| MEMORYANDDISK2 and other 2 | A second copy on another executor | Survives the loss of one executor |
| OFFHEAP | Serialised, outside the heap; needs spark.memory.offHeap.enabled | Not cached |
PySpark names the DataFrame default MEMORY_AND_DISK_DESER (since Spark 3.0, to match Scala): memory and disk, deserialised. Data of a Python RDD is always pickled, whatever the level says.
When memory runs out, a block is pushed out
Cached blocks live in storage memory, and that room is limited. When a new block needs space, or a join needs memory to work in, the MemoryStore pushes blocks out. This is called eviction.
It evicts the least recently used block first. It keeps its blocks in the order they were last read, and reading a block moves it to the back of the queue. One rule protects a cache from itself: it never evicts a block of the same RDD it is caching right now.
What happens to an evicted block depends on the storage level. Step through a small executor: 1,000 MB of storage memory, first the cleaned orders, then the order lines.
Two caches in 1,000 MB of storage memory
An executor with 1,000 MB of storage memory caches three orders blocks of 250 MB, then four order-line blocks of 200 MB; each new block that does not fit evicts the least recently used orders block, until only the order lines are left in memory.
The orders are cached. Three partitions of 250 MB each: 750 MB of the 1,000 MB are used.
The first order-lines block arrives.
rdd_5_0is 200 MB. 750 + 200 = 950 MB, so it fits.The second one does not fit. 950 + 200 is over 1,000. The least recently used block of another RDD goes:
rdd_3_0. WithMEMORY_AND_DISKit is written to local disk.The same again, twice.
rdd_5_2pushes outrdd_3_1, andrdd_5_3pushes outrdd_3_2. Memory now holds only order lines: 800 MB.The same story with MEMORY_ONLY. Nothing is written to disk. The three orders blocks are dropped: they are not cached anywhere any more.
Read each step top to bottom: memory, disk, nowhere. rdd_3 is the cleaned orders and rdd_5 the order lines. The second cache pushed the first one out completely.
A model of the MemoryStore
from collections import OrderedDict
def cache_blocks(blocks, capacity_mb, level):
"""Store blocks (id, MB) in order in capacity_mb of storage memory, evicting the
least recently used block of another RDD when one does not fit."""
memory, on_disk, recompute = OrderedDict(), [], []
for block, size in blocks:
rdd = block.split('_')[1]
while sum(memory.values()) + size > capacity_mb:
victim = next((b for b in memory if b.split('_')[1] != rdd), None)
if victim is None:
break
memory.pop(victim)
(on_disk if level == 'MEMORY_AND_DISK' else recompute).append(victim)
if sum(memory.values()) + size <= capacity_mb:
memory[block] = size
else:
(on_disk if level == 'MEMORY_AND_DISK' else recompute).append(block)
return list(memory), on_disk, recompute
orders = [(f'rdd_3_{p}', 250) for p in range(3)]
lines = [(f'rdd_5_{p}', 200) for p in range(4)]
for level in ['MEMORY_AND_DISK', 'MEMORY_ONLY']:
memory, on_disk, recompute = cache_blocks(orders + lines, 1000, level)
print(level)
print(' in memory:', memory)
print(' on disk: ', on_disk)
print(' recompute:', recompute)
The walkthrough as twenty lines of Python. Caching the order lines (800 MB) after the orders (750 MB) in 1,000 MB of storage memory pushed every orders block out. With MEMORY_AND_DISK they are read back from disk. With MEMORY_ONLY every later use recomputes them, three joins and all.
Remember: on the Storage tab, Fraction Cached below 100% means some partitions are not in the cache at all. With MEMORY_ONLY, those partitions are recomputed on every use.
What eleven caches cost
Now you can read your own job. Eleven caches fight for the same storage memory, and the joins need that memory too. A cache has five costs.
- Used once: you pay to build the batches and hold them, and you save nothing.
- It blocks pruning: the cache is built from a read of every column. A query that needed 2 columns with pushed filters now waits for a full-width read.
- It competes for memory: storage memory is shared with joins and sorts. A big cache makes them spill, or pushes another cache out.
- It goes stale: a cache is a snapshot. Data written by another job is not seen until you
unpersist()and rebuild it. - It leaks: caching inside a loop without
unpersist()piles up blocks until eviction never stops.
A cache and a join share one executor
One executor's memory with a cached table filling the storage side; when tasks of a join ask for execution memory, cached blocks are evicted to make room.
Press Next step and watch one thing: a table is cached, then a join starts, and the join pushes cached blocks out to get its working memory. Lesson 12.8 explains every region of this picture.
When the plan itself is the problem
A cache keeps the data and the plan behind it, called its lineage. If blocks are lost, Spark recomputes them from the lineage.
Sometimes the lineage is the problem. A job that updates a DataFrame in a loop of 50 rounds builds a plan 50 joins deep. Checking it takes minutes, and one lost block means recomputing all 50 rounds.
Checkpointing cuts the lineage off. df.checkpoint() writes the data to a folder on reliable storage, set with spark.sparkContext.setCheckpointDir(...), and returns a DataFrame whose plan is only a scan of those files.
df.localCheckpoint() cuts the lineage too, but keeps the data inside the executors. It is fast and not safe: lose an executor later, and the data cannot be recomputed.
Writing a real table does the same job, durably. Most pipelines do that between steps.
What checkpoint() does to the lineage
Two boxes side by side: the lineage of a cached DataFrame after fifty rounds is fifty joins over a scan, and after a checkpoint it is a single scan of the checkpoint files.
Read each box top to bottom, the result first. Left: everything Spark has to keep, check and maybe run again. Right: after checkpoint() the plan is one scan.
Which one to use
| Keeps the lineage? | Survives a lost executor? | Survives the application? | Use it for | |
|---|---|---|---|---|
| cache() / persist() | Yes | Yes, by recomputing (or a 2 replica) | No | A result read by several actions |
| checkpoint() | No: plan becomes a file scan | Yes: files on reliable storage | Files stay until removed | Deep iterative plans |
| localCheckpoint() | No | No: the job fails | No | Cutting a plan when speed beats safety |
| Write a table | No | Yes | Yes | Handing data to the next step or job |
On Databricks: a cache you do not manage
Databricks adds a second cache that needs no code. The disk cache keeps copies of the remote Parquet and Delta files a worker reads, on that worker's local SSDs. It fills on the first read, serves any later query that reads the same files, and notices when files change, so it is never stale.
It is on by default on worker types with local SSDs, uses at most half of that disk, and Databricks recommends it over the Spark cache.
So production pipelines on Databricks rarely call cache(). The disk cache speeds up repeated reads, and results that several jobs need are written to a Delta table. cache() earns its place in interactive work, and inside one job that reuses an expensive DataFrame.
Spark cache or disk cache?
| Spark cache (df.cache()) | Databricks disk cache |
|---|---|
| Stores a computed DataFrame (after joins, filters) | Stores copies of the raw files it read |
| In executor memory, then local disk | On the workers' local SSDs |
| You trigger it in code and must unpersist() | Automatic on the first read, evicted LRU |
| A snapshot: misses later writes | Sees file changes automatically |
| Saves recomputing the plan | Saves fetching from object storage |
Numbers to remember
| Setting or name | Default | What it is |
|---|---|---|
| spark.sql.inMemoryColumnarStorage.batchSize | 10,000 rows | Rows in one cached batch |
| spark.sql.inMemoryColumnarStorage.compressed | true | Each column is compressed with a scheme chosen from its values: run-length, dictionary or delta encoding |
| CacheManager | matches by plan | Compares the analysed plan of every later query with the cached plans |
| CACHE TABLE t (SQL) | eager | Fills the cache at once, unless you write CACHE LAZY TABLE |
| df.checkpoint() | eager | Runs a job at once |
| spark.memory.storageFraction | see Lesson 12.8 | Joins and sorts can push cached blocks out only above this protected share of storage memory |
| spark.locality.wait | 3 s | How long a task waits for a free core on the executor that holds its cached block |
| 2 levels | two copies | A lost executor does not lose the block |
| spark.databricks.io.cache.enabled | on for worker types with local SSDs | The Databricks disk cache. It keeps files in a fast intermediate format and uses at most half of the local disk |
| Serverless compute | limited caching | df.cache() and persist() work only on recent environment versions (5 and above, in preview) and behave differently. CACHE TABLE is not supported. Check before you rely on them |
What changed at SwiftKart
You remove ten of the eleven caches.
One stays: on the cleaned orders, after the three joins and before the five summaries. You select only the columns the summaries need first, so the cache is narrow. The last line of the job is unpersist().
The three joins now run once, and the spill is gone.
Nora's rule: "Cache what is expensive and read more than once. Nothing else."
Six lessons in, you can read a plan, a shuffle and a cache. Something wrote those plans for you: it pushed your filters down and chose your joins. Lesson 12.7 opens it up: Catalyst and Tungsten.
In one line
cache() keeps a computed DataFrame in executor memory after the first action so later actions skip the work, but it costs memory, pruning and freshness, so cache only what is expensive and read more than once.
Interview corner
When should you cache a DataFrame, and when not?
When it is expensive to compute and read by more than one action, such as a cleaned table feeding several aggregations. Not when it is used once, when caching would replace a narrow pushed-down Parquet read with a full-width one, or when it would crowd out the execution memory joins and sorts need. cache() is lazy, so the first action fills it; unpersist it when done.
How is a cached DataFrame stored, and what happens when it does not fit?
Its plan becomes an InMemoryRelation filled with columnar cached batches of 10,000 rows, each column compressed and carrying min, max and null counts for batch skipping. The batches are blocks in each executor's block manager, tracked by the driver's BlockManagerMaster. The default MEMORY_AND_DISK level writes partitions that do not fit, or that are evicted least recently used, to local disk; MEMORY_ONLY drops them and recomputes them on use, which the Storage tab shows as Fraction Cached below 100%.
What is the difference between cache, checkpoint and localCheckpoint?
A cache keeps the data and the full lineage, so lost blocks are recomputed. checkpoint() writes the data to a reliable checkpoint directory and replaces the plan with a scan of those files, truncating the lineage; it is eager by default and suits deep iterative plans. localCheckpoint() truncates the lineage but stores the data in executors' block managers, so it is fast but a lost executor fails the job.
How does the Databricks disk cache differ from the Spark cache?
The Spark cache stores a computed DataFrame in executor memory and disk, triggered by code and kept until unpersist or eviction, and it does not see later writes. The disk cache automatically stores copies of the Parquet and Delta files a worker reads on its local SSDs, detects file changes, and helps any query reading those files. Databricks recommends the disk cache for repeated reads and Delta tables for results shared between jobs.