Part XXII — Caching Is Not Free: Persist Levels and the Memory You Lose
From the publisher’s feed, collected in the ZeroLabs newsroom.
The fastest way to make a Spark job slower is to cache everything “just in case.” Here is the engine-level accounting of what `.cache()` actually costs — and the persist discipline that gets the speed back.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVI | Part XVII | Part XVIII | Part XIX | Part XX| Part XXI| Part XXIIThe Night the “Optimization” Doubled Our RuntimeAt 1:42 AM on a Tuesday, the revenue-aggregation pipeline breached its SLA for the first time in eleven months. The job was unglamorous but load-bearing: 3.4 TB of raw order events on S3, a nightly rollup feeding every finance dashboard in the company, running on 24 r5.2xlarge nodes with a steady-state runtime of 41 minutes at roughly $63 per run. It had been boring in the best possible way.The week before, a well-meaning engineer had “optimized” it. The diff was almost comically simple: .cache() after every major transformation — nine cached DataFrames, one per stage, on the theory that nothing should ever be computed twice. Code review waved it through. Caching is free performance, right?The first run after the change took 2 hours and 17 minutes. Two stages failed outright when YARN killed executors for exceeding their memory limits. The Spark UI told the real story: average GC pause per task had gone from 0.3 seconds to 11 seconds, the BlockManager had evicted 78% of cached blocks before any downstream stage read them, and the driver was spending more time serializing cache bookkeeping than scheduling work. We had spent the entire executor memory budget caching data nobody would ever read twice, and the garbage collector was charging us interest by the minute. Cost per run: $212. SLA: breached. Pager: mine.The rollback took four minutes. The lesson took longer to sink in: .cache() is not a performance hint. It is a memory allocation with a garbage-collection bill attached, and the engine will happily let you bankrupt yourself.So: what does a cached DataFrame actually cost, where does it live, and when is persisting data the right call versus pure overhead?The Mechanic Underneath: The BlockManager Rents You Memory by the ByteEvery cached partition lives in the BlockManager, Spark’s per-executor storage service — the same service that holds shuffle blocks and broadcast variables. On the JVM heap, memory is split by the UnifiedMemoryManager: after a 300 MB reserved region, spark.memory.fraction (default 0.6) of the heap becomes one unified region shared by execution (shuffles, joins, sorts) and storage (cache). Inside that region, spark.memory.storageFraction (default 0.5) draws a soft line — storage is guaranteed half the unified region, and it may borrow the rest, but execution memory can evict cached blocks whenever it needs the space.That last clause is the whole game. Your cache is not a reservation; it is a tenant with no lease. A big shuffle in a later stage can — and will — evict your carefully cached DataFrame block by block, LRU-first, with no warning and no ceremony. (Part V of this series covered this memory split in depth; here is where it bites.)And what you store matters more than where. MEMORY_ONLY, the default behind .cache(), stores deserialized Java objects — each row as a graph of objects on the heap. A 4-byte integer becomes a 16-byte Integer plus object header; a modest row can inflate 2–5x versus its serialized size. You are not caching 3 GB of data. You are caching 3 GB of data wearing a 12 GB object costume, and the garbage collector has to walk that costume on every major GC.MEMORY_ONLY Is a Bet You Usually LoseThe default storage level is the worst one for most production workloads, which is a remarkable design choice until you remember it was optimized for demos. Deserialized objects give you the fastest possible read — no deserialization cost on access — at the price of maximum footprint and maximum GC pressure. On heaps above ~32 GB the GC pauses on a fully cached, object-heavy RDD can exceed the time you saved by not recomputing.The rule is blunt: use MEMORY_ONLY only when the cached dataset is small, reused many times, and the cluster has memory to waste. That combination is rarer than the tutorials suggest. In our incident, nine DataFrames cached with MEMORY_ONLY consumed a combined 41 GB of heap across the cluster to hold roughly 14 GB of actual data — and the GC was spending 11 seconds per task just traversing it.Serialization Trades CPU for Survival: Why _SER ExistsAppending _SER to a storage level stores serialized bytes instead of objects — one compact byte array per partition instead of a thicket of objects. The trade is explicit: you pay deserialization CPU every time you read the cache, and you gain 2–5x smaller footprints plus dramatically lighter GC, because the collector sees a handful of byte arrays instead of millions of objects.Two details most teams miss. First, the serializer matters: the default Java serializer is slow and bloated; Kryo (spark.serializer=org.apache.spark.serializer.KryoSerializer) typically cuts serialized size by another 2–10x and is the difference between _SER being a win and a wash. Second, serialized caching composes well with whole-stage codegen (Part XVI's topic): generated code operating on Tungsten binary rows deserializes less and copies less, so the CPU tax of _SER shrinks exactly where the engine is fastest.Eviction Is Not Failure, It’s Policy: LRU and the Unpersist You ForgotWhen execution memory needs space, the BlockManager evicts cached blocks least-recently-used first. This is not an error — it is the documented policy — but it turns sloppy caching into a special kind of waste: you pay the full cost of writing blocks to memory (and to disk, for _AND_DISK levels), and then the engine throws them away before the second read you cached them for.The discipline has two halves. Cache lazily and deliberately: call .persist() with an explicit level, then force materialization with an action on your terms — a .count() right after persisting — so the cache is populated once, up front, instead of trickling in mid-stage while downstream tasks are already waiting. Unpersist aggressively: the moment the last consumer finishes, release the blocks. A cached DataFrame that outlives its last reader is not a cache; it is a memory leak with a Spark UI entry.If You Read It Once, Caching Is Pure OverheadHere is the decision rule, and it fits in one sentence: persist a dataset only if it is read more than once AND expensive to recompute. Both conditions. A DataFrame consumed by a single downstream stage gains nothing from caching — you pay serialization, memory, and GC, and you read it exactly as many times as you would have without the cache. A cheap-to-recompute frame (a filter over an already-cached parent) gains nothing either; recomputation is faster than the cache bookkeeping.In the incident diff, five of the nine cached DataFrames had exactly one consumer. They were pure overhead — memory spent to avoid recomputation that was never going to happen.Off-Heap Changes the Game but Not the Rulesspark.memory.offHeap.enabled moves storage outside the JVM heap into Tungsten's binary format, which largely sidesteps GC — the collector never sees off-heap bytes. It is the right answer when GC pauses dominate, but it does not change the accounting: off-heap memory is still finite, still shared with execution, and still evictable. It converts a GC problem into a capacity problem. The decision rule above still applies; off-heap just makes the "expensive to recompute" side of the ledger cheaper to satisfy.Executor Memory, AnnotatedThe Fix, and What It Cost# Naive: cache everything "just in case" — 9 DataFrames, MEMORY_ONLY default.# raw = spark.read.parquet("s3://lake/orders/").cache()# cleaned = raw.filter(...).cache()# enriched = cleaned.join(...).cache()# ... six more ...# Result: 41 min -> 2h17m, 11s GC pauses, 78% of blocks evicted unread.# Optimized: persist ONE frame — read twice, expensive to build — serialized,# materialized up front, released the moment its last consumer finishes.from pyspark import StorageLevelbase = ( spark.read.parquet("s3://lake/orders/") .filter("order_date >= current_date() - interval 90 days") .repartition(512, "order_date") # stable layout: cache once, reuse the partitioning)# MEMORY_AND_DISK_SER: serialized bytes survive memory pressure by spilling;# Kryo keeps the byte footprint small (set spark.serializer accordingly).base.persist(StorageLevel.MEMORY_AND_DISK_SER)base.count() # materialize NOW, on your terms — not trickling in mid-stageagg_a = base.groupBy("region").agg(...) # consumer 1agg_b = base.join(dims, "sku").groupBy(...) # consumer 2agg_a.write.mode("overwrite").parquet("s3://lake/revenue_by_region/")agg_b.write.mode("overwrite").parquet("s3://lake/revenue_by_sku/")base.unpersist() # last consumer done: give the memory back immediatelyThe numbers after the fix, same cluster, same data: wall-clock 2h17m → 38 minutes (three minutes faster than the pre-cache baseline, because the stable repartitioning also fixed a skew-adjacent shuffle). Cached footprint: 14 GB of objects → 3.1 GB of serialized bytes. Average GC pause: 11s → 0.4s. Evicted-before-read blocks: 78% → 0%. Executor losses: two per run → zero. Cost per run: $212 → $58 — and the 3 AM pager went back to sleep.The Catch: Persist Is Not Durability, and DISK_ONLY Is a TrapThree honest counterweights. First, persist is not durability: cached blocks die with the application. If you need data to survive a driver restart, that is checkpoint() (Part XVII's territory), which writes to reliable storage at the cost of breaking lineage. Persist is a within-application optimization, nothing more.Second, DISK_ONLY looks like a safety net and behaves like a tar pit: every read pays full disk I/O plus deserialization, and on cloud object stores the "disk" is often network-attached anyway. It is occasionally right for enormous, rarely-read frames — but measure it, because recomputation is frequently faster.Third, caching interacts with skew (Part VII’s playbook): persisting a skewed frame bakes the skew into every downstream consumer. Fix the partitioning first — as the repartition(512, "order_date") above does — then cache the balanced result. A cache of a bad layout is just a fast way to repeat a bad layout.Takeaways.cache() is MEMORY_ONLY: deserialized Java objects, 2–5x inflation, maximum GC pressure. It is the default, not the recommendation.The decision rule is two conditions: persist only if the dataset is read more than once AND expensive to recompute. One consumer means pure overhead.Serialize to survive: _SER levels trade a little CPU for 2–5x smaller footprints and GC the collector can actually traverse — pair with Kryo.Your cache has no lease: execution memory evicts storage LRU-first. Cache lazily, materialize with an action on your terms, and unpersist() the moment the last consumer finishes.Off-heap moves the problem: it kills GC pauses but not capacity limits or eviction. The accounting still applies.Fix the layout before you cache it: persisting a skewed or badly partitioned frame just makes every downstream stage repeat the mistake faster.Cache is a loan from the executor, and the garbage collector collects the interest.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XXII — Caching Is Not Free: Persist Levels and the Memory You Lose was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.