icon Join with us for Oracle DBA Training Live Session ENROLL NOW

Caching and Persisting DataFrames in Apache Spark

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
  • 02 Dec, 2026
  • 0 Comments
  • 5 Mins Read

Caching and Persisting DataFrames in Apache Spark

1. Why do we need cache and persist?

In Spark, transformations such as filter(), select(), join() and groupBy() are evaluated lazily. Spark builds a logical execution plan when these transformations are defined. The work is generally performed only when an action—such as count(), show(), collect() or writing a result—is executed.

If the same intermediate DataFrame is used by multiple actions or downstream operations, Spark may need to recompute its lineage. Caching or persisting stores the computed partitions so later operations can reuse them instead of repeating the upstream work.

Real-time example: imagine a daily sales DataFrame that is read from cloud storage, cleaned, joined with product data and reused for revenue, region-wise and category-wise reports. Persisting the cleaned result can avoid repeating the read and cleaning steps for every report.

2. What is cache()?

cache() is a convenience method that marks a DataFrame for caching using Spark’s default storage level for that API. In PySpark DataFrames, the default is MEMORY_AND_DISK_DESER in current Spark releases: Spark attempts to keep cached partitions in memory in deserialized form and can use disk for partitions that do not fit. Exact behavior can depend on the Spark version and API.

clean_sales_df = raw_sales_df.filter("status = 'COMPLETED'").select("order_id", "region", "amount")

clean_sales_df.cache()
clean_sales_df.count()   # action materializes the cached partitions

Important: calling cache() does not immediately calculate and store the DataFrame. It marks the DataFrame for caching. The first action that needs the data materializes the cached partitions. If you never run an action, the cache may never be populated.

3. What is persist()?

persist() also marks a DataFrame for reuse, but it lets you choose a StorageLevel. This gives you more control over whether Spark should use memory, disk, serialized storage, replication, or combinations of these.

from pyspark import StorageLevel

clean_sales_df.persist(StorageLevel.MEMORY_AND_DISK)
clean_sales_df.count()   # materializes the persisted DataFrame

In short: cache() is the simple, default choice; persist() is the configurable choice. For DataFrames, cache() is effectively equivalent to persist() with the DataFrame API’s default storage level. You normally choose one for a DataFrame rather than calling both.

4. Cache vs. persist

Aspect cache() persist()
Purpose Reuse computed partitions Reuse computed partitions
Storage control Uses the API’s default level Lets you specify a StorageLevel
Best suited for Simple, common caching needs When you need to choose memory/disk/serialization/replication
Materialization On the first action that computes it On the first action that computes it
Release unpersist() unpersist()

5. Common PySpark StorageLevels

StorageLevel describes how Spark stores each cached partition. The options below are the commonly used PySpark levels. Availability and exact defaults should be checked against the Spark version running on the Databricks Runtime.

Storage level Meaning When to consider it
MEMORY_ONLY Keep deserialized partitions in memory. Partitions that do not fit may be recomputed when needed. When the working set comfortably fits in executor memory and fast access matters.
MEMORY_AND_DISK Keep partitions in memory where possible; spill remaining partitions to disk. A practical option when the full cached DataFrame may not fit in memory.
MEMORY_ONLY_SER Store serialized partitions in memory; reduces object overhead but requires deserialization on access. When available in the Spark/PySpark version and memory efficiency is important.
MEMORY_AND_DISK_SER Serialized partitions in memory, with disk used when needed. When serialized storage is preferred and disk fallback is useful.
DISK_ONLY Store cached partitions on disk rather than memory. When recomputation is expensive but memory is constrained; access is slower.
OFF_HEAP Use Spark-managed off-heap memory when off-heap memory is configured. Specialized deployments with off-heap memory configured and tested.
*_2 variants Replicate each partition to another executor for fault tolerance (for example, MEMORY_AND_DISK_2). Specialized cases where extra resilience is worth the additional storage/network cost.

Version note: Spark 3.x/4.x APIs and Databricks Runtime versions may differ in which constants are exposed or recommended. In particular, serialized DataFrame storage levels are not always available in the same way as RDD storage levels. For DataFrames, use the StorageLevel constants actually exposed by the installed PySpark version; MEMORY_AND_DISK is a widely used portable choice.

6. End-to-end Azure Databricks example

Scenario: an e-commerce team reads transaction data, filters completed orders, derives a revenue column and reuses the cleaned DataFrame for multiple business reports. The example creates sample data, so it can be run directly in a PySpark notebook without uploading a file.

Step 1 — Create sample data

from pyspark.sql import functions as F
from pyspark import StorageLevel

sales_data = [
    (101, "North", "Laptop", 2, 50000, "COMPLETED"),
    (102, "South", "Phone",  3, 20000, "COMPLETED"),
    (103, "West",  "Tablet", 1, 15000, "CANCELLED"),
    (104, "North", "Phone",  2, 20000, "COMPLETED"),
    (105, "East",  "Laptop", 1, 50000, "COMPLETED"),
    (106, "West",  "Phone",  1, 20000, "PENDING")
]

columns = ["order_id", "region", "product", "quantity",
           "unit_price", "status"]

sales_df = spark.createDataFrame(sales_data, columns)
display(sales_df)

Step 2 — Transform the data

completed_sales_df = (
    sales_df
    .filter(F.col("status") == "COMPLETED")
    .withColumn("revenue", F.col("quantity") * F.col("unit_price"))
    .select("order_id", "region", "product", "quantity", "revenue")
)

display(completed_sales_df)

Step 3A — Use cache()

cached_sales_df = completed_sales_df.cache()

print(cached_sales_df.is_cached)

# The action triggers computation and populates the cache
print("Rows:", cached_sales_df.count())

# Reuse the cached DataFrame for multiple reports
display(
    cached_sales_df.groupBy("region")
    .agg(F.sum("revenue").alias("total_revenue"))
)

display(
    cached_sales_df.groupBy("product")
    .agg(F.sum("revenue").alias("total_revenue"))
)

The first count() computes the upstream transformations and materializes the cache. The subsequent aggregations can reuse cached partitions while they remain cached and available.

Step 3B — Use persist() with a chosen level

# First remove the cache created in Step 3A if you are testing both
cached_sales_df.unpersist()

persisted_sales_df = completed_sales_df.persist(
    StorageLevel.MEMORY_AND_DISK
)

print("Rows:", persisted_sales_df.count())

display(
    persisted_sales_df.groupBy("region")
    .agg(F.sum("revenue").alias("total_revenue"))
)

Run either Step 3A or Step 3B as the caching approach for a given DataFrame. The unpersist() call is included so the two demonstrations do not compete for the same cached resources.

7. How do I verify whether a DataFrame is cached or persisted?

Method 1 — Check storageLevel in PySpark

print(persisted_sales_df.is_cached)
print(persisted_sales_df.storageLevel)
print(persisted_sales_df.storageLevel.useMemory)
print(persisted_sales_df.storageLevel.useDisk)
print(persisted_sales_df.storageLevel.deserialized)
print(persisted_sales_df.storageLevel.replication)

A non-NONE StorageLevel indicates that a storage policy has been assigned to the DataFrame. For example, MEMORY_AND_DISK will show that memory and disk are enabled. This is a useful programmatic check, but it does not by itself prove that every partition has already been materialized or is currently resident.

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo