Releasing with unpersist()
Concepts covered: Caching & Persistence
A cached DataFrame stays stored until 1 of 3 things happens: your code calls unpersist() on it, the application ends, or Spark needs the room for something else. Spark cannot tell that your code has moved on, so a variable that no later line reads frees nothing. In a scheduled job that runs for an hour, a forgotten cache holds memory for the rest of the run, and the joins and aggregations on those executors have less memory to work with while it is held.
Notebooks make this worse. Picture a session on a cluster whose executors can hold about 400GB of cached data. Four cells each cache a 90GB result, and none is read again after its cell. By the fifth cell, 360GB is held for nobody. Storing the fifth result first means moving older partitions out of memory, at the default level by writing them to local disk, so the fifth cell pays to save data that is already dead.
unpersist() takes effect at once
cache() is lazy, but unpersist() is eager: when the line runs, Spark tells every executor to drop that DataFrame's stored partitions. By default it returns without waiting for the drop to finish, and unpersist(blocking=True) waits. The DataFrame itself still works afterwards. The next action on it recomputes from the source, exactly as if it had never been cached.
That timing decides where the call goes: after the last action that reads the cache, and before the work that needs the memory. Here is the pattern in a job with 2 phases:
visits = daily_events.join(users, "user_id").cache()
visits.count()
visits.groupBy("country").count().write.parquet("/reports/by_country")
visits.groupBy("device").count().write.parquet("/reports/by_device")
visits.unpersist()
baskets = orders.join(order_items, "order_id").cache()
baskets.count()Run the cell: bulk is cached, filled by count(), then released, and the final total still comes back correct because Spark recomputes bulk from transactions for it.
Three places to put the call
| Where visits.unpersist() sits | The 2 reports | Memory while baskets builds |
|---|---|---|
| right after `visits.count()` | both recompute the join from the source | free |
| after the by_device write | both read the cache | free |
| nowhere | both read the cache | still holding `visits` |
The first row is the costly mistake: the cache is filled, released and never read, so the job pays for storing it and then runs the join 2 more times. The last row costs memory instead of time: baskets competes with data nobody reads, and some of its partitions can end up on local disk or recomputed.
Releasing everything, and checking
spark.catalog.clearCache() drops every cached DataFrame and table in the session in 1 call. It fits the end of a notebook, or the boundary between 2 phases that share nothing. Inside a job where another part still reads a cache, it throws away work you meant to keep, so release by name there.
| Check | Shows | After cache() | After unpersist() |
|---|---|---|---|
| `df.is_cached` | whether the DataFrame carries the cache mark | `True`, even before any action | `False` |
| `print(df.storageLevel)` | the level the mark asks for | `Disk Memory Deserialized 1x Replicated` | `Serialized 1x Replicated`, meaning no memory and no disk |
| Storage tab | partitions stored and their size | a row once an action fills it | the row is gone |
Calling unpersist() on a DataFrame that was never cached does nothing and raises no error, so a release at the end of a code path is safe even when an earlier branch skipped the cache.
This job combines placement, the first action and release. What happens when it runs?
joined = events.join(users, "user_id").cache()
joined.show()
joined.groupBy("country").count().collect()
joined.unpersist()
joined.groupBy("device").count().collect()- cache() stores every partition at once, so both counts read memory and the join runs once
- show() fills the whole cache, and unpersist() waits until the device count has finished
- show() stores a few partitions, the country count stores the rest, and the device count recomputes the join
- The join runs once, because the cache is kept until the application ends regardless
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.