Skip to main content
How-toLevel: Intermediate

Test DataFrame caching on Databricks serverless

Measure repeated transformations and make snapshot cleanup explicit before adopting the preview.

TechExplained 8 min readPublished: 3 November 2026Last updated: 3 November 2026
#databricks#serverless#performance#how-to
  1. 01

    Choose a workload that reuses the same intermediate result

    Caching is a design choice about reuse and freshness. A faster second result matters only if the complete execution improves and the data remains appropriate for the decision it supports. Do not begin by adding a cache call to every DataFrame.

    Consider a fictional analytics team using prepared order lines for two checks: counts by category and totals of a calculated measure. In a real workload, preparation might include an expensive join or aggregation. Our objective is to reuse that calculation responsibly within one working session.

    QuestionRecord before the experiment
    Which intermediate result is reused?The exact transformation and consuming steps
    How often is it used?Every action that needs the result
    How fresh must it be?Acceptable age and the meaning of a fixed snapshot
    What does the complete execution cost?A measured baseline without the change
    Who owns its lifecycle?Owner of cleanup, session management and recovery

    Start with a bounded workload without sensitive data. A small example helps you understand behavior; a representative trial determines usefulness. Keep those objectives separate in the report.

    Decision
    optimize one demonstrably reused intermediate result. Leave a simple, one-time read unchanged until measurement provides a specific reason to cache it.
  2. 02

    Check Azure prerequisites and preview scope

    Open the Azure DataFrame caching documentation and compare its requirements with your workspace. The feature is in Public Preview. The preview must be available and enabled; workspaces with the compliance security profile are outside the documented support.

    Serverless notebooks and jobs require environment version 5 or later. External Python clients require Databricks Connect 18.1.8 or later. Record your environment and client version so a colleague can reproduce the starting conditions.

    Use a Python notebook on serverless compute for this example. A serverless SQL warehouse is a different execution route. The serverless limitations distinguish supported DataFrame methods from unsupported SQL and catalog caching commands.

    Also confirm with the platform owner that this preview can be evaluated in the intended environment. The presence of an interface option does not constitute acceptance of new production behavior.

    Important
    do not transfer AWS-specific settings into Azure automatically. The additional Databricks reference below covers AWS; Microsoft Learn is the Azure reference for this guide.
  3. 03

    Build a reproducible baseline first

    Begin with synthetic data and a function that constructs a fresh DataFrame each time. The two checks below do not write data. Fixed inputs and expected output let you determine whether an optimization preserves the result.

    from time import perf_counter
    from pyspark.sql import functions as F
    
    ROWS = 100_000
    BUCKETS = 10
    
    def build_prepared():
        return (
            spark.range(ROWS)
            .withColumn("bucket", F.col("id") % BUCKETS)
            .withColumn("measure", F.col("id") * F.lit(2))
        )
    
    def summarize(df):
        by_bucket = df.groupBy("bucket").count().collect()
        totals = df.agg(F.sum("measure").alias("measure_total")).first()
        return {
            "rows": sum(row["count"] for row in by_bucket),
            "buckets": len(by_bucket),
            "measure_total": totals["measure_total"],
        }
    
    EXPECTED = {
        "rows": ROWS,
        "buckets": BUCKETS,
        "measure_total": ROWS * (ROWS - 1),
    }
    
    start = perf_counter()
    baseline = summarize(build_prepared())
    baseline_seconds = perf_counter() - start
    
    assert baseline == EXPECTED
    print({"mode": "baseline", "seconds": baseline_seconds, **baseline})
    

    The example deliberately uses no business sources, catalog names or permission changes. Its control total follows from the generated sequence. If an assertion fails, investigate the example and environment first; a timing comparison with different output is invalid.

    Our choice of one hundred thousand rows is a practical exercise value. It is not intended to stress serverless compute and establishes nothing about the performance of a production join.

    Result
    a baseline result, a simple timing measurement and explicit output checks, without creating or modifying a table.
  4. 04

    Cache one DataFrame and measure its complete lifecycle

    Construct a new DataFrame, cache it and run the same checks. On serverless compute, the cache call materializes the snapshot immediately. Include that phase in the total; timing only subsequent actions gives an incomplete comparison.

    Run this cell after the definitions in the previous step:

    prepared = build_prepared()
    start = perf_counter()
    
    try:
        prepared.cache()
        cache_seconds = perf_counter() - start
    
        actions_start = perf_counter()
        cached_result = summarize(prepared)
        actions_seconds = perf_counter() - actions_start
    
        assert cached_result == EXPECTED
    finally:
        cleanup_start = perf_counter()
        prepared.unpersist()
        cleanup_call_seconds = perf_counter() - cleanup_start
    
    total_seconds = perf_counter() - start
    
    print({
        "mode": "cached",
        "cache_seconds": cache_seconds,
        "actions_seconds": actions_seconds,
        "cleanup_call_seconds": cleanup_call_seconds,
        "total_seconds": total_seconds,
    })
    

    The finally clause makes cleanup explicit even when a check fails. The measurement around unpersist records the call duration, not the point at which all underlying storage has physically been deleted. Preserve that distinction in the measurement labels.

    Let exceptions fail visibly. Silently skipping a failed cache phase and reporting the remaining time as success would invalidate the experiment. This example demonstrates behavior and measurement design; it has not been run in your workspace.

    Performance impact
    compare the complete baseline with the complete cached variant. Individual phases explain where time goes but do not independently prove savings.
  5. 05

    Keep the reuse path visible in your code

    After caching, the cached DataFrame and DataFrames derived from it use the snapshot. An independently reconstructed query with identical logic does not automatically reuse it. The official cache reference documents that boundary.

    Make the boundary visible in the notebook structure. Name the prepared dataset clearly and pass it into consuming functions. A helper that rebuilds the source internally can look like the same computation while bypassing the intended reuse.

    In our example, summarize(prepared) is the intended route. summarize(build_prepared()) constructs a new DataFrame. Use the latter deliberately, for instance for the baseline or a fresh source read.

    Before the representative trial, sketch which steps derive from the cached result. Also identify steps that intentionally need a new source read. A reviewer can then assess whether the snapshot has the same meaning throughout the workflow.

    Pitfall
    identical query text does not establish identical cache usage. Inspect DataFrame derivation in the code rather than comparing only query strings.
  6. 06

    Include freshness and access in acceptance

    A fixed snapshot has implications beyond execution time. The Azure documentation states that subsequent source changes and changes to permissions, row filters or column masks do not get reapplied to an existing snapshot.

    Discuss two separate questions. May a user continue using a previously authorized result during the session? May an analysis continue with a snapshot that no longer represents the latest source state? The answers belong in the workload's governance agreement.

    For tests using actual tables, we recommend an isolated test catalog, a test identity and a pre-agreed change. Do not alter production permissions or real masks merely to demonstrate the behavior.

    TopicProposed test agreementDecision to record
    Source freshnessControlled source change outside the snapshotWhen to reconstruct from the source
    AccessTest identity with agreed changesHow cached sessions fit access revocation
    ConsumersNamed steps using the snapshotWho may interpret the output
    IncidentOwner and recovery route defined beforehandWhen to end the session

    Our recommendation is to put an explicit freshness requirement alongside the performance requirement. A faster analysis using inappropriate data does not satisfy acceptance.

    Decision
    have the data owner and platform owner review the lifecycle and access contract before introducing the approach into an existing production route.
  7. 07

    Clean up and reconstruct for the next phase

    On serverless compute, unpersist ends use of the relevant DataFrame and derived DataFrames dependent on that snapshot. Do not reuse those variables afterward. Construct a new source definition when you need to continue.

    In the exercise, start again after the cached cell with fresh = build_prepared(). Pass the new variable to subsequent operations. Prefer a visible phase boundary over reusing a variable name that may still refer to an invalidated result.

    Treat session duration as a design decision too. The snapshot is session-bound and has a maximum lifetime of seven days. That is not a retention period to build a process around. Our advice is to limit the session and cache to the actual analytical task.

    For results needed by another user or a later session, design a separate publication step to a managed table with appropriate permissions and retention. That is a different decision from temporarily optimizing one notebook.

    Best practice
    keep cache creation, consumption and cleanup close together in the code. Make object ownership and the final valid consumer visible.
  8. 08

    Repeat with a representative workload

    Use the synthetic exercise to remove mistakes in setup and lifecycle first. Then replace build_prepared() with an approved test version of the actual preparation. Bound the input and keep filters, outputs and execution route consistent between variants.

    A fair comparison alternates variant order and includes several runs. This reduces the chance of attributing favorable conditions to caching. Record unusual circumstances, such as concurrent work or a changing source.

    MeasurementWhy it belongs in the report
    Commit and notebook versionTraceable implementation
    Environment and clientReproducible starting conditions
    Dataset and filtersComparable input
    Total duration for each variantEvaluation of the complete execution
    Cache, action and cleanup phasesExplanation of differences
    Output assertionsCorrectness alongside speed
    Available usage recordsCost assessment with the same scope
    Owner and rollback pathResponsible operation after the trial

    Use the query profile where available to investigate execution. The serverless limitations explain that the classic Spark UI is unavailable. Do not translate a difference in seconds directly into a cost saving; assess the relevant usage records and measurement window too.

    Result
    an evidence-based go/no-go decision with measurements, valid output checks and an explicit path back to the uncached implementation.

Common mistakes

MistakeConsequenceBetter
Timing only actions after cachingCreation cost disappears from the comparisonMeasure the complete lifecycle
Reconstructing the query for every consumerIntended reuse is absentPass the cached DataFrame
Using unpersist as a refresh buttonLater code uses an invalid objectReconstruct from the source
Leaving freshness unspecifiedSnapshot does not fit the decisionDefine an explicit freshness requirement
Excluding access changes from evaluationThe access contract remains unclearReview sessions and revocation together
Publishing a small exercise as a benchmarkNo evidence for the real workloadMeasure representative work and report scope

What to do next

Include an accepted change in CI/CD for Azure Databricks. Check your governance foundation with setting up Unity Catalog. The snapshot boundary also appears in Known Limitations.

Official sources

Reviewed on 3 November 2026: Microsoft Learn: Azure DataFrame caching, serverless limitations, and the supplementary Databricks AWS reference. The synthetic code, measurement design and acceptance agreements are TechExplained guidance; no measured results for your environment are claimed.

The process at a glance

Click a step for its key decision

Decision

Choose a workload that reuses the same intermediate result

optimize one demonstrably reused intermediate result. Leave a simple, one-time read unchanged until measurement provides a specific reason to cache it.

Test DataFrame caching on Databricks serverless | TechExplained