> ## 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.

# How to check the CPU and memory allocated to and used by a ClickHouse Cloud service with SQL

> SQL queries on system tables that show the CPU and memory allocated to each replica of a ClickHouse Cloud service and how much of them the service uses over time.

The CPU and memory allocated to a replica of a ClickHouse Cloud service are the `CGroupMaxCPU` and `CGroupMemoryTotal` metrics in `system.asynchronous_metrics`. The CPU that a replica uses is recorded in `system.metric_log`, and the memory it uses in `system.asynchronous_metric_log`. These tables are specific to each replica, so the queries below read them from all replicas with [`clusterAllReplicas`](https://clickhouse.com/docs/reference/functions/table-functions/cluster).

## Allocated CPU and memory now

One row per replica:

```sql theme={null}
SELECT *
FROM clusterAllReplicas('default', view(
    SELECT
        hostname() AS server,
        anyIf(value, metric = 'CGroupMaxCPU') AS cpu_cores,
        formatReadableSize(anyIf(value, metric = 'CGroupMemoryTotal')) AS memory
    FROM system.asynchronous_metrics
))
ORDER BY server ASC
SETTINGS skip_unavailable_shards = 1;
```

The total for the service:

```sql theme={null}
SELECT
    count() AS replicas,
    sum(cpu_cores) AS total_cpu_cores,
    formatReadableSize(sum(memory_bytes)) AS total_memory
FROM clusterAllReplicas('default', view(
    SELECT
        anyIf(value, metric = 'CGroupMaxCPU') AS cpu_cores,
        anyIf(value, metric = 'CGroupMemoryTotal') AS memory_bytes
    FROM system.asynchronous_metrics
))
SETTINGS skip_unavailable_shards = 1;
```

These are the metrics behind the **Allocated CPU** and **Allocated memory** graphs of the [Cloud console](https://clickhouse.com/docs/products/cloud/features/monitoring/cloud-console.md#memory-and-cpu).

## CPU used compared with CPU allocated

Each row of `system.metric_log` contains, in the `ProfileEvent_OSCPUVirtualTimeMicroseconds` column, the CPU time in microseconds that the server recorded since the previous row. The sum over one minute for all replicas, divided by 60 seconds, is the average number of CPU cores that the service used in that minute. The second subquery returns the `CGroupMaxCPU` value of every replica in the same minute. A replica that started or stopped during the minute counts only for the seconds in which it wrote rows, so the CPU used is compared with the CPU that was available in that minute.

```sql theme={null}
WITH
    toStartOfMinute(now()) - INTERVAL 1 MINUTE - INTERVAL 3 HOUR AS start_time,
    toStartOfMinute(now()) - INTERVAL 1 MINUTE AS end_time
SELECT
    t,
    round(sum(cpu_seconds) / 60, 2) AS cores_used,
    round(sum(replica_cores * seconds_with_data) / 60, 2) AS cores_allocated,
    round(sum(cpu_seconds) / sum(replica_cores * seconds_with_data), 2) AS utilization
FROM
(
    SELECT
        toStartOfMinute(event_time) AS t,
        hostname,
        sum(ProfileEvent_OSCPUVirtualTimeMicroseconds) / 1000000 AS cpu_seconds,
        uniqExact(event_time) AS seconds_with_data
    FROM clusterAllReplicas('default', merge('system', '^metric_log'))
    WHERE event_date BETWEEN toDate(start_time) AND toDate(end_time)
        AND event_time >= start_time AND event_time < end_time
    GROUP BY t, hostname
) AS used
INNER JOIN
(
    SELECT
        toStartOfMinute(event_time) AS t,
        hostname,
        avg(value) AS replica_cores
    FROM clusterAllReplicas('default', merge('system', '^asynchronous_metric_log'))
    WHERE metric = 'CGroupMaxCPU'
        AND event_date BETWEEN toDate(start_time) AND toDate(end_time)
        AND event_time >= start_time AND event_time < end_time
    GROUP BY t, hostname
) AS allocated USING (t, hostname)
GROUP BY t
ORDER BY t ASC
SETTINGS skip_unavailable_shards = 1;
```

The result has one row per minute:

* `cores_used` is the average number of CPU cores used by all replicas together.
* `cores_allocated` is the average number of CPU cores allocated to all replicas together. A replica with 4 cores that ran for 30 seconds of the minute adds 2.
* `utilization` is the ratio of the two. A value of 1 means that all the allocated CPU was in use.

`seconds_with_data` is the number of seconds of the minute in which the replica wrote a row to `system.metric_log`. The query assumes one row per second, which is the default collection interval of [`metric_log`](https://clickhouse.com/docs/reference/settings/server-settings/settings/other#metric_log).

`cores_used` is based on the same column as the `CPU Usage (cores)` chart of the `Cloud overview` dashboard in [`system.dashboards`](https://clickhouse.com/docs/reference/system-tables/dashboards). The **CPU usage** graph of the Cloud console is built from a different metric, so the two do not have to match exactly.

## CPU peaks per replica

An average over all replicas and over a long time hides peaks and replicas that are busier than the others. This query returns, for every replica and every 30 minutes, the average number of CPU cores in use and the number of cores in use during the busiest minute:

```sql theme={null}
WITH
    toStartOfMinute(now()) - INTERVAL 1 MINUTE - INTERVAL 1 DAY AS start_time,
    toStartOfMinute(now()) - INTERVAL 1 MINUTE AS end_time
SELECT
    replica,
    toStartOfInterval(minute, INTERVAL 30 MINUTE) AS t,
    round(avg(cores), 2) AS average_cores,
    round(max(cores), 2) AS busiest_minute_cores
FROM
(
    SELECT
        splitByChar('.', hostname)[1] AS replica,
        toStartOfMinute(event_time) AS minute,
        sum(ProfileEvent_OSCPUVirtualTimeMicroseconds) / 1000000 / 60 AS cores
    FROM clusterAllReplicas('default', merge('system', '^metric_log'))
    WHERE event_date BETWEEN toDate(start_time) AND toDate(end_time)
        AND event_time >= start_time AND event_time < end_time
    GROUP BY replica, minute
)
GROUP BY replica, t
ORDER BY replica ASC, t ASC
SETTINGS skip_unavailable_shards = 1;
```

Compare the result with `cpu_cores` of the same replica from the first query.

The period starts and ends at a whole minute, so no minute is counted in part. The first and the last row of a replica can cover fewer than 30 minutes. A minute in which the replica started or stopped has CPU time for only a part of it, so its value is lower than the usage while the replica ran.

Do not take the maximum of single rows of `system.metric_log` as the peak. A thread adds its CPU time to the counter from time to time, for example after it has processed a block of data, not continuously. For example, a query that processes one large block in one thread for several seconds reports almost nothing while it runs, and then all of its CPU time in a single row. Such a row shows more cores than were in use during that second, and the value can exceed the number of cores of the replica. A sum over a minute evens this out.

## Memory used per replica

`MemoryResident` is the amount of physical memory used by the server process. It is also the metric behind the **Memory usage** graph of the Cloud console. The query compares its maximum in every 30 minutes with the memory allocated to the replica:

```sql theme={null}
WITH
    now() - INTERVAL 1 DAY AS start_time,
    now() AS end_time
SELECT
    splitByChar('.', hostname)[1] AS replica,
    toStartOfInterval(event_time, INTERVAL 30 MINUTE) AS t,
    formatReadableSize(maxIf(value, metric = 'MemoryResident')) AS max_memory_used,
    formatReadableSize(maxIf(value, metric = 'CGroupMemoryTotal')) AS memory_allocated,
    round(maxIf(value, metric = 'MemoryResident') / maxIf(value, metric = 'CGroupMemoryTotal'), 2) AS utilization
FROM clusterAllReplicas('default', merge('system', '^asynchronous_metric_log'))
WHERE metric IN ('MemoryResident', 'CGroupMemoryTotal')
    AND event_date BETWEEN toDate(start_time) AND toDate(end_time)
    AND event_time BETWEEN start_time AND end_time
GROUP BY replica, t
ORDER BY replica ASC, t ASC
SETTINGS skip_unavailable_shards = 1;
```

The total amount of memory tracked by the server is in the `CurrentMetric_MemoryTracking` column of [`system.metric_log`](https://clickhouse.com/docs/reference/system-tables/metric_log). The advanced dashboard shows it as **Memory (tracked, bytes)**.

## What to keep in mind

* The `hostname` column of the log tables holds the fully qualified domain name of the server that wrote the row. The queries keep the part before the first dot to get a short replica name.
* `merge('system', '^metric_log')` reads all versions of a log table. After an upgrade that changes the structure of a system log table, ClickHouse renames the old table and creates a new one, see [querying multiple versions](https://clickhouse.com/docs/reference/system-tables/overview.md#querying-multiple-versions).
* `skip_unavailable_shards = 1` skips replicas that are being added or removed at the moment of the query, see [querying across nodes](https://clickhouse.com/docs/reference/system-tables/overview.md#querying-across-nodes).
* When a service is scaled, new replicas are added before the old ones are removed, see [make before break](https://clickhouse.com/docs/products/cloud/features/autoscaling/make-before-break.md). While both exist, `cores_allocated` includes both, each for the seconds in which it wrote rows.
* The same page says that 30 days of system table data are kept when replicas are replaced, so do not expect older history.
* The log tables have rows only for the time when a replica was running. An idle or stopped service leaves a gap.
* The periods of the two CPU queries end one minute before the start of the current minute. The server writes rows to the log tables in batches, every 7.5 seconds by default (`flush_interval_milliseconds`, see [system tables](https://clickhouse.com/docs/reference/system-tables/overview.md#system-tables-introduction)), so the newest minute can lack its last rows.
* Queries on system tables add load to the service and [prevent it from idling](https://clickhouse.com/docs/products/cloud/features/monitoring/system-tables.md#system-considerations). For continuous monitoring, use the Cloud console or the [Prometheus endpoint](https://clickhouse.com/docs/products/cloud/features/monitoring/prometheus.md).
* ClickHouse Cloud takes its scaling decisions from its own measurements, as described in [scaling recommendations](https://clickhouse.com/docs/products/cloud/features/autoscaling/scaling-recommendations.md). Use these queries to understand your workload, not to reproduce those decisions.

## Related pages

* [How to get the history of the size of a ClickHouse Cloud service from system tables](https://clickhouse.com/docs/resources/support-center/knowledge-base/cloud-services/cloud-service-size-history-from-system-tables.md)
* [Querying ClickHouse's system database](https://clickhouse.com/docs/products/cloud/features/monitoring/system-tables.md)
* [`system.asynchronous_metrics`](https://clickhouse.com/docs/reference/system-tables/asynchronous_metrics)
* [Automatic scaling](https://clickhouse.com/docs/products/cloud/features/autoscaling/overview.md)
