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

# Size and Load-Test Connectors

> Learn what drives Connector CPU, memory and disk use, how to scale for high availability, and how to load-test safely

## Overview

Connector resource use depends on your traffic, payload sizes and policies, so no single size fits every deployment.
This page explains what drives CPU, memory and disk use, and how to scale and monitor Connectors.
It ends with a load-test method to size Connectors for your own workload.

For the baseline requirements, see [Resource Requirements](https://docs.formal.ai/docs/guides/core-concepts/connectors/deployment.md#resource-requirements).

## What Drives Resource Use

| Driver | Resource | Why |
| - | - | - |
| Requests per second | CPU | The Connector parses each request and evaluates your policies on it. |
| Policy complexity | CPU | Policies run on a worker pool. Regexes, decoding and rewrites over large bodies cost more CPU. |
| Open connections and streams | Memory | More concurrent requests and streams hold more request and response data in memory at once. |
| Payload size | Memory | LLM request bodies are read whole into memory for inspection. |
| Log volume | Memory, disk | Every request produces a log. Logs wait in memory, then on disk, until delivery. |

### CPU

The Connector sizes its policy evaluation worker pool to `GOMAXPROCS`.
Go sets `GOMAXPROCS` from the container CPU limit ([Go 1.25 release notes](https://go.dev/doc/go1.25#container-aware-gomaxprocs), container-aware `GOMAXPROCS`).
A higher CPU limit gives more parallel policy evaluations.

Allocate whole CPU cores.
With fractional CPU limits, CPU throttling raises latency and causes timeouts during peaks.

### Memory

These factors add to memory use beyond the base process:

* **Log buffer:** The Connector buffers up to 400 MB of logs in memory before it [spools them to disk](https://docs.formal.ai/docs/guides/core-concepts/connectors/operations.md#log-spool).
* **LLM requests:** The Connector reads each non-streaming LLM request body whole to evaluate policies on it.
* **HTTP request bodies:** The Connector buffers HTTP request bodies up to 1 MB so it can retry them when an upstream closes an HTTP/2 connection.
* **Logged bodies:** Each HTTP log keeps at most 500 KB of request and response body, shared between both.

Peak memory scales with concurrency times payload size.
For example, 1,000 concurrent LLM requests with 400 KB bodies hold about 400 MB of request bodies alone.

### Disk

Disk only holds the log spool, used when logs cannot reach the Control Plane.
Size it for your log rate and the outage length you want to cover.
See [Log Spool](https://docs.formal.ai/docs/guides/core-concepts/connectors/operations.md#log-spool).

## Default Sizes in Formal Templates

Formal's deployment templates start from these sizes.
They are starting points, not tested capacity limits. Confirm them with a load test.

| Template | CPU | Memory | Instances |
| - | - | - | - |
| [Connector Helm chart](https://github.com/formalco/helm-charts/tree/main/charts/connector) defaults | 1 request, 2 limit | 2 Gi request, 4 Gi limit | 2 replicas |
| Helm values generated by the Control Plane | 4 request, 8 limit | 8 Gi request, 16 Gi limit | 2 replicas |
| [AWS ECS Terraform example](https://github.com/formalco/terraform-provider-formal/tree/main/examples/deployments/aws/connector) | 1 vCPU (`1024` units) | 2 GB | 3 desired, autoscaling from 1 to 20 |
| AWS CloudFormation template generated by the Control Plane | 1 vCPU (`1024` units) | 2 GB | 1 desired, autoscaling from 1 to 20 |

## Scale and High Availability

### Run at Least Two Instances

Run at least two instances behind a load balancer, spread across availability zones.
A single instance drops every session when it restarts or fails.
See [Disaster Recovery](https://docs.formal.ai/docs/guides/core-concepts/connectors/operations.md#disaster-recovery).

Instances that serve the same Connector can form a [cluster](https://docs.formal.ai/docs/guides/core-concepts/connectors/clustering.md).
Clustering shares state, such as rate limit counters, across instances.

### Scale Out on CPU and Memory

The ECS Terraform example and the CloudFormation template use target tracking autoscaling:

* **CPU:** Scale to keep average CPU at 60%.
* **Memory:** Scale to keep average memory at 70%.
* **Wait time:** Wait 300 seconds between scale-in and scale-out steps.

The Connector Helm chart does not create a `HorizontalPodAutoscaler`.
To autoscale on Kubernetes, add one with the chart's `extraManifests` value or your own manifests.

> [!NOTE]
>
> Base memory autoscaling on container memory against its limit.
> Do not use `formal.connector.memory.usage_percent`; see [Metrics to Watch](#metrics-to-watch).

### Plan for Long-Lived Connections

A load balancer assigns each new TCP connection to one instance.
New instances only receive new connections, so scaling out does not move open database sessions or LLM streams.
Scale out before peaks, and keep enough headroom for the instances already holding sessions.

When an instance stops, it does not wait for open sessions to finish.
To drain sessions, see [Graceful Shutdown](https://docs.formal.ai/docs/guides/core-concepts/connectors/operations.md#graceful-shutdown).

## Metrics to Watch

Watch these signals during load tests and in production.

| Signal | Source | What to look for |
| - | - | - |
| CPU usage against the limit | Container runtime (ECS, Kubernetes, Docker) | Sustained use near the limit, or CPU throttling |
| Memory usage against the limit | Container runtime | Growth toward the limit, or out-of-memory restarts |
| `formal.connector.active_connections` | [Connector metrics](https://docs.formal.ai/docs/guides/core-concepts/connectors/health.md#metrics) | Open connections per instance, and imbalance between instances |
| `formal.connector.connections_opened` | Connector metrics | Rate of new connections |
| `formal.connector.instance.heartbeat` | Connector metrics | Gaps, which show restarts or a stalled instance |
| `formal.connector.resource_health_check` | Connector metrics | Upstream failures, so you can rule out the resource |
| Request latency and error rate | Your load generator or clients | Latency overhead against a baseline without the Connector |
| Free disk on `/formal/logs` | Host or volume metrics | Spool growth, which shows logs are not reaching the Control Plane |

The Connector does not emit request latency metrics.
Measure latency at the client, as described in the load-test method below.

`formal.connector.memory.usage_percent` compares memory in use to memory the Go runtime got from the OS.
It ignores the container limit, so values of 70-90% are normal. Do not use it to size memory.

To chart these metrics, import the [Datadog or Grafana dashboard](https://docs.formal.ai/docs/guides/core-concepts/connectors/health.md#datadog-dashboard).

## Load-Test a Connector

Load tests show the Connector overhead and the capacity of one instance for your traffic.
Run them against a test Connector, never against a Connector that serves production users.

### 1. Set Up an Isolated Environment

Deploy a dedicated Connector with the same version, size and listeners as production.
Use the [deployment option](https://docs.formal.ai/docs/guides/core-concepts/connectors/deployment.md#recommended-deployment-options) you run in production.

Run the load generator on a separate host, in the same VPC and availability zone as the Connector.
Point the Connector at a mock upstream, so you do not load a real database or pay for LLM tokens.

Start with one Connector instance. Per-instance capacity tells you how many instances you need.

**Verify:**

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
curl -s -o /dev/null -w "%{http_code}\n" "http://<CONNECTOR_HOST>:8080/ready"
# Expected: 200
```

### 2. Mirror Production Configuration

Apply the same configuration you plan to run in production:

* **Policies:** The same policies, since policy complexity drives CPU use.
* **Log configuration:** The same [log configuration](https://docs.formal.ai/docs/guides/observability/logs.md), including body capture and [policy evaluation input retention](https://docs.formal.ai/docs/guides/observability/logs.md#policy-evaluation-input-retention).
* **Identity:** A [machine user](https://docs.formal.ai/docs/guides/core-concepts/identities.md) and, if used, a native user with injected credentials.
* **Requests:** The same headers, paths and body sizes as real clients.

Send real client headers, because the Connector uses them to detect protocols.
For example, the Connector detects Anthropic traffic from the `anthropic-version` header.
Without it, LLM policies do not see the model or messages.

**Verify:** Send one request through the Connector.
Open [Logs](https://app.formal.ai/logs) and confirm it shows the expected user, resource and policy results.

### 3. Measure a Baseline

Run each test twice with the same load: once against the mock upstream directly, and once through the Connector.
The difference in latency and errors is the Connector overhead.

This [k6](https://grafana.com/docs/k6/latest/) script (open source load-testing tool) ramps HTTP traffic against a target URL.
It ramps for one minute, then holds each rate for five minutes:

```javascript theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
import http from "k6/http";
import { check } from "k6";

export const options = {
  scenarios: {
    ramp: {
      executor: "ramping-arrival-rate",
      startRate: 10,
      timeUnit: "1s",
      preAllocatedVUs: 200,
      stages: [
        { target: 50, duration: "1m" },
        { target: 50, duration: "5m" },
        { target: 100, duration: "1m" },
        { target: 100, duration: "5m" },
        { target: 200, duration: "1m" },
        { target: 200, duration: "5m" },
      ],
    },
  },
};

const body = JSON.stringify({ input: "x".repeat(50 * 1024) });

export default function () {
  const res = http.post(`${__ENV.TARGET_URL}/v1/test`, body, {
    headers: {
      "Content-Type": "application/json",
      "X-Formal-User-Username": __ENV.FORMAL_USERNAME,
      "X-Formal-User-Password": __ENV.FORMAL_PASSWORD,
    },
  });
  check(res, { "status is 2xx": (r) => r.status >= 200 && r.status < 300 });
}
```

Run it against the mock, then through the Connector:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
TARGET_URL="http://<MOCK_HOST>:<MOCK_PORT>" k6 run load.js
```

Enter the machine user secret at the prompt. It stays out of your shell history and process arguments:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
printf "Machine user secret: " && read -rs FORMAL_PASSWORD && echo
```

Then run the test through the Connector:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
FORMAL_USERNAME="<MACHINE_USER>" FORMAL_PASSWORD="$FORMAL_PASSWORD" \
  TARGET_URL="https://<CONNECTOR_HOST>:<LISTENER_PORT>" k6 run load.js
```

k6 reads `TARGET_URL` and the credentials from environment variables.
The credentials are not exported, so later runs against the mock do not send them.
Use `https://` if the listener has a [TLS certificate](https://docs.formal.ai/docs/guides/core-concepts/connectors/tls.md), and `http://` otherwise.
Replace the path and body with requests that match your clients.

**Verify:** k6 prints `http_req_duration` percentiles and the `checks` pass rate for each run.

### 4. Ramp Load and Change One Variable at a Time

Increase the request rate in steps, and hold each step for several minutes.
The k6 summary combines all steps of a run.
To get latency percentiles for one rate, run a test at that rate alone with the `constant-arrival-rate` executor.
Change one variable per run: request rate, body size, streaming, or policy set.
This shows which factor limits capacity.

Stop raising load at the first of these signs:

* p99 latency rises well above the baseline
* Errors or timeouts appear
* CPU stays near its limit, or CPU throttling appears
* Memory approaches its limit, or the container restarts

The last step before these signs is the capacity of one instance for that traffic.

**Verify:** Check the [metrics](#metrics-to-watch) for each step, and match them to the latency the load generator reports.

### 5. Choose Size and Instance Count

Divide your expected peak load by the per-instance capacity.
Add headroom for one failed instance or availability zone, and for traffic growth.
Deploy at least two instances in production.

If memory limits capacity before CPU does, give each instance more memory.
If CPU limits capacity, add whole cores or add instances.

### 6. Clean Up

Each test request produces a log in your Formal organization.
Delete the test Connector, its resources and its machine user after the test.

**Verify:** The test Connector no longer appears on the [Connectors](https://app.formal.ai/connectors) page.

## Troubleshooting

> [accordion] The Connector restarts with out-of-memory errors
>
> **Cause:** Concurrent large payloads, many open streams, or a growing log buffer exceed the memory limit.
> **Fix:** Raise the memory limit, or run more instances so each holds fewer concurrent requests.
> Check that logs reach the Control Plane, since undelivered logs stay in memory up to 400 MB.

> [accordion] Latency spikes under load while CPU looks low
>
> **Cause:** The container has a fractional CPU limit and is throttled.
> **Fix:** Allocate whole CPU cores, and check throttling metrics from your container runtime.

> [accordion] New instances receive no traffic after scaling out
>
> **Cause:** Existing clients keep their long-lived connections on the original instances.
> **Fix:** Expect new instances to take only new connections. Scale out before peaks.

> [accordion] LLM policies do not match during the load test
>
> **Cause:** The test requests lack the headers or paths that real clients send, so the Connector cannot parse them.
> **Fix:** Copy headers such as `anthropic-version` and the request path from a real client request.

> [accordion] The disk fills up during the test
>
> **Cause:** Logs cannot reach the Control Plane fast enough, so they spool to `/formal/logs`.
> **Fix:** Check Control Plane connectivity, and size the spool volume for your log rate.

## Next Steps

> [card] [Deployment](https://docs.formal.ai/docs/guides/core-concepts/connectors/deployment.md)
>
> Infrastructure and network requirements

> [card] [Health](https://docs.formal.ai/docs/guides/core-concepts/connectors/health.md)
>
> Collect Connector metrics and logs

> [card] [Clustering](https://docs.formal.ai/docs/guides/core-concepts/connectors/clustering.md)
>
> Share state across instances

> [card] [Operations](https://docs.formal.ai/docs/guides/core-concepts/connectors/operations.md)
>
> Upgrades, health checks and recovery


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