cache() vs persist()
Concepts covered: Caching & Persistence
cache() and persist() make the same request: keep this DataFrame's partitions on the executors once an action computes them. They differ in 1 thing, who chooses the storage level, meaning where the partitions are kept: memory, local disk or both.
| Call | Storage level it sets |
|---|---|
| `df.cache()` | the default for DataFrames: memory first, local disk for what does not fit |
| `df.persist()` | the same default |
| `df.persist(StorageLevel.MEMORY_ONLY)` | the level you pass, here memory only |
So cache() is shorthand for persist() with no argument. Reach for persist() when you want a level other than the default; the next section covers how to choose one. Both return the DataFrame they were called on and also mark it in place, so df.cache() on a line of its own works as well as df = df.cache().
Calling cache() on a DataFrame that is already cached changes nothing: Spark logs a warning that the data is already cached and keeps the first level. To switch levels, call unpersist() first, then persist() with the new level.
Marking is free, the first action pays
Like a transformation, cache() is lazy. The line returns at once, launches no job and stores nothing. The partitions are stored by the first action that computes them: as each task finishes a partition, the executor running it keeps a copy. That first action does all of its usual work plus the storing, so it runs a little slower than it would without the cache. Every action after it reads the stored copy.
Traced through the job from the previous section, with enriched.cache() on its own line before the actions:
| Line | What Spark does | Time |
|---|---|---|
| `enriched.cache()` | records the cache mark; no job runs | none |
| `enriched.count()` | reads, filters and joins, storing each partition as its task finishes | 7 min plus the storing |
| `enriched.groupBy("country").count().collect()` | reads the stored partitions and aggregates them | the aggregation only |
| `enriched.write.mode("overwrite").parquet(...)` | reads the stored partitions and writes them out | the write only |
The first action sets how much is stored
A partition is stored only when an action computes it in full, so the action you run first sets how much of the cache exists afterwards. count() has to visit every partition to count its rows, so it fills the whole cache. show() asks for 20 rows and computes only as many partitions as it needs to find them, sometimes 1 out of 200. The other 199 stay unstored until a later action computes them, and that later action pays the full build for each of them.
The DataFrame has 200 partitions. After show() finishes, how many of them are stored in the cache?
long_views = spark.read.parquet("/data/page_views").filter(F.col("dur_ms") > 1000).cache()
long_views.show()
long_views.count()- Only the partitions show() computed to find 20 rows, as few as 1
- All 200, because the cache() call stored them as the line ran
- All 200, because any action fills the whole cache the first time
- None, because show() previews rows without storing any of them
Checking the cache is in the plan
explain() shows whether a query will read the cache. After enriched.cache(), the plan for enriched.groupBy("country").count() starts from an InMemoryTableScan over an InMemoryRelation, where before it started from the file scans and the join. The plan reflects the mark, so it looks the same before and after the first action. To see how much is stored, open the Storage tab in Spark's web UI: it lists each cached DataFrame with its storage level, Cached Partitions, Fraction Cached, Size in Memory and Size on Disk. A Fraction Cached far below 100% right after a show() is the partial fill described above.
Try it on the practice data. The cache() line marks completed, count() computes and stores every partition, and the final collect() reads the stored copy to sum profit.
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.