Apache Spark · Beginner
What is the difference between cache() and persist() in Spark?
By Anurag Pandey, Lead Data Engineer ·
The short answer
cache() is persist() with the default storage level, MEMORY_AND_DISK_DESER for DataFrames. persist() lets you choose the level, such as memory only or memory and disk. Both are lazy: the data is stored the first time an action computes it.
Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.
Say it like this
About 50 seconds out loud. Use it as a model, then put it in your own words.
Both keep a DataFrame around so Spark doesn't recompute it every time I use it. cache() is simply persist() with the default storage level, which for PySpark DataFrames is MEMORY_AND_DISK_DESER: keep data in memory and spill to disk when memory runs out. persist() lets me choose the storage level myself, for example memory only, disk only, or a replicated level. Both are lazy. Calling cache() doesn't store anything yet; the data is stored the first time an action computes that DataFrame. Caching only helps when I reuse the same DataFrame more than once, like in a loop or in several joins. Otherwise it just uses memory that execution could have used. When I'm done with it, I call unpersist() to free that space.
What interviewers look for
- You know cache() is persist() with the default level.
- You explain that caching is lazy.
- You say when caching helps and when it hurts.
Common mistakes
- Saying cache() stores data immediately. It happens on the first action.
- Caching every DataFrame by habit, which wastes executor memory.
- Forgetting unpersist() in long-running jobs or notebooks.
Follow-up questions to expect
- 1What storage levels can you pass to persist()?
- 2How would you check what is cached in the Spark UI?
- 3When is checkpointing a better choice than caching?
Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.