# Caching Techniques for the Data Lake

*By Shai Ben-Yehuda · Nov 2026*

☕ Ten techniques that move data closer to the CPU: from the bucket to the local SSD, to RAM, and into the CPU's own caches.

> **We care about speedup, not about cache hits.**
>
> And a real speedup is not easy to get.

![Where each technique moves data, from far and slow (left) to near and fast (right)](https://multitrail.com/blog/datalake-caching-techniques/assets/caching-moves.svg)

---

## Part I — From the Bucket to the Machine


# 1. Bucket → SSD Cache (Virtual File System)

**Move:** object store → local SSD

Keep a local SSD copy of each Parquet range read from the bucket. Later reads hit the SSD.

```text
without cache   query 1 → bucket   query 2 → bucket   query 3 → bucket
with SSD cache  query 1 → bucket → SSD   query 2 → SSD   query 3 → SSD
```

## How It's Built

| Form | Example |
|---|---|
| File system that mounts the bucket | Mountpoint for S3: `mount-s3 --cache /nvme/cache coffee-lake /mnt/lake` |
| Cache in the engine's file layer | Trino: `fs.cache.enabled=true`; Presto: Alluxio SDK cache |
| Managed | Databricks disk cache, on by default for workers with local SSD |

## When It Pays

The cache removes only the time spent **waiting for the bucket**. It does nothing for the time spent **computing**.

- A dashboard tile on denormalized data (no joins) spends almost all its time waiting for the bucket. The cache made it ≈20× faster.
- A TPC-DS query spends most of its time on joins and aggregations. The same kind of cache gave only 10–30%.

So a CPU-intensive query gains little, however good the cache is. The cache pays only when:

- the same data is read again, and fits on the SSD, and
- most of the query's time is waiting for the bucket, not joining or aggregating.

If the bucket is already fast for the workload (large parallel scans), the gain is small too (Trino docs).

## Evidence

| Source | Workload | Gain |
|---|---|---|
| Alluxio / Uber / Meta (USENIX ATC 2024), Presto local SSD cache | TPC-DS Q81–Q99, warm cache vs S3 | 10–30% |
| Same paper, Meta production | interactive Presto | P95 latency −49% |
| Presto + Alluxio blog (2020) | remote scans | 57% better I/O |
| Databricks cache blog (2018) | selected TPC-DS queries vs Parquet on S3 | up to 5.7× (Q53), "up to 10×" interactive |
| Our faster-parquet-cache paper | dashboard page, **denormalized** data, 300 MB | ≈10 s → ≈0.5 s (≈20×) |

To report a fair speedup, compare cold vs cached on the same data model.

Two side benefits, even when a typical query is not much faster:

- **The slowest queries get faster.** Slow or throttled bucket requests are the main cause of slow outliers, and a cache hit avoids them. At Meta, the slowest 5% of queries (P95) got 49% faster.
- **The bucket bill drops.** Every cache hit is one less paid GET request to the bucket.

## HTTP vs Local Read

Why is the gain 20× for one query and 30% for another? Every request to the bucket pays a fixed network delay, while a local read costs almost nothing. A Parquet query makes many small requests, so it pays that delay many times; a big parallel scan pays it once and hides it.

| | S3 over HTTP | Local SSD |
|---|---|---|
| Per request | tens of ms to ≈200 ms (AWS: 100–200 ms) | ≈0.1 ms (page cache ≈1 µs) |
| Bandwidth | ≈85–90 MB/s per connection; ≈15 connections fill 10 Gb/s | GB/s per drive |
| Per-request fee | yes | no |

A Parquet query reads the footer plus one range per column chunk, e.g. 1 file × 5 columns × 4 row groups = 21 requests:

| | S3 over HTTP | Local SSD |
|---|---|---|
| 21 requests, one by one | ≈2 s | ≈2 ms |
| 21 requests, in parallel | ≈0.1–0.2 s | ≈0.1 ms |
| 10 GB sequential scan | ≈8 s at 10 Gb/s | ≈2–3 s |

Small reads: 100–1000× gap. Big scans: 2–5×.

- **FUSE (Mountpoint):** any tool works unchanged; a few µs extra per read.
- **In-engine cache (Trino, Presto):** no FUSE hop.
- **S3 Express One Zone:** single-digit ms, up to 10× faster than S3 Standard; still a network hop, higher storage cost.

## Alluxio

The cache library behind several results above: a local cache inside each Presto worker (and Trino's file system cache since Trino 439), or a separate shared cluster. The local cache needs soft affinity (section 3). Uber checks each file's modification time before using a cached copy, because Hudi tables are updated constantly.

## Pitfalls

- **Freshness:** immutable files (Delta, Iceberg) are safe; mutable files need invalidation.
- **Security:** the cache is a plain local copy (Mountpoint: unencrypted). Restrict the directory.
- **Cold start:** the first read pays full price.
- **Many nodes:** without affinity, hit rate ≈ 1/N (section 3).
- **Decompression:** raw bytes are decompressed on every hit (section 2).

## Who Does It

Mountpoint for Amazon S3, Trino file system cache, Presto + Alluxio SDK cache, Alluxio cluster, Databricks disk cache, Apache Doris file cache.

---

# 2. Cache Decompressed Parquet

**Move:** no layer change; the data stays on local SSD, but each hit skips **decompression and decoding** (CPU)

**In one sentence:** when filling the SSD cache, store the columns in a format that's cheap to read (no Snappy/Zstd, light or no encoding), instead of the raw Parquet bytes, so a cache hit doesn't spend its time decompressing.

## Why it's needed

Section 1 removes the download. What's left on a hit:

```text
query time = fetch + decompress + decode + compute

no cache:          fetch + decompress + decode + compute     → waiting on the bucket
raw-bytes cache:   (no fetch) + decompress + decode + compute  → now CPU-bound on decoding
decoded cache:     (no fetch) + (no decompress) + light decode + compute
```

Over HTTP, decompression is hidden behind the download. On a fast SSD it's exposed, and it becomes the bottleneck. A raw-bytes cache turns a bucket-bound query into a **CPU-bound** one, and its gain stops growing. That's one reason the Alluxio local cache (raw bytes) shows 10–30% on TPC-DS, while the Databricks cache (transcoded) reports up to 10×.

## Example

A do-it-yourself version with DuckDB: when a file enters the cache, rewrite it once without general-purpose compression. Parquet's lightweight encodings (dictionary, RLE, bit-packing) stay, so the file stays compact:

```sql
COPY (SELECT * FROM read_parquet('/mnt/lake/sales/date=2026-11-29/part-0.parquet'))
TO '/nvme/cache/sales/date=2026-11-29/part-0.parquet'
(FORMAT parquet, COMPRESSION uncompressed);
```

```text
                      raw Parquet + Zstd     uncompressed, still encoded
size on SSD           25 MB                  34 MB   (sizes from Zeng et al.)
per hit               read + unzstd + decode read + light decode
```

## Evidence

- **On NVMe, decoding dominates.** Zeng et al. (VLDB 2024) scanned the same Parquet table from storage tiers of increasing speed: Zstd only speeds up scans on slow storage, where I/O dominates. On NVMe SSDs, I/O time is negligible compared with computation, so decompression becomes the bottleneck. Their recommendation: formats should not apply general-purpose block compression (Snappy, Zstd) by default, because the bandwidth savings don't justify the decompression cost.
- **Decompression makes scans CPU-bound.** BtrBlocks (SIGMOD 2023) makes the same point for data lakes, and replaces heavy compression with lightweight encodings that decompress much faster.
- **Databricks transcodes on purpose.** Its disk cache doesn't store the raw input bytes; it transcodes them into an optimized on-disk format. Their reason: on i3 SSDs, common file formats used only a fraction of the SSD's bandwidth because "the CPU-intensive decoding is simply too slow to keep up with the fast SSDs." With the faster-decoding format they report up to 10× faster scans, up to 5.7× on TPC-DS Q53 vs Parquet on S3, and 4× faster reads than Spark's disk cache.
- **Decoding, not filtering, is the cost.** LiquidCache (VLDB 2025) found that in filter pushdown on ClickBench Q22, decoding and decompression take over 90% of the time. It transcodes Parquet into a lightweight cache-only format and cuts cache CPU time by up to 10×.

## The options, from least to most work at cache-fill time

| Cache stores | Hit cost | Size on SSD | Who |
|---|---|---|---|
| Raw Parquet bytes (compressed + encoded) | decompress + decode every time | smallest | Alluxio local cache, Trino file system cache, Mountpoint |
| Decompressed, still encoded (dictionary, RLE, bit-packed) | light decode only; filters can run on encoded data | medium (34 MB vs 25 MB with Zstd in Zeng et al.) | the sweet spot, in our view |
| Fully decoded (e.g. Arrow) | almost none | largest | in-memory caches |
| Transcoded to a fast-decoding format | small, SIMD-friendly | similar to compressed | Databricks disk cache, LiquidCache, BtrBlocks/FastLanes-style formats |

## Statistic it needs

- **Decode share of a cache hit:** decompress + decode time ÷ total query time, on queries already served from the SSD. High share → big gain.
- **Size growth:** compressed vs decoded size of the hot columns, against the SSD capacity.
- **Re-read count:** transcoding costs CPU once per file; it has to be read enough times to pay that back.

## When it gives ×10

When, after section 1, decoding is most of the remaining time, as in LiquidCache's >90% case, and the decoded data still fits the cache. The same Amdahl logic applies: removing a 90% share gives up to 10×. Combined with section 1, it removes both the waiting and the decoding, which leaves only the query's real compute.

## Pitfalls

- **Bigger cached data means fewer hits.** Dropping Zstd grows the data (≈1.4× in the Zeng example), so less of the hot data fits and *h* drops. Lightweight encodings keep most of the size savings without the CPU cost.
- **Transcoding costs CPU at fill time.** Do it asynchronously (Databricks does), so the query that fills the cache isn't slowed down.
- **It only pays off on fast local storage.** If reads still go to the bucket, decoding is hidden behind the download.
- **Engine support:** a custom cache format must be readable by the engine. Uncompressed Parquet works everywhere; a custom format needs a reader.

## Who does it

Databricks disk cache (transcoded format); LiquidCache (DataFusion); research formats built for fast decoding (BtrBlocks, FastLanes). Technique 22 in `10x-techniques.md` (data files prepared for SIMD) is the same idea applied to the files themselves.

---


# 3. Cache Affinity Routing

**Move:** object store → local SSD, but **hitting** (it raises *h* for section 1)

**In one sentence:** always send the work for the same file chunk to the same node, so that node's cache actually gets hits.

## Example

Four workers, and the daily sales file has 8 row groups:

```text
without affinity (any free worker)        with affinity (hash(file, row group) % 4)
query 1: rg0→w2 rg1→w0 rg2→w3 ...           rg0,rg4 → w0
query 2: rg0→w1 rg1→w3 rg2→w0 ...           rg1,rg5 → w1
         (rg0 was cached on w2, so miss)    rg2,rg6 → w2
                                            rg3,rg7 → w3   (every query, same mapping)
```

## Why it matters

Without affinity, a chunk cached on one node is needed by a random node next time. With N nodes, the hit rate is roughly **1/N**: 25% with 4 nodes, 1% with 100. With affinity, each chunk has one home, the hit rate approaches 100% after warm-up, and the cluster acts like **one big cache holding one copy of each chunk**.

Use **consistent hashing**, not `hash % N`: when a node is added or removed, only about 1/N of the chunks move instead of almost all of them.

## Statistic it needs

- The chunk key (file path + row group, or a split ID) and the node list.
- Load per node: if the preferred node is busy, fall back to another node ("soft" affinity).

## When it gives ×10

It doesn't speed up a single read; it **turns section 1's misses into hits**. It moves the hit share *h* from 1/N toward 1, which is exactly the range where the speedup takes off.

## Pitfalls

- **Hot chunks** overload their home node. Soft affinity (fall back when busy) or a second preferred node fixes this.
- **Autoscaling** reshuffles homes. Consistent hashing limits the damage.

## Who does it

Snowflake assigns table files to worker nodes by consistent hashing, so each file is cached in one place. Presto has soft affinity scheduling (`hive.node-selection-strategy=SOFT_AFFINITY`), used with the Alluxio local cache at Uber. Trino's file system cache prefers the same nodes for the same splits. The "hot lambda /tmp" design in our faster-parquet-cache paper relies on the same idea.

---

# 4. Browser Cache + WASM Engine

**Move:** object store → the browser's file system (OPFS) on the user's own device; read sequentially into the engine's memory

**In one sentence:** run the query engine in the browser (e.g. DuckDB-WASM), fetch only the needed column chunks once, store them in the browser's private file system (OPFS), and answer every follow-up query locally, even after the tab is closed and reopened.

## Example

A store manager opens the dashboard, then keeps clicking filters:

```sql
-- runs inside the browser, DuckDB-WASM
SELECT flavor, SUM(quantity) AS cups
FROM 'https://lake.example.com/sales/date=2026-11-29/part-0.parquet'
WHERE store_id = 17
GROUP BY flavor;
```

```text
click 1:  browser ──HTTP range reads──▶ bucket   (columns: store_id, flavor, quantity)
click 2:  browser ── cached chunks ──▶ local scan (only new columns are fetched)
click 3+: no network at all
```

## Where the chunks live

```text
OPFS (browser file system)   persistent: survives the closed tab and a new worker
worker memory (WASM heap)    fast, but only until the tab or worker goes away
```

OPFS, the Origin Private File System, is the browser's own private file system: one file per Parquet object, plus a map of which byte ranges are cached. It is the browser's version of the local SSD in section 1. Chunks are copied from OPFS into the worker's memory when a query runs; a fresh worker that finds its pages in OPFS makes zero network calls.

DuckDB reads synchronously but the browser fetches asynchronously, so the engine runs in a Web Worker and **plans before it scans**: read the footer, list the column chunks the query needs, fetch the missing ones in parallel into OPFS, then scan. Our faster-parquet-cache paper describes this design.

## Statistic it needs

- **Per-user working set size:** one store's day is MBs, which fits. The whole network's year doesn't.
- **Re-query rate:** interactive exploration (filters, drill-downs) re-reads the same chunks many times.
- **The user's connection and device:** network speed and latency to the server, and the laptop's CPU and disk. A slow connection plus a fast laptop is the best case.

## When it gives ×10

The jump is the largest on the map: from a network round trip plus a server queue to a local file read on the user's own device. If most clicks re-use cached chunks (high *h*), each click becomes milliseconds instead of a server round trip. And server cost drops, because the user's CPU does the work.

**Best case: slow internet, fast laptop.** Both sides of the gap work in its favor:

- **A slow or far connection makes every server round trip expensive.** On a home or mobile connection, each click that goes to the server pays the latency (often 50–200 ms or more) plus queueing on the server. With the chunks in OPFS, follow-up clicks don't touch the network at all, so the slower the connection, the bigger the gain per click (*r* grows).
- **A fast laptop makes the local scan cheap.** Modern laptops have many cores and fast NVMe disks, often faster than the share of a shared server one user gets. Scanning a few MB of cached columns locally takes milliseconds.

```text
                         per click, server-side query        per click, browser + OPFS
fast office network      ~100 ms round trip + server time    a few ms locally
slow / mobile network    ~300 ms+ round trip + server time   a few ms locally   ← gap grows
```

**The catch is the first load.** The browser downloads column chunks (MBs), while a server-side query would return only a small result (KBs). On a slow connection that first download takes longer. It pays off after a few clicks on the same data:

```text
pays off when:  (clicks on the same data) × (round trip per click)  >  first download time
```

Prefetching the likely chunks before the user clicks (plan-then-scan, above) hides most of it.

## Pitfalls

- **Data size and device limits:** OPFS storage quotas (set per site by the browser), worker memory, slow phones.
- **Freshness:** the browser copy goes stale; use file versions (immutable files) or short time-to-live.

## Who does it

DuckDB-WASM; hybrid execution that splits a query between the browser and the cloud (e.g. MotherDuck). Our faster-parquet-cache paper uses the browser as a cache holder.

---

## Part II — Inside the Machine

Once the data is on the machine, the bottleneck moves to memory.

![The memory ladder, and the two rules that decide speed: small is fast, in order is fast](https://multitrail.com/blog/datalake-caching-techniques/assets/cpu-memory.svg)

# 5. Skew-Aware Hot/Cold Join

**Moves:** hot keys: SSD random → RAM · cold keys: SSD random → SSD sequential

**In one sentence:** when the lookup side of a join is too big for memory, keep the keys that are probed most often in RAM, and handle the rest in one sequential pass on disk.

![Hot/cold join on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-5.svg)

## Example

```sql
SELECT c.tier, SUM(s.quantity * s.unit_price) AS revenue
FROM sales s
JOIN customers c ON c.customer_id = s.customer_id
GROUP BY c.tier;
```

`customers` has 100M rows, too big for the join's memory budget. But purchases are skewed: a small group of regular customers makes most of the sales.

```text
probe distribution (Zipf-like)        what goes where
customer 42   ███████████████         top 10% of customers → hash table in RAM
customer 7    ██████████              (answers ~89% of probes under Zipf 1.0)
customer 913  ███████
...
customer X    ▏  (long tail)          remaining 90% → sorted on SSD
```

## How it works

1. Before the join, read the **most common values (MCV)** of `sales.customer_id`, from stored statistics or a sketch built from the first batches.
2. Build a small, **packed** hash table with only those customers. Choose how many by size: stop when the table fills the per-core L2 (≈1–2 MB), or when the next customers add little coverage.
3. Probe each sale: a hit is answered immediately; a miss goes into a buffer.
4. Sort or partition the buffered misses by key, then do **one sequential pass** over the cold customers on SSD.

Step 4 is what makes the cold part cheap: thousands of random SSD reads become one sequential read.

**What stays in cache.** The hot table is in RAM on paper, but it is small and probed all the time, so the hardware keeps it in L2/L3. Two things protect that:

- **Pack the hot keys together.** In the full table each hot key shares its 64-byte line with cold keys; packed, the same hot set needs several times fewer lines.
- **Stream `sales` past it.** Read the one-pass rows with streaming hints (non-temporal loads), so they don't evict the hot table.

## Statistic it needs

Frequencies of the probe-side keys (MCV list), not of the lookup side. What matters is which customers *buy* often, not which customers exist. The same list gives the coverage curve (probes answered vs. number of hot keys), which sizes the hot table to L2.

## When it gives ×10

When the hot share is high (≥90%) and the baseline does random disk reads or spills everything. Against a good baseline that already spills sequentially (grace hash join), the gain is smaller, because the gap between layers is smaller.

## Pitfalls

- **No skew, no gain:** with uniform probes, 10% of keys in RAM answers only 10% of probes.
- **A hot key with many matching rows** on the lookup side may not fit in "hot" either.
- **Stale statistics:** yesterday's hot customers may not be today's. A runtime sketch avoids this.

## Who does it

PostgreSQL (a small skew hash table built from MCV statistics, Histojoin); Snowflake (detects frequent probe keys at runtime with a sketch). Research: NOCAP (2023) sizes the hot part adaptively.

---

# 6. Sorted Probes

**Move:** RAM random → RAM sequential

**In one sentence:** when both tables are sorted by the join key, keep one cursor in each and move both forward: every match is the next row, never a jump, so both tables are read in order.

![Sorted probes on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-6.svg)

## Example

Joining `sales` to `customers` on `customer_id`, both sorted by `customer_id`:

```text
sales.customer_id       1001   1001   1004   1007   1007   ...
                          ▲ cursor A moves forward →

customers.customer_id   1001   1002   1003   1004   1005   1006   1007   ...
                          ▲ cursor B moves forward →

A = 1001 → B stays at 1001        match
A = 1001 → B stays at 1001        match
A = 1004 → B steps to 1004        match
A = 1007 → B steps to 1007        match
```

Neither cursor ever goes back. Unsorted, each `sales` row jumps to a random place in `customers` and waits ≈100 ns for RAM.

**Why it's fast.** The data stays in RAM, but the hardware prefetcher sees the forward pattern and loads the next lines into L2/L3 before the cursors reach them. Read in batches small enough to fit in L2, so prefetched lines are still there when they are used.

## Statistic it needs

A **sorted** flag on both sides (Parquet/Delta/Iceberg can record sort order), or clustering on the join key. Row width of the needed columns sets the batch size: rows per batch × bytes per row ≤ L2.

## When it gives ×10

It doesn't move data to a faster layer; it changes the **access pattern**: random lookups pay one RAM miss each, two forward cursors run at memory bandwidth, and no hash table is built at all. Our estimate: ≈5× or more on a big lookup table.

## Pitfalls

- A table can only be sorted one way: sorted by `customer_id` helps this join, not a join on `product_id`.
- New appends arrive unsorted until the table is re-clustered.

## Who does it

ClickHouse (sort-merge joins that use the table's primary-key order); any engine with merge join, when the input is already sorted.

---

# 7. Dense Array Instead of a Hash Table

**Move:** RAM random (hash table) → CPU cache, **only if the key range is small**

**In one sentence:** if keys are dense integers (min/max close to the count), store values in a plain array indexed by `key − min`. No hashing, no key comparisons, and a much smaller structure.

![Dense array on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-7.svg)

![Hash table vs dense array, one lookup](https://multitrail.com/blog/datalake-caching-techniques/assets/dense-array.svg)

## Example

```sql
SELECT p.category, SUM(s.quantity) AS cups
FROM sales s
JOIN products p ON p.product_id = s.product_id
GROUP BY p.category;
```

Statistics for `products.product_id`: min = 1, max = 5,000, count = 5,000. Dense.

## What the CPU sees

**Build:** read only `product_id` and `category` from `products` (from the SSD cache), and fill one array. With 50 categories, each value is a 1-byte dictionary code:

```c
uint8_t cat[5000];                       // 5 KB: the key is the position, only the value is stored
memset(cat, NO_MATCH, sizeof cat);       // e.g. 255 = "no such product"
for (i = 0; i < n_products; i++)
    cat[product_id[i] - 1] = category_code[i];
```

**Probe:** stream `sales` in batches (e.g. 2,048 rows), with just the two needed columns decoded:

```c
uint64_t cups[50] = {0};                 // the result: 400 bytes
for (i = 0; i < 2048; i++) {
    uint8_t c = cat[pid[i] - 1];         // the join: one load, an L1 hit
    cups[c] += qty[i];                   // the GROUP BY: another L1 hit
}
```

Per row: one subtraction and one load for the join, one add for the aggregation. No hash, no key compare, no branches. The join and the GROUP BY become one loop.

```text
L1 cache (~32–48 KB)
 ├─ cat[]          5 KB    stays for the whole query (the lookup)
 ├─ cups[]         0.4 KB  stays (the result)
 └─ current batch  16 KB   streamed in, used once, replaced by the next batch
RAM / SSD cache
 └─ the rest of sales, read sequentially; the prefetcher loads it ahead
```

All the *random* accesses (`cat[...]`) hit L1; the only memory traffic is the *sequential* stream of `sales`. With SIMD, a gather instruction (e.g. AVX2 `vpgatherdd`) looks up 8 keys at once. The `cups[c] +=` step is harder to vectorize, because two rows in one vector can share a category; engines keep it scalar or give each thread its own `cups[]` and add them at the end.

## Statistic it needs

min, max, and count (or distinct count) of the key. Dense when `max − min + 1 ≈ count`.

## How much it gives

Not ×10 per lookup. We measured up to **4.5×**, when the hash table has left L2 (≈128K–1M keys) and the array has not. For our 5,000 products both fit in cache: 1.5×. With a very big key range, both end in RAM and the gap closes.

The gain is smaller than the L1-vs-RAM gap (≈100×) because the lookups in a join loop don't depend on each other: the CPU runs many RAM reads at once and hides most of the wait.

![Measured: dense array vs hash table](https://multitrail.com/blog/datalake-caching-techniques/assets/dense-array-chart.svg)

## Pitfalls

- Sparse keys (e.g. IDs with big gaps) waste space; a perfect hash function is the general version.
- ClickHouse-style specialization by **declared type** (8- or 16-bit keys use a 256- or 65,536-slot array) misses cases where values are small but the type is wide; using min/max catches them.

## Who does it

DuckDB (perfect hash aggregation, statistics propagation); ClickHouse (array lookup for 8/16-bit keys). Research on perfect hashing in DuckDB: 1.7× on joins, 3.1× on aggregations end-to-end.

---

# 8. Cache-Sized Lookup Tables

**Move:** RAM random → CPU cache

**In one sentence:** when a dimension table is small, build its lookup structure compactly enough that it lives in the CPU cache for the whole query.

![Cache-sized lookups on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-8.svg)

## Example

Joining `sales` to `stores` to sum revenue by region: `stores` has 300 rows. Its lookup (`store_id → region`) is a few KB. Every one of the billions of `sales` probes hits L1/L2 cache (≈1–4 ns) instead of RAM (≈100 ns).

## Statistic it needs

Row count and row width of the lookup side, so the engine can pick the smallest representation (only the needed columns, narrow types, dictionary codes for `region`).

## How much it gives

Up to **≈3×** per lookup, and only in a middle range (≈32K–256K rows), where wide entries have left L2 and compact ones have not. A 300-row dimension is in L1 either way. A star schema with small dimensions is already fast; compact entries keep a medium dimension fast too.

![Measured: compact vs wide entries](https://multitrail.com/blog/datalake-caching-techniques/assets/lookup-size-chart.svg)

## Pitfalls

- Carrying unneeded columns or wide strings can push the structure out of cache. Project early, encode strings.
- Many small lookups in one query compete for the same cache.

## Who does it

Most engines, implicitly (broadcast hash joins with small build sides). Few size the structure deliberately for the cache.

---

# 9. Sketches Instead of Exact Sets

**Move:** RAM random (or SSD, if spilled) → CPU cache

**In one sentence:** replace a huge exact set (for `COUNT(DISTINCT)` or percentiles) with a tiny summary that fits in cache, accepting a small, known error.

![Sketches on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-9.svg)

## Example

```sql
-- exact: a set of every distinct customer, per day (millions of entries)
SELECT DATE(ts) AS day, COUNT(DISTINCT customer_id) AS customers
FROM sales GROUP BY 1;

-- approximate: one small HyperLogLog sketch per day
SELECT DATE(ts) AS day, approx_count_distinct(customer_id) AS customers
FROM sales GROUP BY 1;
```

Sketches also **merge**: each node builds its own and sends a few KB instead of shuffling millions of IDs.

## Statistic it needs

The error tolerance (from the user or the dashboard), and the expected cardinality (high cardinality is where sketches win).

## When it gives ×10

High-cardinality distinct counts and percentiles, where the exact structure would sit in RAM or spill. The structure shrinks by orders of magnitude and drops to the fastest layer.

![Measured: exact set vs HyperLogLog](https://multitrail.com/blog/datalake-caching-techniques/assets/sketch-chart.svg)

## Pitfalls

- Answers are approximate. Fine for dashboards, not for billing.
- Some engines don't use sketches unless the query asks explicitly (`approx_count_distinct`).

## Who does it

`approx_count_distinct` and approximate percentiles in Spark, Trino, Snowflake and BigQuery; Druid sketches.

---

# 10. Squeeze and Split the Master Data

**Move:** RAM → L3 / L2 / L1, by making each piece of the lookup small enough

**In one sentence:** encode the master data (dimension tables) as tightly as its statistics allow, then split it by key range until each piece fits a core's L2 or a machine's L3.

![Squeeze and split on the memory ladder](https://multitrail.com/blog/datalake-caching-techniques/assets/ladder-10.svg)

## Example

```sql
SELECT c.tier, SUM(s.quantity * s.unit_price) AS revenue
FROM sales s
JOIN customers c ON c.customer_id = s.customer_id
GROUP BY c.tier;
```

`customers` has 16M rows; `tier` has 4 values; purchases are skewed.

## Squeeze

Each step is driven by a statistic:

| Step | Statistic | Effect |
|---|---|---|
| Keep only the columns the join reads | the query | drops wide rows |
| Dictionary-encode strings | distinct count | `'platinum'` → a 1-byte code |
| Renumber keys to 0…N−1 (in ETL) | min, max, count | the key disappears into the array position (section 7) |
| Bit-pack the values | distinct count | 4 tiers → 2 bits |
| Renumber by probe frequency | MCV list (section 5) | hot customers get the lowest IDs, so the hot set is a small prefix of the array |

![Measured: squeezing 16M customers](https://multitrail.com/blog/datalake-caching-techniques/assets/squeeze-chart.svg)

From 1 GB to 4 MB, and from 15.8 ns to 2.6 ns per lookup: **≈6×**. The two biggest steps are dropping the key (hash table → dense array) and the bits.

## Split

If the squeezed data still doesn't fit, split it by key range:

1. **Across machines:** each machine gets a range that fits about half its L3 (the other half is for the stream).
2. **Across cores:** inside a machine, each core gets a range that fits its L2.
3. **Hot keys:** copy the small hot set to every machine (broadcast), and split only the cold keys. Otherwise one piece gets most of the probes.

Ranges keep each piece dense, so every core can still use a dense array.

![Measured: splitting a 32 MB lookup](https://multitrail.com/blog/datalake-caching-techniques/assets/split-chart.svg)

Probing a piece that fits L2 is **≈3.6×** faster than probing one big table (9.5 → 2.6 ns). But moving the probe rows to their piece costs about as much as it saves: on one core, partition + probe is no faster than one table.

So the split pays only when the rows are **already** in the right place:

- the table is stored split by the join key (bucketed / partitioned on `customer_id`), or
- the plan shuffles by this key anyway (a distributed join), so the split costs nothing extra.

## Statistic it needs

Row count × squeezed row width (how many pieces), min/max of the key (dense ranges), the probe-side MCV list (hot keys to renumber or broadcast), and how the data is stored (is the split free?).

## Pitfalls

- Renumbering keys is an ETL change: every table that references the key must use the new IDs.
- Hot keys change over time; renumbering by frequency must be redone, or kept to a stable hot set.
- Cache sizes differ between machines; size pieces from the actual hardware, and leave room for the stream.

## Who does it

Pieces of it everywhere: dictionary encoding and bit-packing in every columnar format; radix-partitioned hash joins in research engines (and DuckDB's partitioned hash join); bucketed tables in Hive, Spark and Iceberg, which make the split free. Few engines pick the split *size* from the cache size.

---

## Part III — Summary

| # | Technique | Move | Statistic needed | Pays when |
|---|---|---|---|---|
| 1 | Bucket → SSD cache (VFS) | object store → SSD | data re-read repeatedly + queries not CPU-bound | re-read, I/O-bound queries (dashboards) |
| 2 | Cache decompressed Parquet | same SSD, removes decompress + decode | decode share of hit time, size growth, re-read count | decoding dominates after the download is gone |
| 3 | Cache affinity routing | makes section 1 hit | chunk key, node list, load | many nodes; raises hit rate from 1/N toward 1 |
| 4 | Browser + WASM (OPFS) | object store → browser file system (OPFS) | per-user working set, re-query rate | interactive exploration of small per-user data |
| 5 | Skew-aware hot/cold join | SSD random → RAM / SSD sequential | probe-side most common values | ≥90% of probes are hot |
| 6 | Sorted probes | RAM random → RAM sequential | sort order / clustering | both sides sorted on the join key |
| 7 | Dense array instead of hash | RAM random → CPU cache (if small) | min, max, count | dense key range, ≈128K–1M keys (up to 4.5×) |
| 8 | Cache-sized lookups | RAM random → CPU cache | row count, row width | medium dimensions, ≈32K–256K rows (up to 3×) |
| 9 | Sketches (HLL) | RAM / SSD → CPU cache | error tolerance, cardinality | high-cardinality distinct counts, approximation OK |
| 10 | Squeeze and split | RAM → L3 / L2 / L1 | distinct counts, min/max, MCV, storage layout | big dimensions; split only when already partitioned (≈6× squeeze, ≈3.6× split) |

# References

- Mountpoint for Amazon S3, caching — https://docs.aws.amazon.com/AmazonS3/latest/userguide/mountpoint-usage.html
- Trino file system cache — https://trino.io/docs/current/object-storage/file-system-cache.html
- AWS, Best practices design patterns: optimizing Amazon S3 performance — https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html
- AWS, Horizontal scaling and request parallelization for high throughput — https://docs.aws.amazon.com/whitepapers/latest/s3-optimizing-performance-best-practices/horizontal-scaling-and-request-parallelization-for-high-throughput.html
- Amazon S3 Express One Zone price reductions (Apr 2025) — https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-s3-express-one-zone-reduces-storage-request-prices
- Trino file system cache built on Alluxio (Trino 439) — https://trino.io/blog/2024/03/08/cache-refresh
- Databricks disk cache — https://docs.databricks.com/optimizations/disk-cache
- Tang et al., *Data Caching for Enterprise-Grade Petabyte-Scale OLAP*, USENIX ATC 2024 — https://arxiv.org/abs/2406.05962
- Databricks cache boosts Apache Spark performance (2018) — https://www.databricks.com/blog/2018/01/09/databricks-cache-boosts-apache-spark-performance.html
- Presto soft affinity + Alluxio local cache — https://prestodb.io/blog/2020/06/16/alluxio-datacaching
- Zeng et al., *An Empirical Evaluation of Columnar Storage Formats*, VLDB 2024 — https://www.vldb.org/pvldb/vol17/p148-zeng.pdf
- Kuschewski et al., *BtrBlocks: Efficient Columnar Compression for Data Lakes*, SIGMOD 2023 — https://www.cs.cit.tum.de/fileadmin/w00cfj/dis/papers/btrblocks.pdf
- Hao et al., *LiquidCache: Efficient Pushdown Caching for Cloud-Native Data Analytics*, VLDB 2025 — https://www.vldb.org/pvldb/vol18/p5662-hao.pdf
- Speed up Presto at Uber with Alluxio local cache — https://www.uber.com/blog/speed-up-presto-with-alluxio-local-cache/
- Dageville et al., *The Snowflake Elastic Data Warehouse*, SIGMOD 2016 — https://www.cs.purdue.edu/homes/csjgwang/CloudNativeDB/SnowflakeSIGMOD16.pdf
- Cutt, *Histojoin* (thesis), UBC 2009 — https://cmps-people.ok.ubc.ca/rlawrenc/research/Students/BC_09_Thesis.pdf
- NOCAP: Near-Optimal Correlation-Aware Partitioning Joins — https://arxiv.org/abs/2310.03098
- Gaffney & Patel, *Is Perfect Hashing Practical for OLAP Systems?*, CIDR 2024 — https://db.cs.cmu.edu/papers/2024/p65-gaffney.pdf
- ClickHouse hash tables for GROUP BY — https://clickhouse.com/blog/hash-tables-in-clickhouse-and-zero-cost-abstractions
- Nicholson, Chrysogelos, Ailamaki, *HPCache*, VLDB Journal 2024 — https://link.springer.com/article/10.1007/s00778-023-00828-7
- *Faster Parquet with a Column Cache* (our paper) — ../faster-parquet-cache/paper.md
