# Shared Memory Sizing

API7 Gateway shares metrics, service-discovery data, and other state between its workers through NGINX shared memory zones (`lua_shared_dict`). A full zone can drop data or evict entries. On affected releases, a full Prometheus zone can also cause high CPU usage. Size these zones for your workload and monitor their usage.

## Zones That Need Sizing[​](#zones-that-need-sizing "Direct link to Zones That Need Sizing")

The API7 Dashboard monitors the following zones because their contents are not self-healing: an overflow causes a persistent, hard-to-diagnose loss rather than a transient cache miss.

| Zone                              | Default    | Holds                                               | Symptom when full                                    |
| --------------------------------- | ---------- | --------------------------------------------------- | ---------------------------------------------------- |
| `prometheus-metrics-advanced`     | 128 MB     | each Prometheus time series (\~1 KB)                | metrics stop updating; gaps in dashboards and alerts |
| `kubernetes` / `nacos` / `consul` | 64 MB each | one entry per discovered service (its node list)    | new or changed upstream nodes do not resolve         |
| `api-calls-for-portal`            | 64 MB      | one counter per Developer Portal API-call dimension | portal analytics under-count                         |
| `tracing_buffer`                  | 32 MB      | SkyWalking trace segments awaiting report           | trace spans are dropped                              |

Other shared zones can also need tuning for a particular workload. Check their errors and usage instead of assuming that eviction makes their capacity unlimited.

note

The defaults above are chosen to cover the majority of deployments. Change them only if your scale exceeds the capacity described below, or if you want to reclaim memory on a small deployment. An explicit value always overrides the default.

## Capacity Reference[​](#capacity-reference "Direct link to Capacity Reference")

The figures below come from measuring how many entries fit per megabyte on the API7 Gateway runtime. Shared memory is allocated in fixed slab classes, so the cost per entry rounds up to the next power-of-two boundary. Crossing a boundary — a longer key or a larger value — roughly doubles the per-entry cost, which is why the numbers below step in halves.

### Prometheus Metrics[​](#prometheus-metrics "Direct link to Prometheus Metrics")

Each unique metric-and-label combination (a time series) costs about 1 KB: the library stores the label set twice — once as the metric sample and once in an internal key index — and NGINX rounds each of those two entries up to a \~512-byte slab.

| Zone size        | Approximate time series |
| ---------------- | ----------------------- |
| 64 MB            | 65,000                  |
| 128 MB (default) | 130,000                 |
| 256 MB           | 260,000                 |

The series count grows with the number of routes and services that have the `prometheus` plugin enabled, multiplied by label cardinality and histogram buckets. Histogram metrics dominate: the request-latency histogram alone adds about 15 buckets per label combination, whereas counters such as bandwidth add only a couple of series each. High-cardinality labels, such as a per-upstream-node label, multiply the count quickly; use the `prometheus` plugin's `disabled_labels` metadata to drop specific labels if you need to cap it.

In version 3.10.9 and later, stream service labels add series for each service, including distinct listener and service combinations for listener-keyed families. Their fixed `service` and `service_id` labels cannot be removed with `disabled_labels`, so include those combinations in the capacity estimate.

Very short label sets fit two to three times more series per MB, and a full zone produces a proportionally large `/metrics` response — roughly 0.2 MB of exposition text per MB of zone (a full 128 MB zone is about 25 MB), so at high cardinality, trimming labels helps more than enlarging the zone.

### Service Discovery[​](#service-discovery "Direct link to Service Discovery")

Each discovered service is stored as the JSON list of its backend nodes, so the per-service cost grows with the number of nodes per service.

| Nodes per service | Services per 64 MB (default) |
| ----------------- | ---------------------------- |
| 1                 | 170,000                      |
| 5                 | 100,000                      |
| 20                | 31,000                       |
| 100               | 8,000                        |

Size the `kubernetes`, `nacos`, or `consul` zone to the number of services in your registry, leaving headroom for the services with the largest node lists. The figures above are for `kubernetes`, which keeps a small version marker alongside each service; `nacos` and `consul` store a single entry per service and hold roughly 1.5× more at low node counts.

### Developer Portal API Calls[​](#developer-portal-api-calls "Direct link to Developer Portal API Calls")

Each entry is a counter keyed by a combination of subscription, developer, application, credential, API product, and response status — about 512 bytes.

| Zone size       | Approximate counter combinations |
| --------------- | -------------------------------- |
| 64 MB (default) | 130,000                          |
| 128 MB          | 260,000                          |

The number of live combinations grows with portal consumers × applications × products × distinct response codes. Counters are flushed periodically, so size for peak concurrent cardinality rather than cumulative traffic.

### Tracing Buffer[​](#tracing-buffer "Direct link to Tracing Buffer")

The buffer holds SkyWalking trace segments queued for reporting. It absorbs spikes when the collector is slow or briefly unreachable; segments drain as they are reported.

| Segment size | Segments per 32 MB (default) |
| ------------ | ---------------------------- |
| \~1 KB       | 16,000                       |
| \~2 KB       | 8,000                        |
| \~4 KB       | 4,000                        |

Size this for how long you need to keep buffering during a collector slowdown, not for steady-state throughput. If you see dropped segments while the collector is healthy, raise it.

## Prevent Metric Dictionary Exhaustion[​](#prevent-metric-dictionary-exhaustion "Direct link to Prevent Metric Dictionary Exhaustion")

Reduce metric cardinality before increasing capacity. Use the following steps to limit shared-memory growth and recover an affected gateway:

1. Remove unbounded `extra_labels`, such as request IDs or full request URIs. Disable unnecessary supported labels and estimate the remaining series count under peak traffic.
2. Increase the metric zone if the bounded workload still needs more space, allowing for the gateway's container memory limit. Restart gateway instances one at a time to apply the new size.
3. Monitor the zone's used capacity and errors such as `Shared dictionary used for prometheus metrics is full`. Verify that metric expiry actually reclaims capacity instead of relying on the configured `expire` value alone.
4. If a worker is already stuck at high CPU, remove the affected instance from traffic and restart it after reducing cardinality or increasing capacity. A restart clears in-memory metrics; expect counter resets and gaps in monitoring.

## Change the Defaults[​](#change-the-defaults "Direct link to Change the Defaults")

Override any of these zones on the data plane. The value is a size string such as `128m` or `1g`. For Helm deployments, apply the change with `helm upgrade`; for a directly managed data plane, edit `config.yaml` and restart the node. Apply the change with a controlled rolling restart and verify the reported capacity. Restarting clears in-memory state, including metrics and counters.

* Data Plane Config
* Helm

Set the zone under `nginx_config` in the data plane `config.yaml`, which overrides `config-default.yaml`:

```
nginx_config:

  meta:

    lua_shared_dict:

      prometheus-metrics: 512m      # backs the prometheus-metrics-advanced zone

  http:

    lua_shared_dict:

      tracing_buffer: 64m

      api-calls-for-portal: 128m

    custom_lua_shared_dict:

      kubernetes: 128m

      nacos: 128m

      consul: 128m
```

Set the zone in the gateway chart values:

```
apisix:

  meta:

    luaSharedDict:

      prometheus-metrics: 512m      # backs the prometheus-metrics-advanced zone

  http:

    luaSharedDict:

      tracing_buffer: 64m

      api-calls-for-portal: 128m

  customLuaSharedDicts:

    - name: kubernetes

      size: 128m

    - name: nacos

      size: 128m

    - name: consul

      size: 128m
```

The Prometheus zone is configured under the `meta` context with the key `prometheus-metrics`, which sizes the `prometheus-metrics-advanced` zone shown on the Dashboard.

## Monitor Usage[​](#monitor-usage "Direct link to Monitor Usage")

The API7 Dashboard reports the used and total capacity of each monitored zone per data plane node and raises an alert as a zone approaches its limit. Use it to confirm your sizing under real traffic and to catch a zone trending toward full before it starts dropping data.
