> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# Spill to disk

> How to configure the database to spill intermediate query results to disk or object storage to prevent out-of-memory errors.

**Beta feature**

[Advice on use of Beta features](/documents/4.2/maturity/features.md)

This topic describes how to spill intermediate computation results of large operators to local disks and object storage.

## Overview

For database systems that rely on in-memory computing for query execution, like the database, they can consume substantial memory resources when processing queries with aggregate, sort, and join operators on a big dataset. When memory limits are reached, these queries are forcibly terminated due to out-of-memory (OOM).

However, there are still chances that you want certain memory-intensive tasks to be completed stably and performance is not your top priority, for example, building a materialized view, or performing a lightweight ETL with INSERT INTO SELECT. These tasks can easily exhaust your memory resources and thereby block other queries running in your cluster. Usually, to address this issue, you can only fine-tune these tasks individually, and rely on your resource isolation strategy to control the query concurrency. This could be particularly inconvenient and likely to fail under some extreme scenarios.

From StarRocks v3.0.1, the database supports spilling the intermediate results of some memory-intensive operators to disks. With this feature, you can trade a tolerable drop in performance for a significant reduction in memory usage, thereby improving system availability.

Currently, the database' spilling feature supports the following operators:

* Aggregate operators
* Sort operators
* Hash join (LEFT JOIN, RIGHT JOIN, FULL JOIN, OUTER JOIN, SEMI JOIN, and INNER JOIN) operators
* CTE operators (Supported from v3.3.4 onwards)
* Nested loop join (CROSS JOIN) operators (Supported from v3.1.0 onwards, and only when `spill_mode` is set to `force`)
* Analytic (window) operators, for whole-partition window frames only, that is, the window either has no frame clause or specifies `ROWS/RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`, and each window function in the operator is one of `sum`, `avg`, `count`, `min`, `max`, `first_value`, and `last_value`

> **NOTE**
>
> Spilling is enabled for all the supported operators by default. You can control the scope with the session variable `spillable_operator_mask`, a bitmask in which each operator type takes one bit: hash join (1), aggregate (2), distinct aggregate (4), sort (8), nest-loop join (16), multicast local exchange (32), and analytic (64). The default value `-1` enables all of them. For example, to keep spilling enabled for the other operators but disable it for analytic operators, set `spillable_operator_mask` to `-65`.

## Enable intermediate result spilling

Follow these steps to enable intermediate result spilling:

1. (Optional) Specify the local spill directory `spill_local_storage_dir`, which stores the spilled intermediate result on the local disk, in the BE configuration file **be.conf** or the CN configuration file **cn.conf**, and restart the cluster to allow the modification to take effect. If you do not specify it, the default directory `${STARROCKS_HOME}/spill` is used.

   ```Properties theme={null}
   spill_local_storage_dir=/<dir_1>[;/<dir_2>]
   ```

   > **NOTE**
   >
   > * You can specify multiple `spill_local_storage_dir` by separating them with semicolons (`;`).
   > * In a production environment, we strongly recommend you use different disks for data storage and spilling. When intermediate results are spilled to disk, there could be a significant increase in both writing load and disk usage. If the same disk is used, this surge can impact other queries or tasks running in the cluster.

2. Execute the following statement to enable intermediate result spilling:

   ```SQL theme={null}
   SET enable_spill = true;
   ```

3. Configure the mode of intermediate result spilling using the session variable `spill_mode`:

   ```SQL theme={null}
   SET spill_mode = { "auto" | "force" };
   ```

   > **NOTE**
   >
   > Each time a query with spilling completes, the database automatically clears the spilled data the query produces. If BE crashes before clearing the data, the database clears it when the BE is restarted.

   | **Variable** | **Default** | **Description** |
   | - | - | - |
   | enable\_spill | false | Whether to enable intermediate result spilling. If it is set to `true`, the database spills the intermediate results to disk to reduce the memory usage when processing aggregate, sort, join, or eligible analytic (window) operators in queries. |
   | spill\_mode | auto | The execution mode of intermediate result spilling. Valid values:<ul><li>`auto`: Spilling is automatically triggered when the memory usage threshold is reached.</li><li>`force`: the database forcibly executes spilling for all relevant operators, regardless of memory usage.</li></ul>The values `none` and `random` are also accepted, but they are intended for internal testing only. This variable takes effect only when the variable `enable_spill` is set to `true`. |

## \[Experimental] Adaptive spill column encoding

From this version onwards, BE supports an experimental adaptive column-codec selector for
spilled data. When enabled, each spilled column samples a set of type-appropriate encodings
(RLE, delta, frame-of-reference, patched FOR, dictionary, front coding, block compression,
ALP for decimal-like doubles, and more) and picks the one minimizing an I/O-plus-CPU cost
model instead of the fixed streamvbyte/LZ4 encoding.

Both stages are on by default whenever `enable_spill` is `true` and are controlled per session:

| Session variable | Default | Description |
| - | - | - |
| `spill_enable_codec_selector` | `true` | Uses the adaptive spill column-codec selector (v2 spill serialization format). When `false`, the legacy `spill_encode_level`-driven encoding is used unchanged. |
| `spill_enable_block_compress` | `true` | Runs the block-level (stage-2) spill compression pass: the whole serialized chunk is compressed once more before being written to disk (and transparently decompressed on read). Sampled per window, so incompressible data pays no size penalty. Orthogonal to the codec selector; the two compose. |

The cost model and the stage-2 compressor are tuned cluster-wide via BE configuration items:

| Configuration item | Default | Description |
| - | - | - |
| `spill_codec_disk_bandwidth_mbps` | `100` | Effective write throughput of the spill target (MB/s), used to price encoding and decoding CPU against saved disk bytes. This is a policy input rather than a measurement: it states how many bytes of I/O one nanosecond of codec CPU is worth. Only the order of magnitude matters, and lower values are the safer error: they over-compress, but the extra CPU still buys real I/O savings. Set it to `20` or so when the spill volume is close to capacity, to trade CPU for a smaller footprint. See `spill_codec_disk_bandwidth_mbps` in the BE configuration reference for the measured sensitivity in both the page-cache and the device regime. |
| `spill_block_compress_type` | `lz4` | Block compressor used by the stage-2 pass: `lz4` (fast, suited to the spill hot path) or `zstd` (smaller output, slower). Any other value disables the stage-2 pass. |
| `spill_block_compress_min_gain` | `0.8` | Vote threshold for the stage-2 pass. A sampled chunk counts as compressible only if compression shrinks it to at most this fraction of its original size; a sampling window turns stage-2 on when the majority of its sampled chunks vote yes, and then compresses every chunk of that window. Raise it toward `1.0` to accept marginal gains, lower it to compress only clearly compressible data. |

## \[Preview] Spill intermediate result to object storage

From v3.3.0 onwards, the database supports spilling intermediate results to object storage.

**Tip**

Before enabling spilling to object storage, you must create a storage volume to define the object storage you want to use. For detailed instruction on creating a storage volume, see [CREATE STORAGE VOLUME](/documents/4.2/sql-reference/sql-statements/cluster-management/storage_volume/CREATE_STORAGE_VOLUME.md).

After you have enabled spilling in the previous step, you can further set these system variables to allow the intermediate results to be spilled to object storage:

```SQL theme={null}
SET enable_spill_to_remote_storage = true;

-- Replace <storage_volume_name> with the name of the storage volume which you want to use.
SET spill_storage_volume = '<storage_volume_name>';
```

After spilling to object storage has been enabled, the intermediate results of queries that triggered spilling will be first stored in the local disks of the BE or CN nodes, and then the object storage if the capacity limit of the local disks is reached.

Please note that, if the storage volume you specified for `spill_storage_volume` does not exist, spilling to object storage will not be enabled.

## Limitations

* Not all OOM issues can be resolved by spilling. For example, the database cannot release the memory used for expression evaluation.
* Usually, queries with spilling involved indicate a tenfold increase in query latency. We recommend you extend the query timeout for these queries by setting the session variable `query_timeout`.
* There is a significant performance drop in spilling to object storage compared to spilling to local disks.
* `spill_local_storage_dir` of each BE or CN node is shared among all queries running on the node. Currently, the database does not support setting a size limit of spilled data to local disks individually for each query. Therefore, concurrent queries involved spilling may impact one another.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.