Spark · Trade-off
cache, persist, or neither
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
A teammate adds .cache() after almost every DataFrame in a job 'to make it faster', and the job got slower. When does caching help, when does it hurt, and what would you do instead?
Then
Follow-ups the interviewer asks next
- What's the difference between
cacheandpersist? - Does
cache()run anything right away? - How do you see what's cached and how much memory it takes?
- What's the difference between caching and checkpointing?
- When is writing an intermediate table better?
The answer
What a strong answer covers
- Helps when the same DataFrame feeds two or more actions, it's expensive to recompute (big scan plus joins), and it fits.
- Hurts when the data is used once, when it's cached before a filter (storing far more than needed), or when it takes memory the joins and aggregations need (more spill and GC).
cache()ispersist()with the default level: memory and disk for DataFrames (MEMORY_AND_DISK_DESERin PySpark).persist()lets you choose (MEMORY_ONLY,DISK_ONLY, replicated levels).- Lazy: stored on the first action that computes it; call
unpersist()when done. - The Storage tab in the Spark UI shows the fraction cached and its size.
- Checkpointing writes to reliable storage and cuts the lineage (useful for very long or iterative plans); a local checkpoint is faster but lost with the executor.
- Often better: restructure into one pass, or write the intermediate result to a table when it's large or reused by other jobs.
The red pen
Common traps
Avoid:caching everything; never unpersisting; expecting cache() to do work by itself.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.