> For the complete documentation index, see [llms.txt](https://docs.lenses.io/latest/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.lenses.io/latest/deployment/configuration/hq/sizing-and-tuning.md).

# Sizing and tuning

Size HQ and its Postgres database for consumer groups, and tune HQ settings as your fleet grows.

Reference for sizing HQ and Postgres for consumer groups. HQ stores one row per consumer group, topic and partition, and every size below follows the number of rows. Memory is in GiB, CPU in cores. The figures were measured with HQ handling all resources from its agents, with consumer groups as the dominant load.

For the settings mentioned here, see the [HQ configuration reference](https://docs.lenses.io/latest/deployment/configuration/hq/configuration-reference.md). With the Helm chart, version 6.3.5 or later, set `consumerGroups.*` under `lensesHq.consumerGroups` and `database.*` under `lensesHq.storage.postgres`.

## Measure your fleet

Before HQ runs, count the rows of `kafka-consumer-groups.sh --describe --all-groups` to get the total rows. Plan for the worst case: every row changes on every poll.

* Groups with no committed offsets have no rows.
* A topic read by several groups has a row per group. 1,000 partitions read by 10 groups are 10,000 rows.
* HQ re-reads a group when anything in it changes, but writes only the rows that changed. A rebalance (group state change) rewrites all of them.

With HQ running, run this on the HQ database. Run the heavy queries off peak.

```sql
-- Total rows
SELECT count(*) FROM cg_partition;

-- Rows per environment, largest first
SELECT env_name, count(*) FROM cg_partition GROUP BY 1 ORDER BY 2 DESC LIMIT 10;

-- Environments with groups
SELECT count(DISTINCT env_name) FROM cg_group;

-- Table size, both tables with indexes
SELECT pg_size_pretty(pg_total_relation_size('cg_partition') + pg_total_relation_size('cg_partition_committed_window'));

-- Rows written per second: run twice, 60 seconds apart,
-- then divide the difference by 60
SELECT n_tup_ins + n_tup_upd FROM pg_stat_user_tables WHERE relname = 'cg_partition';
```

Two numbers come from metrics. HQ serves them at `/metrics` on `metrics.prometheusAddress`.

* Refreshes per second: `rate(hq_consumer_groups_env_refresh_total{outcome="success"}[5m])`. The poller keeps up when it matches environments ÷ `pollInterval`.
* Postgres CPU throttling: `container_cpu_cfs_throttled_periods_total` ÷ `container_cpu_cfs_periods_total` for the Postgres container. Above a few percent, Postgres needs more cores.

The share of rows rewritten per poll is rows written per second × `pollInterval` ÷ total rows. The worst case is 100%, and the tables below assume it. If 20% of rows change, you need about a fifth of the cores.

## HQ

Size by total rows. HQ writes each environment in batches of `maxPartitionsPerBatch` rows, so one large environment does not need more memory.

| Total rows | Refresh workers | Memory | CPU |
| ---------- | --------------- | ------ | --- |
| 100,000    | 4               | 1 GiB  | 1   |
| 500,000    | 4               | 1 GiB  | 1   |
| 1,000,000  | 4 to 8          | 2 GiB  | 1   |
| 2,000,000  | 8 to 16         | 3 GiB  | 2   |
| 4,000,000  | 16              | 4 GiB  | 3   |

* Round up for sizes in between. Below 10,000 rows, 256 MiB and 0.5 core is enough.
* Memory is 1.5 × the expected peak, for `maxPartitionsPerBatch` up to 40,000. A higher limit raises it.
* Workers, environments and groups add memory and CPU. 4,000,000 rows over 350 environments and 47,000 groups peaked at 2.6 GiB and 2.5 cores.

## Postgres

### CPU

```
writes per second  = rows rewritten per poll / pollInterval (seconds)   # default 30
cores for writes   = writes per second / rate per core   # 8,000 dedicated node, 2,500 shared node
cores to provision = cores for writes / 0.7              # keeps 30% for reads and index maintenance
```

* Rows rewritten per poll: the total rows for the worst case, or rows written per second × `pollInterval` once HQ runs.
* Rate per core, in rows per second: **8,000** on a dedicated Postgres node with no other workloads, **2,500** on a shared node. The rate drops if workers saturate the cores. The 0.7 keeps Postgres out of that range, and leaves 30% for API reads and index maintenance.
* Example: 1,000,000 rows at 90s is 11,100 writes per second. At 8,000 per core: 1.4 cores for writes, 2 to provision. At 2,500: 4.4 and 6.5.

Cores to provision on a dedicated Postgres node (8,000 rows per second per core), worst case, rounded up to the next half core. On a shared node, multiplying by about 3 gives a rough estimate. To provision, use the formula above with 2,500 rows per second per core.

| Total rows | 30s | 60s | 90s | 120s | 180s | 300s |
| ---------- | --- | --- | --- | ---- | ---- | ---- |
| 100,000    | 1   | 0.5 | 0.5 | 0.5  | 0.5  | 0.5  |
| 500,000    | 3   | 1.5 | 1   | 1    | 0.5  | 0.5  |
| 1,000,000  | 6   | 3   | 2   | 1.5  | 1    | 1    |
| 2,000,000  | 12  | 6   | 4   | 3    | 2    | 1.5  |
| 4,000,000  | 24  | 12  | 8   | 6    | 4    | 2.5  |

### Memory, disk and IOPS

* **`shared_buffers`:** more than the table size, about 3 to 4 KB per row. If the tables outgrow it, Postgres goes disk bound, writes slow down and the disk fills.
* **Pod memory:** 1.5 to 2 × `shared_buffers`. Set the request close to real use.
* **Volume:** at least 2 × the space in use, which is about 4 GiB at 1,000,000 rows, 8 GiB at 2,000,000 and 18 GiB at 4,000,000. Rows take 3 to 5 KB, mostly indexes. A rebuild copies each index, so it needs room too.
* **IOPS:** provisioned, such as `gp3`. Start at 6,000 above 100,000 rows.

| Total rows | `shared_buffers` | Pod memory   | Volume | IOPS  |
| ---------- | ---------------- | ------------ | ------ | ----- |
| 100,000    | 1 GB             | 2 GiB        | 2 GiB  | 3,000 |
| 500,000    | 3 GB             | 6 GiB        | 6 GiB  | 6,000 |
| 1,000,000  | 5 GB             | 8 to 10 GiB  | 10 GiB | 6,000 |
| 2,000,000  | 8 GB             | 12 to 16 GiB | 16 GiB | 6,000 |
| 4,000,000  | 16 GB            | 24 to 32 GiB | 40 GiB | 6,000 |

After a Postgres crash or a failover to a standby, `cg_partition` is empty, and HQ rebuilds it from the agents within minutes.

## Tuning

Every setting is described in the [HQ configuration reference](https://docs.lenses.io/latest/deployment/configuration/hq/configuration-reference.md). These are the ones that matter for sizing.

* **`consumerGroups.pollInterval`:** default 30s. Doubling it about halves the Postgres CPU needed, and data gets that much older. The single slot for large environments and write bursts can limit throughput before average CPU does.
* **`consumerGroups.refreshWorkers`:** you need about `environments × refresh time / pollInterval`. 150 environments with 2,000,000 rows need 8 workers at 120s and 16 at 60s. Workers help only while Postgres has spare CPU. Past that, more workers lower throughput.
* **`database.pollerPoolMaxConns`:** at least `consumerGroups.refreshWorkers`.
* **Connections:** (`database.maxConns` + `database.pollerPoolMaxConns` + 2 for health checks) × HQ replicas must stay under the database's `max_connections`.
* **Timeouts:** keep `database.statementTimeout` above `consumerGroups.readTimeout`.

## Index maintenance

`cg_partition` is rewritten on every poll, so its indexes bloat faster than autovacuum cleans them. A periodic `REINDEX INDEX CONCURRENTLY` compacts them without blocking reads or the poller. Keep it on above 100,000 rows. Above 300,000 rows, run it as a cron job.

### In process or cron job

Both run the same rebuild with the same guards. Use either one or both.

* **In process (default):** HQ runs it on a timer, one `interval` after it starts and then every `interval`. The timer restarts when HQ restarts. Nothing to set up.
* **Cron job (recommended for large fleets):** you schedule the `lenses-hq reindex-cg-partition` command. The schedule survives HQ restarts, and a pass skipped for a vacuum is retried at the next run. A full rebuild takes minutes on a large fleet and slows reads, so you can run it off peak.

#### In process

```yaml
consumerGroups:
  indexMaintenance:
    enabled: true
    interval: 60m
    minGrowthPercent: 25
```

* `enabled: false` turns off the in process task only.
* `interval` is the time between passes. The minimum is 1m.
* `minGrowthPercent` skips a pass until the indexes have grown by this much since the last rebuild. `0` rebuilds every interval.

#### Cron job

1. If cron should be the only schedule, set `consumerGroups.indexMaintenance.enabled: false`. Leaving it on is safe, but HQ's own timer then also runs passes at any hour.
2. Schedule the command with the configuration file HQ uses. Without a path it reads `config.yaml` in the current directory.

On a host with cron:

```
*/15 * * * * lenses-hq reindex-cg-partition /path/to/config.yaml >> /var/log/cg_partition_reindex.log 2>&1
```

A run does nothing if the last pass finished less than `interval` ago, so keep `interval` shorter than the time between runs. To run only off peak, turn off the in process task and use a night schedule such as `0 3 * * *`.

On Kubernetes with the Helm chart, version 6.3.5 or later:

```yaml
cgIndexMaintenanceCronJob:
  enabled: true
  schedule: "*/15 * * * *"
```

The Job runs HQ's image with HQ's configuration and database credentials, and needs no Kubernetes permissions. Its pod must reach Postgres: if a NetworkPolicy admits only HQ's pods, also allow pods labelled `component: lenses-hq-cg-reindex`.

Without the chart, run HQ's image as a CronJob with the args `reindex-cg-partition` and the path to HQ's configuration file, and give it the same configuration file and environment variables as HQ.

To run it now and read the result, here for a release named `lenses-hq` (`kubectl get cronjob` shows the name):

```
kubectl create job --from=cronjob/lenses-hq-cg-reindex reindex-manual-1
kubectl logs job/reindex-manual-1
```

How the command behaves:

* One run is one pass. A schedule tighter than `interval` is safe: most runs find the guards unmet and exit at once.
* `enabled` only controls the in process task. The command always runs when you start it, so you can turn the in process task off and use cron alone.
* Two runs never overlap, whether cron with cron, cron with the in process task, or several HQ replicas. One runs and the others exit at once.
* Exit code 0 means the indexes were rebuilt or a guard skipped the pass. A non zero code means something went wrong: an index failed, or HQ could not read its configuration, reach the database or take the lock. A failed Job is not a health signal. Read the log for `cg_partition index rebuild complete` or `cg_partition index rebuild failed`. A skipped pass logs only at debug level. A failed index is retried next run and does not block the others.
* Each run is a new process, so a pass cut short, by a vacuum for example, starts again from the largest index at the next run. The in process task continues where it stopped.

### What a pass does

* It rebuilds one index after another. A watchdog cancels any single rebuild past 15 minutes.
* No pass starts, and a running pass stops between indexes, while a vacuum runs on `cg_partition`. On a big fleet, or at a short interval, autovacuum runs almost back to back, so rebuilds rarely get a gap and the indexes keep growing. Watch `hq_consumer_groups_reindex_skipped_total` with reason `autovacuum_active`.
* After you remove a very large environment, passes are skipped until the indexes grow past the old size. Set `consumerGroups.indexMaintenance.minGrowthPercent: 0` for one pass, or run `DELETE FROM cg_reindex_state`.
* HQ runs `ANALYZE` on `cg_partition` after an environment of 50,000 or more rows is rewritten, at most every 5 minutes. It is skipped during a rebuild.

## Troubleshooting

| Symptom                                                                                                 | Fix                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Data older than `pollInterval`, Postgres throttled                                                      | Add cores or raise `consumerGroups.pollInterval`. More workers do not help                                                                                                                                                                     |
| Data older than `pollInterval`, Postgres not throttled, `hq_consumer_groups_worker_blocks_total` rising | Raise `consumerGroups.refreshWorkers` and `database.pollerPoolMaxConns` together. Above 500,000 rows, add Postgres cores too                                                                                                                   |
| Large environments refreshed too rarely, `hq_consumer_groups_large_env_gate_wait_duration_seconds` high | If Postgres stays below about 70% of its CPU limit, set `consumerGroups.maxPartitionsPerBatch` just above their size, about 40,000 for environments of 20,000 to 40,000 rows, and add HQ memory. Otherwise raise `consumerGroups.pollInterval` |
| Thousands of topics in one environment, polls failing with `DeadlineExceeded`                           | Raise `consumerGroups.chunkConcurrency` (for example 12) and `consumerGroups.composeTimeout` (for example 15m)                                                                                                                                 |
| Slow polls because Kafka is slow                                                                        | Raise `composeConcurrency`. Memory grows with it                                                                                                                                                                                               |
| Reads failing with 503 on big sorts or name filters                                                     | Sort on `lag`, `lag_seconds` or `lag_catch_up_seconds`, or raise `consumerGroups.readTimeout` and keep `database.statementTimeout` above it                                                                                                    |
| Blank time lag and catch-up                                                                             | The environment refreshes too rarely. Fix data age. Offset lag is always filled                                                                                                                                                                |
| Rebuilds skipped after removing a very large environment                                                | Set `consumerGroups.indexMaintenance.minGrowthPercent: 0` for one pass, or run `DELETE FROM cg_reindex_state`                                                                                                                                  |
| Disk space needed back after deleting an environment                                                    | Run `VACUUM FULL cg_partition` by hand. HQ never does, it locks the table                                                                                                                                                                      |

Why not raise the batch limit or the workers when Postgres is near its limit: several large environments then write at once, Postgres saturates, total throughput drops and HQ uses more memory. With real headroom a high limit pays off, so raise it together with the Postgres cores.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.lenses.io/latest/deployment/configuration/hq/sizing-and-tuning.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
