Caching Before the Filter

Take an events table partitioned by event_date into 90 daily directories, with 40 columns in its files. A job needs Brazil's events from a single day and reuses them in 3 aggregations, so it caches. Here are 2 placements of cache() that return identical rows.

events = spark.table("events").cache()
brazil = (
    events
    .filter("event_date = '2024-03-14' AND country = 'BR'")
    .select("user_id", "event_type")
)
brazil.count()
brazil = (
    spark.table("events")
    .filter("event_date = '2024-03-14' AND country = 'BR'")
    .select("user_id", "event_type")
    .cache()
)
brazil.count()

Why the filter stops at the cache

Calling cache() registers the plan as it stands at that moment with Spark's cache manager. When a later query is planned, Spark searches it for any subtree that produces the same result as a registered plan and swaps that subtree for an InMemoryRelation. That swap happens before optimization. In the first version the registered plan is a scan of every file, so by the time the optimizer would push event_date and country into the scan, the scan sits behind the cache. Both conditions run as a filter over cached batches, and the first action reads and stores all 90 partitions and all 40 columns.

Cache eviction makes the cache-first job worse. Storage memory sized for a single day's slice cannot hold the whole table, so cache(), whose default level includes disk, writes most of it to the executors' local disks before the first count returns, and all of it was read without pruning. The filter-first job reads even less than its day of files, because column pruning skips the 37 columns that nothing selects or filters on.

Cached batches carry per-column minimum and maximum values, so InMemoryTableScan can skip whole batches that cannot match a filter. That saving starts only after the full table has been read and stored.

Where the cache belongs

Caching before the filter is right only when the consumers truly share the whole input. If 6 reports each filter a different country from the same day, cache that day once, with the union of the columns they need, and let each report apply its own country filter to the cache. The cached plan should get every filter and column choice all its consumers share and leave out only what they differ on. If the shared part still exceeds storage memory, write it out as a table and let each consumer prune its own read.

A notebook caches spark.table("clicks") and runs 1 aggregation on it. Later in the same session it runs spark.table("clicks").filter("click_day = '2024-03-14'").count(), where clicks is partitioned by click_day, and every cached block is still resident. How many partitions does that count read from the files?

Run the filter-first version on orders. Then move .cache() to directly after spark.table("orders"), which puts the filter and select after it. Run again. The 2 results match: placement changes what Spark reads and stores, and the rows stay the same. To see which version you wrote, call completed.explain() in each. Filter-first, the plan under InMemoryRelation holds the Filter on status and a scan reading 3 of the table's 4 columns. Cache-first, InMemoryRelation sits directly above a scan reading all 4 columns, and the Filter runs on top of InMemoryTableScan.

About this lesson

This section is part of the Memory and Caching: Advanced 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.