Sub topic 14
Using the disk cache
This chapter covers the Databricks disk cache: what it stores, when it helps, how to turn it on and check it, and where it stops helping. It assumes you know basic SQL, can work in a Databricks workspace, understand Delta tables at a basic level, and know that Spark runs queries as stages and tasks. You should also know that Delta data lives in Parquet files in cloud object storage.
What the disk cache is
Every query that scans a Delta table reads Parquet files from cloud object storage such as S3, ADLS or GCS. Each read pays network latency and bandwidth. When many queries read the same files, that cost repeats.
The disk cache (also called the Delta cache or IO cache) keeps copies of remote data files on the local disks of the worker nodes. The first read of a file fetches it from object storage and writes a copy to the local NVMe or SSD disk. Later reads of the same file are served from that local copy.
Some details matter for how you reason about it:
- The cache stores file data, not query results. A different query that reads the same files and columns benefits too.
- It works at the level of file chunks and columns. The data is kept in a fast, decompressed-friendly format, so a cached read is quicker than reading Parquet from remote storage.
- Each worker caches the data its own tasks read. Spark's scheduler prefers to place a task on a node that already holds the file, which is called cache-aware scheduling.
- The cache is automatically invalidated when the underlying files change. Delta files are immutable, so an updated table writes new files, and the old cached copies are simply never read again.
Disk cache compared with Spark cache
The disk cache is a different thing from df.cache() or CACHE TABLE. Mixing them up is a common source of confusion.
| Property | Disk cache | Spark cache (`cache()`, `CACHE TABLE`) |
|---|---|---|
| Where data lives | Local disk of each worker | Executor memory, optionally spilled to disk |
| What is stored | Raw file data as read from storage | Computed DataFrame or table content |
| How you use it | Automatic once enabled | You call `cache()` or `CACHE TABLE` explicitly |
| Invalidation | Automatic when files change | You must unpersist or refresh |
| Memory pressure | Does not use executor memory | Competes with execution memory |
| Applies to | Parquet and Delta files read from remote storage | Any DataFrame, including results of transformations |
Because the disk cache sits on disk and holds raw file data, it does not shrink the memory available to your queries. That is one reason Databricks recommends it over df.cache() for repeated reads of table data.
How a cached read flows
The diagram shows what happens on a single task's read.
The first run of a query is therefore usually a cold run. It pays the object storage cost and fills the cache. Later runs are warm runs.
When it is enabled
Whether you need to do anything depends on the compute type.
- On many worker types with local NVMe or SSD storage, the disk cache is enabled by default. These include storage-optimized instance types (for example the AWS
i3andi4ifamilies and comparable types on other clouds). - On SQL warehouses, caching is managed for you.
- On other node types you can enable it with a Spark configuration setting. The cache is only useful on nodes that have enough local disk, so choose node types with fast local storage.
You can set it in a notebook for a session, or in the cluster's Spark configuration so it applies to the whole cluster:
SET spark.databricks.io.cache.enabled = true;The same setting in the cluster Spark config is a plain key-value line:
spark.databricks.io.cache.enabled trueThe cache size is controlled by further settings that are normally left at their defaults. When you do set them, you choose how much of each worker's local disk the cache may use, so that Spark shuffle spill and temporary files still have room. Check the Databricks documentation for the exact property names and defaults on your runtime, because they differ across versions and node types.
Checking that the cache is working
Do not assume the cache helps. Verify it with the Spark UI or the Query Profile.
- Run the query once and note the time. This is the cold run.
- Run the identical query again and note the time. This is the warm run.
- Open the query in the Query Profile (for SQL) or the Spark UI (for notebooks and jobs) and look at the scan operator metrics.
- Compare the amount of data read from cache with the amount read from remote storage. A warm run that still reads almost everything from remote storage means the cache is not being used or the data does not fit.
In the Spark UI, the Storage tab covers the Spark cache, not the disk cache. For the disk cache, look at the cache-related metrics in the scan details of the SQL query page and in the Query Profile. Metric names vary by runtime version, so look for entries that report cache hits, bytes read from cache and bytes read from remote storage.
Preloading the cache
By default the cache fills lazily as queries read data. If you know a table will be queried heavily, you can warm the cache ahead of time with a CACHE SELECT statement:
CACHE SELECT order_id, customer_id, amount
FROM orders
WHERE order_date >= '2024-01-01';This reads the selected columns and rows' files and stores them in the disk cache. Note the following:
- Only the columns you list are cached. Selecting
*is possible but fills the cache faster and may evict useful data. - The
WHEREclause chooses which files are cached, using the same data skipping that a normal query uses. A tight filter caches fewer files. - The statement is useful before a dashboard refresh, a benchmark or a demo, where you want predictable warm performance.
Eviction and size limits
The cache has a fixed size. When it fills, the least recently used data is evicted to make room. This has practical consequences:
- If your working set is larger than the cache, queries keep evicting each other's data. You get a low hit rate, and the cache adds writing overhead without much benefit.
- A table scanned once and never again gains nothing. A full-table scan of a very large table can push out useful data.
- The cache is per cluster. When a cluster terminates, its cache disappears. A new cluster starts cold.
- When a cluster autoscales, new workers start with empty caches. Work can land on a cold node until it fills.
- If a worker is lost, the data it cached is lost with it.
Good layout makes the cache more effective. If OPTIMIZE and data skipping mean a query touches fewer files, then fewer bytes need caching, and the same cache holds more useful data. Layout work and caching complement each other.
Common mistakes
- Benchmarking only a cold run. The first run mixes your change with cache fill time. Compare cold with cold and warm with warm, as the benchmarking chapter explains.
- Expecting a speedup on compute-bound queries. If most of the time goes to a shuffle or a UDF, reads are not the bottleneck.
- Using
df.cache()for table reads. It uses executor memory and needs manual management. For plain repeated table reads, prefer the disk cache. - Choosing nodes with small or slow disks. The cache needs fast local storage. Without it, a cache read may be no faster than object storage.
- Forgetting the cache is lost on restart. Short-lived job clusters rarely benefit, because each run starts cold. Interactive clusters and warehouses that stay up between queries benefit most.
Disk cache and Photon
The disk cache and Photon address different costs. The cache reduces time spent fetching bytes. Photon reduces time spent processing them. They combine well: a warm scan feeds Photon's vectorized operators quickly, so a query that is CPU-bound after a cache hit is where Photon's gain shows most clearly. If you test Photon on a cold run and compare it with a warm run on standard Spark, the comparison is unfair, so keep the cache state the same in both.
Exercise
A team runs the same dashboard query three times on a new job cluster. The first run takes 90 seconds. The second and third take 30 seconds. They then schedule the query as a nightly job that starts a fresh cluster each night, and it always takes about 90 seconds. Explain why, and name two changes that could help.
Show answer
The faster second and third runs were warm runs that read files from the workers' local disk cache. A fresh cluster each night has an empty cache, so every nightly run is a cold run that fetches data from object storage. Possible changes: run the query on a longer-lived cluster or SQL warehouse so the cache survives between runs, or preload the needed columns with CACHE SELECT at the start of the job (accepting that this fill costs about the same as one cold run). Reducing the data read through OPTIMIZE, clustering or data skipping would also shorten the cold run.
Exercise
You enable the disk cache and run a query twice, but the second run takes the same time as the first. The scan metrics show almost all bytes read from remote storage on both runs. Give two likely causes.
Show answer
The data being scanned may be larger than the cache, so files are evicted before the second run reads them. Or the nodes may have small or slow local disks, or the cache may not be enabled on that compute type. A third possibility is that the query is not read-bound, though the metrics point first to the cache not holding the data.