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

# Troubleshooting high memory usage: growing working set or allocator fragmentation?

> How to tell from jemalloc.allocated, jemalloc.active and jemalloc.resident whether high memory usage is live data or allocator fragmentation, and what a purge can return.

When the memory usage of a server is high and no query, merge, dictionary or cache explains it, compare three counters of the memory allocator: `jemalloc.allocated`, `jemalloc.active` and `jemalloc.resident`. If `allocated` is high, the server really holds that much data, and you have to find the component that owns it. If `allocated` is small and `active` is large, the memory is lost to fragmentation inside the allocator: no component owns it, and `SYSTEM JEMALLOC PURGE` cannot return it.

## Before you start

Rule out the usual consumers first: running queries, merges, dictionaries, primary keys, caches and in-memory tables. [Debugging memory issues](https://clickhouse.com/docs/concepts/features/performance/troubleshoot/debugging-memory-issues.md) has a query for each of them.

This article is for the case when all of them are small, but the `MemoryTracking` metric stays high, or queries fail with `(total) memory limit exceeded` while the failed allocation is small and `current RSS` in the message is close to `maximum`. ClickHouse corrects `MemoryTracking` from the measured memory usage of the process, and the limit of the server is checked against the resident memory as well. Memory that the allocator holds but does not use therefore counts against [`max_server_memory_usage`](https://clickhouse.com/docs/reference/settings/server-settings/settings/max-server-memory-usage#max_server_memory_usage) like live data.

## Read the three numbers

```sql theme={null}
SELECT
    formatReadableSize(anyIf(value, metric = 'jemalloc.allocated')) AS allocated,
    formatReadableSize(anyIf(value, metric = 'jemalloc.active')) AS active,
    formatReadableSize(anyIf(value, metric = 'jemalloc.resident')) AS resident
FROM system.asynchronous_metrics
WHERE metric IN ('jemalloc.allocated', 'jemalloc.active', 'jemalloc.resident');
```

| Value | Meaning |
| - | - |
| `allocated` | Bytes in live allocations. This is the working set: what the server and its queries hold at this moment. |
| `active` | Bytes in the memory pages that the allocator has assigned to live allocations, including the unused space inside them. It is never less than `allocated`. |
| `resident` | Bytes that the allocator keeps in physical memory: the active pages, its own metadata, and unused dirty pages that are not yet returned to the operating system. |
| `active - allocated` | Space inside active pages that no live allocation uses: fragmentation. The metric `jemalloc.fragmentation` contains this difference. |
| `resident - active` | An upper bound of what a purge can return to the operating system. |

Each server has its own allocator, so on a cluster read the numbers of every replica separately. Query all replicas with the [`clusterAllReplicas`](https://clickhouse.com/docs/reference/functions/table-functions/cluster) table function and group by the server. Without the `GROUP BY`, the result is one row that mixes values of different servers:

```sql theme={null}
SELECT
    hostName() AS host,
    formatReadableSize(anyIf(value, metric = 'jemalloc.allocated')) AS allocated,
    formatReadableSize(anyIf(value, metric = 'jemalloc.active')) AS active,
    formatReadableSize(anyIf(value, metric = 'jemalloc.resident')) AS resident
FROM clusterAllReplicas('my_cluster', system.asynchronous_metrics)
WHERE metric IN ('jemalloc.allocated', 'jemalloc.active', 'jemalloc.resident')
GROUP BY host
ORDER BY host;
```

In ClickHouse Cloud the cluster is named `default`: `FROM clusterAllReplicas(default, system.asynchronous_metrics)`.

## Look at the trend, not at one reading

One reading proves little: after a burst of queries the gap between `active` and `allocated` is large for a while on a healthy server. [`system.asynchronous_metric_log`](https://clickhouse.com/docs/reference/system-tables/asynchronous_metric_log) keeps the history. A low quantile per day approximates the level at rest between bursts:

```sql theme={null}
SELECT
    event_date,
    formatReadableSize(quantileIf(0.1)(value, metric = 'jemalloc.allocated')) AS allocated,
    formatReadableSize(quantileIf(0.1)(value, metric = 'jemalloc.active')) AS active,
    formatReadableSize(quantileIf(0.1)(value, metric = 'jemalloc.resident')) AS resident
FROM system.asynchronous_metric_log
WHERE event_date >= today() - 14
    AND metric IN ('jemalloc.allocated', 'jemalloc.active', 'jemalloc.resident')
GROUP BY event_date
ORDER BY event_date;
```

* `allocated` grows together with `active`: the working set grows. Go back to the per-component checks, or [profile the allocations](https://clickhouse.com/docs/concepts/features/performance/allocation-profiling.md).
* `allocated` stays flat while `active` climbs day after day: fragmentation accumulates.
* `resident` is far above `active`: freed pages are waiting to be returned. This is normally temporary.

## Example

In a test, 3000 empty tables of the `Memory` engine with 31 columns each were created, and then 2700 of them were dropped with `DROP TABLE ... SYNC`. The metadata of a table consists of many small allocations, and the objects of the tables that remain are spread over the same slabs as the objects of the dropped ones.

| Moment | `allocated` | `active` | `resident` |
| - | - | - | - |
| Start | 53.11 MiB | 75.63 MiB | 84.81 MiB |
| 3000 tables created | 119.09 MiB | 187.94 MiB | 199.81 MiB |
| 2700 tables dropped | 58.51 MiB | 198.06 MiB | 219.81 MiB |
| After `SYSTEM JEMALLOC PURGE` | 58.30 MiB | 198.81 MiB | 210.19 MiB |

Dropping the tables brought `allocated` back close to where it started, but `active` did not go down, and the purge returned only the few dirty pages.

## Check what a purge can return

[`SYSTEM JEMALLOC PURGE`](https://clickhouse.com/docs/reference/statements/system#jemalloc-purge) returns unused dirty pages to the operating system. It cannot return a page that still contains a live allocation. Before you run or schedule it, check how many dirty pages there are:

```sql theme={null}
SELECT
    anyIf(value, metric = 'jemalloc.arenas.all.pactive') AS pactive,
    anyIf(value, metric = 'jemalloc.arenas.all.pdirty') AS pdirty,
    anyIf(value, metric = 'jemalloc.arenas.all.pmuzzy') AS pmuzzy,
    round(pdirty / pactive, 4) AS dirty_to_active,
    anyIf(value, metric = 'jemalloc.arenas.dirty_decay_ms') AS dirty_decay_ms,
    anyIf(value, metric = 'jemalloc.background_thread.num_threads') AS background_threads
FROM system.asynchronous_metrics
WHERE metric LIKE 'jemalloc.%';
```

`pactive`, `pdirty` and `pmuzzy` are numbers of pages, not bytes, so compare them as a ratio. If `pdirty` is a small fraction of `pactive`, a purge returns next to nothing.

The server already purges on its own. Background threads of the allocator return dirty pages within `dirty_decay_ms` milliseconds (5000 by default), and the memory worker forces a purge when the memory usage or the amount of dirty pages is high (see [`memory_worker_purge_total_memory_threshold_ratio`](https://clickhouse.com/docs/reference/settings/server-settings/settings/memory-worker#memory_worker_purge_total_memory_threshold_ratio) and the related settings). Under sustained memory pressure, and on machines with less than 4 GiB of memory, the memory worker sets `dirty_decay_ms` to `0`, so that pages are returned as soon as they are freed. The query above shows the current value.

## Find the size classes that waste memory

[`system.jemalloc_bins`](https://clickhouse.com/docs/reference/system-tables/jemalloc_bins) shows the fragmentation per size class. Reading it requires the `SYSTEM JEMALLOC` privilege.

```sql theme={null}
SELECT
    size,
    curslabs,
    curregs,
    round(util, 3) AS utilization,
    formatReadableSize(waste) AS wasted
FROM system.jemalloc_bins
WHERE large = 0
ORDER BY waste DESC
LIMIT 5;
```

At the end of the example above it returned:

```text theme={null}
   ┌─size─┬─curslabs─┬─curregs─┬─utilization─┬─wasted────┐
1. │   80 │       83 │   28880 │       0.085 │ 23.73 MiB │
2. │  224 │       61 │   14588 │       0.117 │ 23.57 MiB │
3. │  112 │       46 │   12651 │       0.067 │ 18.77 MiB │
4. │  640 │       30 │     866 │       0.056 │ 8.85 MiB  │
5. │ 3072 │       54 │     665 │       0.192 │ 8.18 MiB  │
   └──────┴──────────┴─────────┴─────────────┴───────────┘
```

`size` is the size of an allocation in the class, `curslabs` the number of slabs that the class holds, and `curregs` the number of live allocations. The column `util` is the share of the regions in those slabs that are in use, and `waste` is the number of bytes in the slabs that no live allocation uses. A slab is released only when every region in it is free, so a few long-lived objects can keep many nearly empty slabs. The statistics are approximate because of the caches that the allocator keeps per thread: use them to rank the size classes, not as exact totals.

Waste that is concentrated in small size classes points to a workload that creates very many small objects of which some live for a long time. To find the code that allocates them, follow [Analyzing fragmentation from SQL](https://clickhouse.com/docs/concepts/features/performance/allocation-profiling.md#analyzing-fragmentation-from-sql) (version 26.9 and later). A regular heap profile ranks call stacks by live bytes: it explains `allocated`, not the gap between `allocated` and `active`.

## What you can do about fragmentation

* **Restart the server** to release the memory at once. The heap starts empty, and the fragmentation builds up again at the rate that the workload produces it, so this is a mitigation, not a fix.
* **Change the workload that causes it**, once the fragmentation analysis has shown which allocations stay alive.
* **Leave headroom.** Size the memory of the server for the `resident` level that you observe, not for `allocated`.
* **Upgrade.** Newer releases change how memory is allocated; for example, version 26.9 changed an allocator option to reduce fragmentation.
* If the growth does not stop, report it with the outputs of the queries in this article taken at several points in time.
