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

# Runlayer Operator (Kubernetes)

> Deploy Runlayer on EKS or GKE with the unified runlayer-operator — dependencies, cluster requirements, Helm install, secrets, and RunlayerInstance CR

The unified **Runlayer operator** reconciles two custom resources in one controller:

| CRD | Purpose |
| - | - |
| `RunlayerInstance` | Tenant platform stack (backend, frontend, worker, migrations, optional components) |
| `MCPServer` | Hosted MCP server Deployments (Runlayer Deploy) |

Use this path for **one or many isolated tenants** on a Kubernetes cluster (EKS or GKE).

> [!WARNING]
>
> Do **not** install the unified operator on a cluster that already runs `runlayer-deploy-operator`. Both reconcile `MCPServer` CRs.

## End-to-end flow

```mermaid theme={null}
flowchart LR
  A[1. Cluster + deps] --> B[2. Install operator]
  B --> C[3. Namespace + Secrets]
  C --> D[4. RunlayerInstance CR]
  D --> E[5. Ready + Ingress]
```

1. Provision cluster features and **external** per-tenant dependencies (Postgres, Redis, buckets, IAM / Workload Identity, streams).
2. Install the `runlayer-operator` Helm chart once per cluster.
3. Create (or let the operator create) the platform namespace and seed required Secrets.
4. Apply a `RunlayerInstance` (raw YAML, optional `runlayer-instance` Helm chart, or Terraform on AWS).
5. Wait for `status.phase: Ready`, point DNS at the load balancer, then create `MCPServer` CRs if using Runlayer Deploy.

Supporting guides (read before install):

| Guide | Purpose |
| - | - |
| [Kubernetes prerequisites](https://docs.runlayer.com/deployment/kubernetes-prerequisites.md) | Cluster requirements (EKS + GKE) — you provision the cluster |
| [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md) | Postgres, Redis, buckets, streams + sample Terraform |
| [Runlayer-provided inputs](https://docs.runlayer.com/deployment/runlayer-provided-inputs.md) | Credentials and artifacts from Runlayer |
| [Workload identity](https://docs.runlayer.com/deployment/workload-identity.md) | ServiceAccount → IRSA / Workload Identity permission matrix |

***

## 1. External dependencies

The operator does **not** provision cloud infrastructure. Each tenant needs the following out-of-band (Terraform, console, or your platform).

### Required for every tenant

| Dependency | Purpose | AWS | GCP |
| - | - | - | - |
| **PostgreSQL** | Primary datastore | Aurora / RDS PostgreSQL (recommended) | Cloud SQL for PostgreSQL |
| **Redis** | Cache / queues | ElastiCache (TLS recommended) | Memorystore for Valkey (cluster mode disabled) |
| **WorkOS** | Auth (`AUTH_CLIENT_ID`, `AUTH_API_KEY`) | Same (SaaS) | Same (SaaS) |
| **App crypto secrets** | `SECRET_KEY`, `MASTER_SALT` (≥32 chars in production) | Secrets Manager → K8s Secret | Secret Manager → K8s Secret |
| **Container images** | Backend, frontend, worker (+ optionals) | ECR (or Runlayer registry) | Artifact Registry / mirrored images |
| **DNS + TLS** | Public hostname = `spec.domain` | Route 53 + ACM (typical) | Cloud DNS + Google-managed / cert-manager cert |

Network: cluster nodes (or pods via CNI) must reach Postgres and Redis on private connectivity (VPC, Private Service Connect, peering). Tighten egress with `spec.security.networkPolicy.additionalEgressRules` once CIDRs are known.

Configure time synchronization on cluster nodes; Runlayer pods inherit the node clock. Use the cloud provider's local time service (Amazon Time Sync on AWS; Google's internal NTP service on GCP), or your approved internal source. The operator does not configure host NTP.

### Optional (feature-dependent)

| Dependency | When needed | AWS | GCP |
| - | - | - | - |
| **Object storage** | Audit payload offload, tool-output offload, profiler, binary packages, SIEM export | S3 buckets | GCS buckets |
| **Audit stream + consumer** | `components.auditConsumer.enabled` | Kinesis Data Streams + EFO consumer, DynamoDB checkpoint table, DLQ S3 bucket | Pub/Sub subscription, DLQ GCS bucket |
| **SIEM export** | `components.siemExport.enabled` | Same stream pattern + destination S3 bucket | Pub/Sub + destination GCS bucket |
| **Session materializer** | `components.sessionMaterializer.enabled` | Hook-events Kinesis + DynamoDB checkpoints + DLQ S3 + session-payloads S3 | Hook-events Pub/Sub topic+subscription + DLQ GCS + session-payloads GCS |
| **Agent sandbox runtime** | `spec.agents.sandboxMode` | Lambda function, or Bedrock AgentCore runtime (+ execution role, optional VPC/PrivateLink) | In-cluster [kubernetes-sigs Agent Sandbox](https://agent-sandbox.sigs.k8s.io/) (`sandboxMode: k8s`) — see [K8s Agent Sandbox](#k8s-agent-sandbox-sandboxmode-k8s) |
| **IAM for pods** | Bedrock, S3, Kinesis, Secrets Manager, etc. | **IRSA** roles annotated on ServiceAccounts | **Workload Identity** GSA bound to KSA |
| **GPU nodes** | ToolGuard with `gpu.enabled: true` (default) | GPU node group + NVIDIA device plugin | GPU node pool / Autopilot accelerator allowlist + NVIDIA drivers |
| **Topic CPU / ToolGuard model images** | `components.topicCpu` / `toolguard` | Customer Distribution `088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer/toolguard` pins | Same (or GAR mirror) |
| **LLM gateway image + user API key Secret** | `components.llmGateway` | Customer Distribution `runlayer/llm-gateway` + K8s Secret with personal API key | Same |
| **MCP telemetry** | Deploy telemetry sidecar | OTLP collector endpoint reachable from MCP pods | Same |
| **OTEL collector sidecar** | `spec.otelCollector.enabled` | Reachable OTLP backends (Mimir/Tempo/etc.) | Same |
| **Ingress controller** | `spec.ingress.enabled` or external Ingress | AWS Load Balancer Controller (`alb`) | GKE Ingress (`gce` / `gce-internal`) or nginx |
| **Encrypted worker-node volumes** | Audit log spool (on by default) — holds pre-redaction payloads on node disk | Encrypted EBS node volumes | CMEK / Google-managed node-disk encryption |
| **cert-manager** | Optional TLS via Certificate CR | ClusterIssuer / Issuer you own | Same (or use ManagedCertificate) |

Sample Terraform for Postgres, Redis, buckets, streams, and identity is embedded in [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md) and [Workload identity](https://docs.runlayer.com/deployment/workload-identity.md) (AWS and GCP side by side). Adapt the samples to your IaC — Runlayer does not require a specific Terraform module.

### Shared GCP project

When any component uses `streamBackend: pubsub`, set one project for the instance:

```yaml theme={null}
spec:
  gcp:
    projectId: acme-prod   # sets GCP_PROJECT_ID once on platform workloads
```

Do not put `projectId` on per-component `pubsub` blocks (subscription / DLQ only).

### Identity model (IRSA / Workload Identity)

The operator creates dedicated ServiceAccounts per workload and never embeds long-lived cloud keys. Annotate via `spec.serviceAccount`:

| SA (name pattern) | Typical permissions |
| - | - |
| `{instance}-backend` | S3 (audit/tool-output/profiler/packages), Bedrock, optional SM; with **session materializer** enabled: hook-events **publish** (Kinesis PutRecord / Pub/Sub publish) + session-payload bucket **read**, plus **write** under `session-media/` |
| `{instance}-worker` | Same class of AWS/GCP APIs the worker needs; with **session materializer** enabled: same hook-events **publish** + session-payload **read** and `session-media/` **write** as backend |
| `{instance}-audit-consumer` | Kinesis/DynamoDB/S3 **or** Pub/Sub + GCS DLQ |
| `{instance}-siem-export` | Stream read + destination bucket write |
| `{instance}-session-materializer` | Shared by the ingest and compactor Deployments: hook-events stream read + payload bucket R/W + DLQ write (Kinesis/DynamoDB/S3 **or** Pub/Sub/GCS) |

**AWS (IRSA):**

```yaml theme={null}
spec:
  serviceAccount:
    backend:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-backend
    worker:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-worker
    auditConsumer:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-audit-consumer
    siemExport:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-siem-export
    sessionMaterializer:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-session-materializer
```

**GCP (Workload Identity):**

```yaml theme={null}
spec:
  serviceAccount:
    backend:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-backend@PROJECT.iam.gserviceaccount.com
    worker:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-worker@PROJECT.iam.gserviceaccount.com
    auditConsumer:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-audit@PROJECT.iam.gserviceaccount.com
    siemExport:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-siem@PROJECT.iam.gserviceaccount.com
    sessionMaterializer:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-session-materializer@PROJECT.iam.gserviceaccount.com
```

Prefer WI/IRSA over ECS-style assume-role env vars (`AUDIT_LOG_SIEM_EXPORT_ASSUME_ROLE_ARN` is not the K8s path).

### Saved Bedrock providers for monitor consumers

The EKS application policy already grants scoped saved-Bedrock role assumption for separately provisioned monitor consumers.
Additional ServiceAccounts need explicit `application_irsa_additional_service_accounts` trust and matching role annotations.
The saved provider role must trust that AWS identity with its configured external ID and grant model access; GKE consumers also need an AWS credential source because GCP Workload Identity does not authenticate to AWS.

***

## 2. Cluster requirements

### Kubernetes version

| Requirement | Value |
| - | - |
| **Minimum** | **1.29+** (Helm `kubeVersion`; native sidecars / KEP-753 for optional OTEL collector) |
| **Recommended** | Latest EKS / GKE stable (Runlayer EKS module defaults to **1.35**) |

### Shared features (EKS and GKE)

| Feature | Why |
| - | - |
| Helm **3.8+**, `kubectl` with cluster-admin (or equivalent) | Install CRDs + ClusterRole |
| CNI with **NetworkPolicy** support | Default isolation; Calico / Cilium / VPC CNI + policy engine as applicable |
| Ability to pull app images | ECR/GAR auth, imagePullSecrets, or public mirrors |
| DNS resolution from pods | CoreDNS; private hosted zones / Cloud DNS for RDS/Redis hostnames |
| Persistent outbound HTTPS | WorkOS, Sentry (optional), catalog API, upstream MCP SaaS |
| Metrics server | Required if you enable HPA (`spec.autoscaling`) |

### EKS-specific

| Item | Notes |
| - | - |
| **AWS Load Balancer Controller** | For `ingressClassName: alb`, Gateway class `alb`, or Terraform ALB Ingress. Gateway API also needs the LBC Gateway CRDs (`LoadBalancerConfiguration`, `TargetGroupConfiguration`). |
| **EBS CSI** (if needed) | Not required by core platform pods (stateless); may be needed by add-ons |
| **OIDC provider + IRSA** | Annotate workload SAs as above |
| **Managed node groups** | Size for backend defaults (\~4 CPU / 8 Gi) or override `components.*.resources` |
| **GPU node group** | Only if ToolGuard GPU enabled |
| **Security groups** | Allow nodes → RDS/Redis; ALB → NodePort/target groups for backend:8000 / frontend:80 |

See [Kubernetes prerequisites](https://docs.runlayer.com/deployment/kubernetes-prerequisites.md) for the full cluster contract.

### GKE-specific

| Item | Notes |
| - | - |
| **GKE Ingress / Gateway** | Ingress class `gce` or `gce-internal`, or Gateway class `gke-l7-*`. Install the Gateway API CRDs for `spec.gateway`. Regional classes (`gke-l7-rilb`, `gke-l7-regional-external-managed`) also need an active proxy-only subnet in the same region and VPC. The operator does not create it. |
| **Workload Identity** | Enable on cluster; bind KSAs to GSAs |
| **BackendConfig CRD** | Used when `spec.ingress.gcp.backendConfig` is enabled (default for `gce*`) |
| **ManagedCertificate** | Optional Google-managed TLS via `spec.ingress.gcp.managedCertificate` |
| **Private clusters** | Ensure Cloud SQL Auth Proxy / PSC / authorized networks so pods reach SQL/Redis |
| **GPU pools** | Same ToolGuard considerations |

### Namespace layout

| Namespace | Contents |
| - | - |
| `runlayer-system` | Operator Deployment; typically all `RunlayerInstance` CRs |
| `runlayer-<customerId>` | Platform workloads + platform Secrets (default) |
| `runlayer-<customerId>-mcps` | `MCPServer` CRs + MCP Deployments (when `deploy.enabled`) |

Override with `spec.deploy.platformNamespace` / `spec.deploy.mcpNamespace`.

***

## 3. Install and upgrade the operator

### Install (once per cluster)

Copy and customize values:

```bash theme={null}
# After `helm pull` / chart unpack, copy values.example.yaml from the chart
cp values.example.yaml values-runlayer-operator.yaml
```

**OCI (Customer Distribution — production):** versions declared production-ready via
the `runlayer-operator-promote-customer-distribution` workflow.

```bash theme={null}
helm upgrade --install runlayer-operator \
  oci://088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer-helm-charts/runlayer-operator \
  --version <chart-version> \
  --namespace runlayer-system --create-namespace \
  -f values-runlayer-operator.yaml
```

**OCI (staging / pre-promote):** continuous push on `main` in account `412677576004`.
Override `image.repository` to the staging operator image when using those charts.

```bash theme={null}
helm upgrade --install runlayer-operator \
  oci://412677576004.dkr.ecr.us-east-1.amazonaws.com/runlayer-helm-charts/runlayer-operator \
  --version <chart-version> \
  --namespace runlayer-system --create-namespace \
  -f values-runlayer-operator.yaml \
  --set image.repository=412677576004.dkr.ecr.us-east-1.amazonaws.com/runlayer-operator
```

Use the Customer Distribution OCI chart for production installs. Runlayer can share a chart tarball if OCI pull is blocked in your environment.

CRDs ship in the chart `crds/` directory and are applied on **first** `helm install` only:

* `platform.runlayer.com/v1alpha1` — `RunlayerInstance`
* `deploy.runlayer.com/v1alpha1` — `MCPServer`

### Common operator values

| Values key | Purpose |
| - | - |
| `image.repository` / `image.tag` | Operator image |
| `leaderElection.enabled` | Default `true`; keep on when `replicaCount > 1` |
| `telemetryProxy.*` | Cluster-wide MCP telemetry sidecar defaults (overridable per tenant) |
| `mcpWorkloads.dedicatedNodes.*` | Fallback MCP node scheduling |
| `otel.*` | Operator traces |
| `metrics.*` | Controller metrics + optional Prometheus `ServiceMonitor` |

Full values reference ships with the Helm chart you install from Customer Distribution ECR (`values.example.yaml` in the chart package).

### Upgrading the operator (manual CRD apply)

Helm **does not upgrade CRDs** on subsequent releases. When a release notes CRD schema changes, apply CRDs **before** upgrading the chart:

```bash theme={null}
# Extract CRDs from the same chart version you are upgrading to, then:
kubectl apply --server-side --force-conflicts \
  -f crds/platform.runlayer.com_runlayerinstances.yaml
kubectl apply --server-side --force-conflicts \
  -f crds/deploy.runlayer.com_mcpservers.yaml

helm upgrade runlayer-operator \
  oci://088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer-helm-charts/runlayer-operator \
  --version <new-chart-version> \
  --namespace runlayer-system \
  -f values-runlayer-operator.yaml
```

If CRDs were never Helm-managed, plain `kubectl apply -f ...` is enough.

> [!TIP]
>
> Always apply CRDs from the **same chart version** you are upgrading to. Skipping CRD apply can leave the controller unable to reconcile new fields.

> [!WARNING]
>
> **Action required for chart `0.2.67` before using audit consumer scaling:** this version adds `spec.autoscaling.auditConsumer` to the `RunlayerInstance` CRD and allows Kinesis `components.auditConsumer.replicas` above 1.
>
> * **Upgrade:** apply the `0.2.67` CRDs before `helm upgrade`, as shown above. The old CRD silently drops `autoscaling.auditConsumer` (no HPA gets created) and still rejects `replicas` above 1.
> * **Rollback below `0.2.67`:** first set `components.auditConsumer.replicas` to the current pod count, remove `autoscaling.auditConsumer`, and wait for the operator to delete `audit-consumer-hpa`. An older operator neither manages nor deletes that HPA, so the two fight over the replica count and every change moves shard leases.

> [!WARNING]
>
> **Action required for chart `0.2.61` with `components.siemExport` on Kinesis:** this version rolls SIEM export start-before-stop. On a Runlayer backend older than `1.28.775`, keep one replica and expect each deploy to export its in-flight batch twice (never loss; dedupe on `audit_log_id`) until the backend is upgraded. See [Optional components](#optional-components-snippet) below.

***

## 4. Prerequisites: namespace and Secrets

### Install order for Secrets

The operator **never creates, reads, or syncs Secret data** (no `secrets` write RBAC). You must create Secrets in the **platform namespace**.

Two workable sequences:

| Sequence | Steps |
| - | - |
| **A — Namespace first (recommended for GitOps/TF)** | Create `runlayer-<customerId>` → create Secrets → apply `RunlayerInstance` |
| **B — CR first** | Apply `RunlayerInstance` (operator creates namespaces) → create Secrets → operator retries until Ready |

Many teams use sequence **A** with their own Terraform syncing Secrets Manager / Secret Manager into the platform namespace.

### Required Secrets (platform namespace)

| Secret | Keys | CR reference |
| - | - | - |
| `runlayer-db` | `username`, `password` | `database.credentials.*From` |
| `runlayer-redis` | `REDIS_URL`: `rediss://:<token>@<host>:6379/0`, with the token percent-encoded | `redis.credentials.urlFrom` |
| `runlayer-auth` | `AUTH_CLIENT_ID`, `AUTH_API_KEY` | `auth.clientIdFrom`, `auth.apiKeyFrom` |
| `runlayer-app` | `SECRET_KEY`, `MASTER_SALT`, `OPENFEATURE_PROVIDER`, `DISTRIBUTION_API_URL`, `DISTRIBUTION_API_KEY`, `MCP_CATALOG_API_KEY` (+ [optional keys](#common-optional-keys)) | `appSecretRef.name` |

Before creating `runlayer-app`, obtain a Distribution reader key registered and active for this deployment from Runlayer. Set all three Distribution settings below so feature flags use Distribution.

Example (sequence A):

```bash theme={null}
kubectl create namespace runlayer-acme

kubectl create secret generic runlayer-db -n runlayer-acme \
  --from-literal=username='runlayer' \
  --from-literal=password='…'

kubectl create secret generic runlayer-redis -n runlayer-acme \
  --from-literal=REDIS_URL='rediss://:…@acme-redis.xxx.cache.amazonaws.com:6379/0'

kubectl create secret generic runlayer-auth -n runlayer-acme \
  --from-literal=AUTH_CLIENT_ID='…' \
  --from-literal=AUTH_API_KEY='…'

kubectl create secret generic runlayer-app -n runlayer-acme \
  --from-literal=SECRET_KEY='…' \
  --from-literal=MASTER_SALT='…' \
  --from-literal=OPENFEATURE_PROVIDER='flagd' \
  --from-literal=DISTRIBUTION_API_URL='https://distribution.prod.runlayer.com' \
  --from-literal=DISTRIBUTION_API_KEY='…' \
  --from-literal=MCP_CATALOG_API_KEY='…'   # required — from Runlayer
```

### MCP Catalog (required)

Onboarding calls the MCP Catalog API. Without a key, `GET /api/v1/catalog/` returns `503` and setup shows **“Couldn't load setup status”**.

| Setting | Default / source |
| - | - |
| `MCP_CATALOG_API_URL` | Backend default: `https://mcp-catalog.prod.runlayer.com`. Override via `runlayer-app` if Runlayer directs (e.g. staging). Operator injects the in-cluster URL only when `components.mcpCatalogApi.enabled`. |
| `MCP_CATALOG_API_KEY` | **Empty by default.** Put the Runlayer-issued key on `runlayer-app` as `MCP_CATALOG_API_KEY`. |

Contact Runlayer for the key — see [Runlayer-provided inputs](https://docs.runlayer.com/deployment/runlayer-provided-inputs.md).

### AI Watch binary distribution (when using AI Watch)

Installer resolution needs a Runlayer download token, a customer-owned object-storage cache, and workload permission to that cache. Without them the UI reports **“No AI Watch installer is currently resolved”**.

| Input | Who | Where |
| - | - | - |
| `RUNLAYER_DOWNLOAD_TOKEN` | Runlayer | `runlayer-app` Secret |
| `BINARY_PACKAGES_S3_BUCKET` (AWS) / GCS equivalent | You | `runlayer-app` (+ IAM on `{instance}-backend` / `-worker`) |

After setting these, restart backend/worker and run release discovery (**Check now** or the scheduled poll). Details: [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md#ai-watch-binary-packages) and [Workload identity](https://docs.runlayer.com/deployment/workload-identity.md).

### Optional component Secrets

| Secret | When | Keys |
| - | - | - |
| `runlayer-catalog` | `components.mcpCatalogApi.enabled` | `API_KEY`; optional `SENTRY_DSN` |
| `runlayer-sentry-relay` | `components.sentryRelay.enabled` | `public_key`, `secret_key`, `id` (key names configurable) |
| `runlayer-llm-gateway` | `components.llmGateway.enabled` | User/personal API key (conventional key `apiKey`) — **not** an org key; holder needs `MANAGE_ORG_SETTINGS` |
| TLS Secret | Manual / cert-manager ingress | Referenced by `spec.ingress.tls.secretName` |

### App secret

Platform Secret named `runlayer-app` by convention (`spec.appSecretRef.name`). Mounted with `envFrom` on **backend** and **worker** (and related backend-image jobs). **Every key** in the Secret becomes an environment variable.

#### Required keys

| Key | Purpose |
| - | - |
| `SECRET_KEY` | JWT / session signing (min 32 characters in production) |
| `MASTER_SALT` | Encryption salt (min 32 characters in production) |
| `OPENFEATURE_PROVIDER` | Set to `flagd` to use Distribution-backed feature flags. Required for this deployment setup; omitting it leaves feature flags on WorkOS. |
| `DISTRIBUTION_API_URL` | Set to `https://distribution.prod.runlayer.com` unless Runlayer provides a different URL. Allow outbound HTTPS to this endpoint. |
| `DISTRIBUTION_API_KEY` | Runlayer-issued Distribution API reader credential for deployment configuration, including feature flags and licensing. Runlayer must register and activate the key for this deployment before startup. |
| `MCP_CATALOG_API_KEY` | **Required** for onboarding. Empty by default — obtain from Runlayer and set on `runlayer-app`. Hosted catalog URL defaults to `https://mcp-catalog.prod.runlayer.com` in the backend (override via Secret if needed). Do not enable in-cluster `components.mcpCatalogApi` for the standard customer path. |

#### Common optional keys

| Key | Purpose |
| - | - |
| `SENTRY_DSN` | Error reporting (if not using relay-only) |
| `PROFILER_API_KEY` | On-demand memory profiling endpoint |
| `RUNLAYER_DOWNLOAD_TOKEN` | Binary release discovery token |
| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | LLM providers when not using Bedrock-only |
| `BEDROCK_ACCESS_KEY_ID` / `BEDROCK_SECRET_ACCESS_KEY` | Only if not using IRSA/WI for Bedrock |
| `MS_TEAMS_APP_CLIENT_SECRET` | Client secret of the Entra provisioning app backing the Microsoft Teams integration. Only with the non-secret `MS_TEAMS_*` keys below; empty or absent leaves Teams provisioning off |
| `SENDBLUE_API_KEY_ID` / `SENDBLUE_API_SECRET_KEY` | The iMessage line's Sendblue API key pair. Only with `IMESSAGE_CHANNEL_ENABLED` |
| `SENDBLUE_WEBHOOK_SECRET` | The secret set on the iMessage line's Sendblue `receive` webhook; the backend rejects webhook calls without it. Only with `IMESSAGE_CHANNEL_ENABLED` |

`AUTH_API_KEY` may also appear here; it is **also** injected from `spec.auth.apiKeyFrom` (duplicate is harmless).

With `terraform-runlayer-instance`, the module copies `RESEND_API_KEY` from the tenant Secrets Manager secret into this Secret (empty when that key is absent); a key added to the Kubernetes Secret by hand is overwritten on the next apply, so put it in Secrets Manager: `initial_tenant_secrets.resend_api_key` on the dependencies module for a new tenant, or edit the existing tenant secret directly (the bootstrap resource ignores later changes).

#### Common non-secret configuration via the same Secret

Because `envFrom` loads all keys, teams often put **non-sensitive** settings in `runlayer-app` as well (or use a separate ConfigMap pattern outside the operator). Typical production keys:

| Key | Example / notes |
| - | - |
| `AWS_REGION` / `AWS_DEFAULT_REGION` | e.g. `us-east-1` |
| `BEDROCK_ENABLED` | `true` / `false`. Drives Runlayer Assistant inference (see below). |
| `BEDROCK_REGION` | e.g. `us-east-1` |
| `BEDROCK_ASSUME_ROLE_TRUSTED_AWS_ACCOUNT_ID` | Account ID for customer Bedrock roles |
| `BEDROCK_AUTO_MODEL_ACCESS` | `true` / `false` (default `true`). When `true`, the backend submits Anthropic's Bedrock use-case form and accepts the model agreement at startup/login. Set `false` to keep that a manual console step |
| `BEDROCK_MODEL_ACCESS_COMPANY_NAME` | Company named on that form (default `Runlayer`). Override for a self-managed install; form is submit-once |
| `BEDROCK_MODEL_ACCESS_COMPANY_WEBSITE` | Website named on that form (default `https://runlayer.com`) |
| `BEDROCK_MODEL_ACCESS_INDUSTRY` | Industry named on that form (default `Software as a Service`) |
| `BEDROCK_MODEL_ACCESS_INTENDED_USERS` | Intended user count on that form (default `2`) — a deployment-level estimate, not a live count |
| `AUDIT_PAYLOAD_S3_BUCKET` | Large audit payload offload. The same bucket also receives audit-spool dead letters exported (redacted) by the backend under `audit-spool-dead-letters/`; that evidence expires after 30 days (S3 lifecycle rule) — replay dead letters, or copy the objects out, before then |
| `TOOL_OUTPUT_S3_BUCKET` | Tool output offload |
| `TOOLGUARD_FEEDBACK_S3_BUCKET` | ToolGuard feedback |
| `PROFILER_S3_BUCKET` | Memray profiles |
| `BINARY_PACKAGES_S3_BUCKET` | Cached binary packages |
| `RUNLAYER_DOWNLOADS_BASE_URL` | Default `https://downloads.runlayer.com` |
| `AWS_CLOUD_DISCOVERY_PRINCIPAL_ARN` | AWS Cloud Discovery: the IAM role customer discovery roles trust. Backend and worker must both run as exactly this role (one IRSA role for both). Empty leaves AWS discovery off |
| `AWS_CLOUD_DISCOVERY_TEMPLATE_BUCKET` | Private bucket holding `aws-cloud-discovery/read-role/v*.json`, readable by that role. Empty leaves AWS discovery off |
| `AWS_CLOUD_DISCOVERY_TEMPLATE_REGION` | That bucket's Region, where Quick Create links open (default `us-east-1`) |
| `MS_TEAMS_APP_CLIENT_ID` | Application (client) ID of the multi-tenant Entra app used to provision per-agent Teams bots |
| `MS_TEAMS_RUNLAYER_TENANT_ID` | Entra tenant owning that app; per-agent Entra apps and Azure Bot resources are created here, never in a customer tenant |
| `MS_TEAMS_AZURE_SUBSCRIPTION_ID` | Azure subscription holding the Bot Service resources |
| `MS_TEAMS_AZURE_RESOURCE_GROUP` | Resource group within that subscription |
| `MS_TEAMS_APP_URL` | Public HTTPS base for the Bot Framework messaging endpoint and admin-consent callback. Defaults to `APP_URL`; set it only when Teams must reach a different host. **Each instance's `{MS_TEAMS_APP_URL}/api/v1/integrations/ms-teams/admin-consent-callback` must be registered as a Redirect URI on the Entra app** or admin consent fails with `AADSTS500113`. Changing it later does **not** move already-provisioned bots: each agent's Azure Bot resource keeps the messaging endpoint captured at provisioning time and must be recreated |
| `IMESSAGE_CHANNEL_ENABLED` | `true` / `false` (default `false`). Shows the Text message card on agent profiles in Go. Also set `SENDBLUE_FROM_NUMBER` (the line's E.164 number) here and the three `SENDBLUE_*` secrets above; without them no agent can turn iMessage on. See [ECS optional features → iMessage channel](https://docs.runlayer.com/deployment/ecs-features.md#imessage-channel) for the Sendblue webhook setup |
| `SENDBLUE_FROM_NUMBER` | The iMessage line's E.164 number, e.g. `+15551234567`. Only with `IMESSAGE_CHANNEL_ENABLED` |
| `DB_POOL_SIZE` / `DB_MAX_OVERFLOW` | Connection pool tuning |
| `CLAUDE_PLATFORM_ORGANIZATION_ID` / `CLAUDE_PLATFORM_SERVICE_ACCOUNT_ID` / `CLAUDE_PLATFORM_FEDERATION_RULE_ID` | **Runlayer-operated deployments only.** Public ids of the Anthropic organization, operator service account and Workload Identity Federation rule Runlayer registers for Claude billing connections. The backend signs its own JWTs for the exchange and publishes the key at `{APP_URL}/.well-known/runlayer-claude-platform.jwks.json`; there is no secret. Leave unset on a self-managed install |
| `CLAUDE_PLATFORM_OAUTH_CLIENT_ID` / `CLAUDE_PLATFORM_CLIENT_AUTH_AUDIENCE` / `CLAUDE_PLATFORM_WORKSPACE_ID` / `CLAUDE_PLATFORM_WIF_SUBJECT` | **Runlayer-operated deployments only.** The Anthropic OAuth app's client ID and client-authentication audience, an optional workspace, and the JWT `sub` (default `runlayer:anthropic-operator:<APP_URL host>`). Leave unset on a self-managed install |
| `RUNLAYER_PRIVATE_CONNECTION_TERRAFORM_TIMEOUT_SECONDS` | Positive finite Terraform command deadline; default `1800` seconds. Applies only to ECS private-connection provisioning, not Kubernetes deployments; setting this does not enable private connections on the operator. |
| `PRE_AUTH_TRUSTED_PROXY_HOPS` | How many trailing `X-Forwarded-For` entries your own proxies append, the client being the first of them (default `1`, at least `1`). Every client-IP decision keys on that entry: per-IP rate limits, the audit `ip_address` and the `meta.request.ip` policy field, so a wrong value also changes which IP-ranged policies match. `1` for ALB or nginx, `2` behind a Google load balancer. The operator sets `2` itself when every enabled edge is a Google load balancer (`gce` / `gce-internal` Ingress, or a `gke-l7-*` Gateway), and that value wins over this Secret. A one-hop class beside a Google edge is rejected. Set the Secret only for an external load balancer. Used when `CLIENT_IP_HEADER` is unset or carries no IP |
| `CLIENT_IP_HEADER` | Header carrying the client IP, set by a trusted proxy (for example `CF-Connecting-IP`). When set and carrying an IP, rate limits, the audit `ip_address` and the `meta.request.ip` policy field read it instead of `X-Forwarded-For`. Default empty |
| `WORKERS` | Uvicorn worker processes (default `4` in non-dev). Recycling below only applies when `WORKERS` ≥ `2` |
| `UVICORN_LIMIT_MAX_REQUESTS` | Recycle each worker after this many requests (default `600000`) to limit ASGI memory growth. Ignored when `WORKERS` is `1`. Memory-tight fleets may pin lower (e.g. shared prod ECS) |
| `UVICORN_LIMIT_MAX_REQUESTS_JITTER` | Random jitter added to the recycle threshold (default `limit_max_requests // 50`, \~`12000` at the default) so workers do not all restart at once |
| `OAUTH_BROKER_URL` | If using oauth-broker |
| `DIRECTORY_SYNC_EVENT_CRON` | Worker directory sync schedule |
| `DIRECTORY_SYNC_EVENT_SYNC_ENABLED` | `true` / `false` |
| `DEBUG_OPS_REQUEST_SIGNING_JWKS` | Trusted production ops-console keys obtained from Runlayer support; see [Runlayer support access](#runlayer-support-access). Once backend signature enforcement is deployed, `/api/v1/debug/*` accepts only requests signed by these keys and encrypts verified responses; unset means no support debug access |

#### Runlayer support access

Runlayer support reaches your deployment's `/api/v1/debug/*` endpoints through the Runlayer ops console, which signs every request. Your backend verifies the signature against your configured trusted keys and encrypts its response so only that request can read it.

Support access also requires `DEBUG_WORKOS_CLIENT_ID` in the `runlayer-app` Secret, configured for Runlayer's ops WorkOS environment, not the tenant's. The backend accepts only tokens from Runlayer's ops WorkOS organization: `DEBUG_ALLOWED_WORKOS_ORG_ID` defaults to it, so leave it unset. For MCP access, coordinate `DEBUG_MCP_AUTHKIT_DOMAIN` with Runlayer support. WorkOS authentication runs before signature verification; signing trust alone does not enable access.

Obtain the reviewed **production** ops-console JWKS from Runlayer support and set its JSON contents as `DEBUG_OPS_REQUEST_SIGNING_JWKS` in the `runlayer-app` Secret (one line is fine). With `terraform-runlayer-instance`, pass the JSON string as `debug_ops_request_signing_jwks`. Do not trust staging console keys in production. Runlayer support coordinates key rotations separately from module releases; publish replacement keys before switching signing keys. Unset, blank, or empty trust disables support debug access once backend signature enforcement is deployed.

Replay protection uses the existing writer Postgres database; the deployment's migration Job creates its table automatically. If replay storage is unavailable, debug requests return 503 without running the handler.

**Runlayer Assistant inference.** `BEDROCK_ENABLED=true` (typical AWS): new/unbound assistants use platform-billed Bedrock (`RUNLAYER_ASSISTANT_BEDROCK_MODEL`; IRSA/WI or `BEDROCK_ACCESS_KEY_ID` / `BEDROCK_SECRET_ACCESS_KEY`). `BEDROCK_ENABLED=false` (typical GCP/GKE): the assistant binds an org AI provider instead — recommended model if one is set, else the custom-agent default, else the oldest provider's first model. Until an admin adds a provider in **Settings → AI Providers**, the assistant is still provisioned but chat is blocked. An admin can change the assistant's model/provider in the agent panel (`MANAGE_ORG_SETTINGS`); a bound org provider is sticky and is not reset when Bedrock is later enabled. Prompt, name, connectors, and skills stay managed.

Any backend `Settings` field (see application config) can be supplied this way. Prefer CR fields for connectivity that the operator already knows how to wire (`database`, `redis`, `auth`, component toggles).

On AWS, when this deployment invokes Anthropic models on Bedrock (`BEDROCK_ENABLED=true`, or Bedrock-backed custom agent models), submit the one-time form in the account those calls come from:

> [!NOTE]
>
> **Anthropic model access.** Anthropic requires a use case details form before its models can be invoked in an AWS account, plus an accepted model agreement. You need this when the deployment invokes Anthropic models on Bedrock — typically `BEDROCK_ENABLED=true` (Runlayer Assistant platform inference and optional Bedrock agent models). With `BEDROCK_ENABLED=false`, Runlayer Assistant binds an org AI provider instead; skip this step unless you also enable Bedrock inference elsewhere (for example `BEDROCK_ANTHROPIC_MODELS_ENABLED` for custom agents).
>
> **The backend does both for you** at startup and on login, in the account the Bedrock calls come from, using the model-access IAM permissions your deployment grants. Four settings describe the deployment on the form — `BEDROCK_MODEL_ACCESS_COMPANY_NAME` (defaults to `Runlayer`, the operator of the software making the calls), `BEDROCK_MODEL_ACCESS_COMPANY_WEBSITE`, `BEDROCK_MODEL_ACCESS_INDUSTRY` and `BEDROCK_MODEL_ACCESS_INTENDED_USERS`. Override them if you run this install yourself. They are never derived from your data: the form is submit-once, so a guessed answer would be permanent.
>
> Set `BEDROCK_AUTO_MODEL_ACCESS=false` to turn this off and do it by hand instead: **Bedrock console → Model catalog → any Anthropic model → Submit use case details**. Do the same if your deployment role predates the model-access permissions — the backend logs exactly which actions it is missing. AWS accepts the form once per account, or once at your AWS Organization's management account, which member accounts inherit.
>
> Deploying outside the US? Also set `RUNLAYER_ASSISTANT_BEDROCK_MODEL` to your geography's inference profile, for example `au.anthropic.claude-opus-4-6-v1` in `ap-southeast-2`. The risk-categorization explainer follows `BEDROCK_REGION` on its own and uses Claude Haiku 4.5 outside the US, so the Anthropic form above covers it; only set `RISK_CATEGORIZATION_MODEL` if you want a different model, and pick one served in your Region. If Bedrock rejects the primary model it falls back to Amazon Nova Lite, which needs no access request.
>
> Access takes up to 15 minutes to propagate. Until it does — or if this is skipped entirely — Bedrock-backed agents fail with `Model use case details have not been submitted for this account`; see [troubleshooting](https://docs.runlayer.com/operations/troubleshooting.md) for the CLI checks and Region caveats.

***

## 5. Deploy a RunlayerInstance

### Required `spec` fields

| Field | Description |
| - | - |
| `customerId` | Tenant id; **immutable**; default ns prefix `runlayer-<customerId>` |
| `domain` | Public hostname (no scheme); **immutable**; drives `APP_URL` / CORS |
| `environment` | Label → `ENVIRONMENT` (`production`, `staging`, …) |
| `version` | App version tag; mirrored to `status.observedVersion` when Ready |
| `images.backend` / `frontend` / `worker` | `repository:tag` |
| `database.host` + `credentials.*From` | Postgres |
| `redis.host` | Redis (credentials optional) |
| `auth.clientIdFrom` / `apiKeyFrom` | WorkOS |
| `appSecretRef.name` | Platform Secret for `envFrom` |

Optional highlights: `database.port` (5432), `database.name` (`runlayer`), `redis.port` / `tls` / `credentials`, `components`, `deploy`, `serviceAccount`, `workloadScheduling`, `security`, `trustedCa`, `autoscaling`, `podDisruptionBudget`, `ingress`, `otelCollector`, `auditSpool`, `extraEnv` (extra environment variables for every backend-image workload; unlike the ECS module's `additional_backend_env_vars`, a name the operator sets itself is rejected rather than overridden). `spec.deploymentTelemetry` is accepted and ignored.

`multiRegion` (`role: primary`, `region: <cloud region>`) marks the instance as a member of a multi-region deployment: backend-image workloads get `RUNLAYER_REGION_ROLE` and a `deployment.region` resource attribute in front of any `OTEL_RESOURCE_ATTRIBUTES` you set in `extraEnv`. Leave it unset unless Runlayer asks you to set it; unset changes nothing. While it is set, declare `OTEL_RESOURCE_ATTRIBUTES` as a literal `extraEnv` value: a `valueFrom` entry is rejected, and a key of that name in the app secret is overridden.

Field-level detail is covered in the sections below and in the supporting guides linked at the top of this page.

### Minimal example (EKS)

```yaml theme={null}
apiVersion: platform.runlayer.com/v1alpha1
kind: RunlayerInstance
metadata:
  name: acme-prod
  namespace: runlayer-system
  labels:
    runlayer.com/customer-id: acme
spec:
  customerId: acme
  domain: acme.example.com
  environment: production
  version: "1.0.0"
  images:
    backend: 123456789012.dkr.ecr.us-east-1.amazonaws.com/runlayer/backend:1.0.0
    frontend: 123456789012.dkr.ecr.us-east-1.amazonaws.com/runlayer/frontend:1.0.0
    worker: 123456789012.dkr.ecr.us-east-1.amazonaws.com/runlayer/worker:1.0.0
  database:
    host: acme-db.cluster-xxx.us-east-1.rds.amazonaws.com
    port: 5432
    name: runlayer
    credentials:
      usernameFrom: { name: runlayer-db, key: username }
      passwordFrom: { name: runlayer-db, key: password }
  redis:
    host: acme-redis.xxx.cache.amazonaws.com
    port: 6379
    tls: true
    credentials:
      urlFrom: { name: runlayer-redis, key: REDIS_URL }
  auth:
    clientIdFrom: { name: runlayer-auth, key: AUTH_CLIENT_ID }
    apiKeyFrom: { name: runlayer-auth, key: AUTH_API_KEY }
  appSecretRef:
    name: runlayer-app
  components:
    backend: { enabled: true, replicas: 2 }
    frontend: { enabled: true, replicas: 2 }
    worker: { enabled: true, replicas: 1 }
  deploy:
    enabled: true
  serviceAccount:
    backend:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-backend
    worker:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/runlayer-acme-worker
  ingress:
    enabled: true
    ingressClassName: alb
    controllerNamespace: aws-load-balancer-controller
    annotations:
      alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:123456789012:certificate/…
      alb.ingress.kubernetes.io/scheme: internet-facing
      alb.ingress.kubernetes.io/target-type: ip
```

### Minimal example (GKE)

```yaml theme={null}
apiVersion: platform.runlayer.com/v1alpha1
kind: RunlayerInstance
metadata:
  name: acme-prod
  namespace: runlayer-system
spec:
  customerId: acme
  domain: acme.example.com
  environment: production
  version: "1.0.0"
  images:
    backend: us-east1-docker.pkg.dev/PROJECT/runlayer/backend:1.0.0
    frontend: us-east1-docker.pkg.dev/PROJECT/runlayer/frontend:1.0.0
    worker: us-east1-docker.pkg.dev/PROJECT/runlayer/worker:1.0.0
  database:
    host: 10.x.x.x   # Cloud SQL private IP or PSC endpoint
    credentials:
      usernameFrom: { name: runlayer-db, key: username }
      passwordFrom: { name: runlayer-db, key: password }
  redis:
    host: 10.y.y.y   # Memorystore for Valkey primary endpoint
    port: 6379
    tls: true
    credentials:
      urlFrom: { name: runlayer-redis, key: REDIS_URL }
  auth:
    clientIdFrom: { name: runlayer-auth, key: AUTH_CLIENT_ID }
    apiKeyFrom: { name: runlayer-auth, key: AUTH_API_KEY }
  appSecretRef:
    name: runlayer-app
  components:
    backend: { enabled: true, replicas: 2 }
    frontend: { enabled: true, replicas: 2 }
    worker: { enabled: true, replicas: 1 }
  deploy:
    enabled: true
  serviceAccount:
    backend:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-backend@PROJECT.iam.gserviceaccount.com
    worker:
      annotations:
        iam.gke.io/gcp-service-account: runlayer-acme-worker@PROJECT.iam.gserviceaccount.com
  ingress:
    enabled: true
    ingressClassName: gce
    gcp:
      managedCertificate:
        enabled: true
      staticIPName: acme-prod-ip
```

### Optional components (snippet)

When enabling an optional component, set its `images.*` field (and any required Secret refs). The operator rejects the CR if those are missing. `status.phase: Ready` / `Available` wait for **every enabled** optional Deployment (not only backend/frontend/worker).

**Pull credentials for platform components:** the operator sets no `imagePullSecrets` on platform component pods (`spec.deploy.defaultImagePullSecrets` applies to MCPServer pods only — the Helm chart's `toolguard.image.pullSecrets` knob has no operator equivalent). Customer Distribution ECR (`088332244652`) supports **cross-account pulls** when Runlayer allowlists your AWS account or IAM pull principal during onboarding — use those image URIs directly on EKS once allowlisted. Prefer a **GAR / private mirror** for GKE, air-gapped networks, or orgs that require an internal registry copy.

```yaml theme={null}
spec:
  images:
    mcpCatalogApi: REGISTRY/mcp-catalog-api:TAG
    sentryRelay: REGISTRY/sentry-relay:TAG
    toolguard: REGISTRY/toolguard:TAG   # or 088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer/toolguard:…
    topicCpu: REGISTRY/toolguard:runlayer-multimodel-guard-TAG   # or 088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer/toolguard:…
    topicCpuRev: REGISTRY/toolguard:runlayer-rev-guard-TAG       # Rev-only image; required when topicCpu.rev.enabled
    llmGateway: REGISTRY/runlayer/llm-gateway:TAG
  components:
    mcpCatalogApi:
      enabled: true
      apiKeyFrom: { name: runlayer-catalog, key: API_KEY }
    toolguard:
      enabled: true
      # dynamicBatchMax: 1   # Optional GPU rollback; GPU defaults to 16
      gpu:
        enabled: false   # CPU-only / Autopilot; batching stays disabled
    topicCpu:
      enabled: true
      # gunicornWorkers: 1          # slow pool: memory >= workers * 4096 MiB
      # fast:
      #   gunicornWorkers: 3        # memory >= max(workers * 1024, 2048) MiB
      # rev:                        # Rev self-hosted decision model (opt-in; POST /predict/runlayer-rev)
      #   enabled: true             # requires images.topicCpuRev; backend gets RUNLAYER_REV_ENDPOINT_URL + RUNLAYER_REV_TIMEOUT
      #   gunicornWorkers: 1        # memory >= (workers + 1) * 2560 MiB; recycler briefly runs workers+1
    llmGateway:
      enabled: true
      apiKeyFrom: { name: runlayer-llm-gateway, key: apiKey }
    extendDB:
      enabled: true   # ClusterIP-only DynamoDB-compatible adapter on this instance's Postgres; gates MCPServer infrastructure.enable_db on K8S
      credentials:   # bootstrap Postgres role (CREATEDB/CREATEROLE) for `extenddb init`; not the app DB credential
        usernameFrom: { name: runlayer-db, key: username }
        passwordFrom: { name: runlayer-db, key: password }
      # image: REGISTRY/extenddb-postgres:TAG   # optional; defaults to the digest-pinned upstream image
    auditConsumer:
      enabled: true
      streamBackend: kinesis   # or pubsub
      kinesis:
        streamArn: arn:aws:kinesis:…
        consumerArn: arn:aws:kinesis:…/consumer/…
        checkpointTableName: runlayer-audit-checkpoints
        deadLetterBucket: runlayer-audit-dlq
      # pubsub:
      #   subscriptionId: audit-log-sub
      #   deadLetterBucket: acme-audit-dlq
    siemExport:
      enabled: true
      streamBackend: kinesis
      kinesis:
        streamArn: arn:aws:kinesis:…
        consumerArn: arn:aws:kinesis:…/consumer/…
        checkpointTableName: runlayer-siem-checkpoints
        deadLetterBucket: runlayer-siem-dlq
      export:
        s3Bucket: customer-siem-bucket
        # gcsBucket: customer-siem-gcs   # when streamBackend: pubsub
    sessionMaterializer:
      enabled: true
      streamBackend: kinesis   # or pubsub
      sessionsReadFromPostgres: true
      kinesis:
        streamArn: arn:aws:kinesis:…:stream/hook-events
        checkpointTableName: runlayer-session-materializer-checkpoints
        deadLetterBucket: runlayer-session-materializer-dlq
      payload:
        s3Bucket: runlayer-session-payloads
      hookEvents:
        streamName: hook-events
        region: us-east-1
        s3Bucket: runlayer-hook-events-parquet
      # replicas: 2          # ingest; kinesis only
      # compactor:
      #   replicas: 2        # kinesis only; default 1
      # pubsub:
      #   subscriptionId: hook-events-sub
      #   deadLetterBucket: acme-session-materializer-dlq
      # payload:
      #   gcsBucket: acme-session-payloads
      # hookEvents:
      #   topicId: hook-events
      #   publishTimeoutSeconds: 5  # optional; backend default is 5s
  agents:
    sandboxMode: agentcore   # or k8s
    filesBucket: acme-agent-sandbox-files
    agentcore:
      runtimeArn: arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/acme_prod_agent_sandbox
    # k8s:
    #   warmPool: runlayer-agent-pool
    #   namespace: runlayer-acme-agents   # optional; defaults to platform NS
  serviceAccount:
    sessionMaterializer:
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::…:role/runlayer-session-materializer
        # GKE: iam.gke.io/gcp-service-account: …@PROJECT.iam.gserviceaccount.com
```

`extendDB` needs no `images.*` entry — it defaults to a digest-pinned upstream [ExtendDB](https://github.com/extenddb/extenddb) image; set `image` only to override. It is the only optional component with a dedicated reconcile path: the init Job runs `extenddb init` (creates the catalog/data Postgres databases + a dedicated role + TLS cert from the bootstrap `credentials`, HTTPS port 18443) then mints a shared SigV4 access key and `kubectl apply`s those Secrets/ConfigMaps into the platform and MCP namespaces (the reconciler never reads Secret payloads). Deployment/Service/PDB come up after that. `RunlayerInstance.status.conditions` reports `ExtendDBReady`: Deployment ready, credentials present, **and** the readiness probe's cached Postgres connectivity check (`extenddb catalog-check` against both catalog and data DBs, refreshed at most every 5 minutes) — gated on the check's connectivity banners only, so a catalog-integrity finding can't take the whole Service `NotReady`. It is still not a live, between-ticks guarantee. `ExtendDBReady` gates `MCPServer.spec.infrastructure.enable_db` (rejected with "enable ExtendDB on the instance first" until then) — see [`infrastructure.enable_db`](https://docs.runlayer.com/platform-deploy#field-details). Enable ExtendDB on the instance **before** setting `enable_db` on MCPServers. MCPServers with `enable_db` still reconcile their Deployment while waiting; init failure does not wedge the rest of the instance. Init is create-once; a partial failure with no MCP keys synced yet gets **one automatic reset** (reconciler drops the half-created catalog/data DBs + role, then recreates the Job, capped by an instance annotation) before it needs a human — see [Upgrading and recovering ExtendDB](#upgrading-and-recovering-extenddb) below. ExtendDB cannot be disabled while any MCPServer in the Deploy namespace still has `enable_db: true` (clear those first; undeploy deletes tables). Connection sizing for the shared Postgres host: [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md#extenddb-connection-budget).

#### Upgrading and recovering ExtendDB

**Bumping `components.extendDB.image` (or a helper image):**

```yaml theme={null}
components:
  extendDB:
    enabled: true
    image: REGISTRY/extenddb-postgres:NEW_TAG@sha256:…
    # kubectlImage: REGISTRY/kubectl:TAG@sha256:…            # init Job's apply container
    # postgresClientImage: REGISTRY/postgres:16-alpine@sha256:…  # reset Job (extenddb image has no psql)
    # awsCliImage: REGISTRY/aws-cli:TAG@sha256:…             # per-MCP create-table/delete-table Jobs
```

* `image` only changes the **Deployment** — `helm upgrade` / re-apply rolls the existing pods to the new tag. It does **not** rerun `extenddb init`: TLS cert/key, the catalog/data Postgres schema, and the shared SigV4 access key are untouched. There is no auto-upgrade Job in v1 — if the new version needs a schema migration, run it yourself against the catalog/data DBs before or after the roll, per the upstream ExtendDB release notes.
* `kubectlImage` / `postgresClientImage` / `awsCliImage` only affect their respective one-shot Jobs (init, reset, and per-MCPServer create-table/delete-table) on their **next** run — they don't restart anything already Running. Bump them ahead of a planned init/reset, or anytime for the next MCPServer table Job.
* **Keep** Secrets/state (do nothing beyond the CR edit) for a routine image bump — this is the common case and preserves the live token store.
* **Don't** delete a succeeded init Job expecting a fresh schema: the operator only recreates the Job, which reruns `extenddb init` against the **existing** catalog/data DBs. Init isn't idempotent, so it just fails `InitFailed` — the MCP keys Secret already exists at this point, so the reset Job (and its refuse-guards) never runs.
* To actually get a clean Postgres schema with no live token store: clear `enable_db` on (or undeploy) every MCPServer on the instance first, then drop the catalog/data DBs (and the app role, if needed) yourself with the bootstrap credential, then delete the init Job so the operator recreates it. This destroys any tokens already stored in those tables — only do it once nothing depends on them.
* Prefer disable → re-enable when you just want the adapter back without touching Postgres — it keeps the succeeded init Job + Secrets and skips re-init entirely.
* A second `InitFailed` after the one automatic reset, or any failure once MCP keys already exist: inspect the Job logs first (the condition message points there — "inspect the Job logs before doing anything manual" for a reset failure), then delete the Job **and** any partially-created catalog/data DBs before retrying. Once keys/tables exist, dropping the DBs destroys stored tokens.

**Mirror checklist:** the upstream `extenddb-postgres` image (and its helper images) are pulled directly from Docker Hub (`docker.io/extenddb/...`) today — not mirrored to Runlayer's own registries. A Runlayer-run mirror is not yet available. Before relying on it for air-gapped or registry-restricted clusters:

* [ ] Confirm the digest you're pinning (`image` / `kubectlImage` / `postgresClientImage` / `awsCliImage`) is reachable from cluster nodes.
* [ ] If not, mirror it into your own registry and set the CR override(s) above.
* [ ] Track re-pinning on every planned upgrade; nothing re-mirrors automatically.

`auditConsumer` and `siemExport` scale with `replicas` or `spec.autoscaling.auditConsumer` / `spec.autoscaling.siemExport` and deploy start-before-stop (new pods start before the old ones stop). The audit consumer's insert is idempotent, so records read twice during the overlap are written once. On Kinesis, a readiness probe on both consumers holds the old pods until each new pod holds its share of the shards; a backend image without that signal passes the probe after 4 minutes, so each of its rollouts waits that long. On Kinesis each replica leases whole shards, so replicas past the stream's open shard count sit idle; keep `replicas` / `maxReplicas` at or below it. On Kinesis, run Runlayer backend `1.28.775` or later (the first release with shard leasing) before going past one replica, and before upgrading to this operator if you run `siemExport`. An older image has no leases, so extra replicas, and the overlap of every deploy, read every shard: SIEM export exports duplicates (never loss; dedupe on `audit_log_id`), while the audit consumer writes each record once but multiplies Aurora writer load by the replica count. Pods on the same Kinesis enhanced fan-out consumer also fight over each shard's subscription: a `SubscribeToShard` 5 s or more after another takes it over, so they keep cutting each other off. On Pub/Sub replicas share the subscription, with no shard cap. A rollout briefly runs twice the current pod count (`maxSurge: 100%`, the ECS 200/100), even above `maxReplicas`; on Kinesis the pods past the shard count idle but still count against cluster quota until the old pods stop. Resharding the audit stream (shard count or capacity mode, managed out of band) requires Runlayer backend `1.28.2313` or later (the first release with the ENG-6765 fix, #19256), or SIEM export skips the first records of new child shards. Session materializer always runs two Deployments: ingest (`session-materializer`, the stream consumer) and compactor (`session-materializer-compactor`, `app.entrypoints.session_compactor`), both on the `{instance}-session-materializer` ServiceAccount. On Kinesis both scale: set ingest `replicas` (up to the shard count; rolls start-before-stop) and `compactor.replicas` (default 1; `compactor.resources` default 1000m / 4096Mi, one fold per 4Gi). On Pub/Sub both stay at ≤ 1 (CEL). The operator rolls ingest only after the compactor has rolled out (`SessionMaterializerReady` reason `WaitingForRollout` meanwhile), so upgrade the operator before `spec.version`: an image without the compactor entrypoint leaves ingest on its previous image instead of running without a compactor. It also injects `SESSION_*` / `HOOK_EVENTS_*` into backend/worker (payload read + hook publish). For Pub/Sub, provision the hook-events subscription with **message ordering enabled**; publishers use `ordering_key=session_id`. Publish RPC timeout defaults to **5s** (`HOOK_EVENTS_GCP_PUBSUB_PUBLISH_TIMEOUT_SECONDS`); override via that env or `hookEvents.publishTimeoutSeconds` on the CR. Infra (streams, checkpoints, buckets, ordered subscription) is out-of-band; see [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md#session-materializer). `spec.agents` env (`RUNLAYER_AGENT_SANDBOX*`) is injected onto backend and worker (and onto `agentEventTrigger` when that component is enabled) — see [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md#agents-agentcore). Procedures validation runs in the same sandbox runtime, so Procedures need `spec.agents` configured too; without it, creating or validating a Procedure returns 503.

`agents.filesBucket` is a bucket you own, so three things on it are yours to set:

* The backend role needs **`s3:PutObjectTagging`** alongside `s3:PutObject`. Files the backend hands a run (Slack attachments) are uploaded with a `runlayer-kind=run-input` tag, and a tagged `PutObject` is denied without that action — the upload fails and the attachment is silently dropped. Grant `s3:PutObjectTagging` on the agent-files bucket in the backend role (see [Workload identity](https://docs.runlayer.com/deployment/workload-identity.md)).
* Those run inputs live under `sessions/{agent_id}/workspace/.runlayer-inputs/{run_scope}/` inside the durable per-agent prefix, and nothing deletes them. They are only ever readable by the run they were delivered to, but to stop them accumulating add a lifecycle rule expiring objects tagged `runlayer-kind=run-input` after \~7 days (plus `noncurrent_version_expiration` if the bucket is versioned). Scope the rule to the `sessions/` prefix as well as the tag: published artifacts are copies that live under `artifacts/`, and a tag-only rule would reach them too. The ECS module ships this rule as `expire-run-inputs`.
* [Artifact uploads from disk](https://docs.runlayer.com/artifacts/create.md#upload-a-file-from-disk) stage files under `artifact-uploads/` until they are published, and publishing deletes them. The backend role needs `s3:GetObject` to read a staged file and `s3:DeleteObject` to discard it on the agent-files bucket, alongside `s3:PutObject` and `s3:PutObjectTagging`; without Get, publishing fails as storage unavailable. To stop abandoned uploads (up to 25 MB each) accumulating, add a lifecycle rule expiring the `artifact-uploads/` prefix after 1 day (plus `noncurrent_version_expiration` if the bucket is versioned). Nothing durable lives under that prefix. The ECS module ships this rule as `expire-artifact-uploads`.

### K8s Agent Sandbox (`sandboxMode: k8s`)

In-cluster runtime using [kubernetes-sigs/agent-sandbox](https://agent-sandbox.sigs.k8s.io/) (`SandboxClaim` + `SandboxWarmPool`). The operator only wires env; it does **not** install the controller, Template, WarmPool, or isolation runtime.

**1. Install the controller**

| Cluster | Install |
| - | - |
| GKE Autopilot or Standard ≥ `1.35.2-gke.1269000` | [Enable Agent Sandbox on GKE](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/how-install-agent-sandbox): `gcloud beta container clusters update CLUSTER --location=REGION --enable-agent-sandbox` |
| EKS / GKE without the add-on | OSS CRDs + controller from the [project site](https://agent-sandbox.sigs.k8s.io/) / [GitHub](https://github.com/kubernetes-sigs/agent-sandbox) |

**2. Isolation on the nodes (gVisor or Kata — pick one)**

Sandbox pods must not use the host `runc` kernel. Nodes that schedule them need a `RuntimeClass` (`kubectl get runtimeclass`):

| | [gVisor](https://agent-sandbox.sigs.k8s.io/docs/use-cases/gvisor-isolation/) | [Kata Containers](https://agent-sandbox.sigs.k8s.io/docs/use-cases/kata-containers-isolation/) |
| - | - | - |
| Isolation | Userspace kernel (no nested virt) | MicroVM, dedicated kernel |
| `runtimeClassName` | `gvisor` | `kata-qemu` |
| GKE Autopilot | Yes (add-on) | No |
| GKE Standard | Pool with `--sandbox=type=gvisor` (COS) | Ubuntu `UBUNTU_CONTAINERD` + **Intel N2** + nested virt. Not E2 / N2D / T2A / COS. [Kata on GKE](https://agent-sandbox.sigs.k8s.io/docs/use-cases/examples/kata-gke-sandbox/) (not a Google product — no GKE SLA) |
| EKS | Install [runsc](https://gvisor.dev/docs/user_guide/quick_start/kubernetes/) on the sandbox node group | Nested virt + [Kata install](https://github.com/kata-containers/kata-containers/tree/main/docs) on those nodes |

GKE add-on admission also requires `automountServiceAccountToken: false`, `runAsNonRoot`, drop ALL capabilities, CPU+memory limits, and `nodeSelector`/`toleration` `sandbox.gke.io/runtime=gvisor`.

**3. Template + WarmPool + RBAC**, then set `spec.agents.sandboxMode: k8s` + `spec.agents.k8s.warmPool`. Ask Runlayer for Agent Sandbox Template / WarmPool examples if you choose `sandboxMode: k8s`.

### Deploy (`spec.deploy`)

| Field | Default | Notes |
| - | - | - |
| `enabled` | `false` | Creates MCP namespace; enables MCPServer reconcile |
| `platformNamespace` | `runlayer-<customerId>` | |
| `mcpNamespace` | `runlayer-<customerId>-mcps` | |
| `deleteMcpServersOnDeprovision` | `true` | |
| `resourceQuota.hard` | — | Applied to **both** platform and MCP namespaces |
| `telemetryProxy.*` | — | Per-tenant override of operator Helm defaults |
| `kubernetes.supportedPlatforms` | `["x86"]` | `x86` and/or `arm` |

When enabled, backend/worker get `RUNLAYER_DEPLOY=K8S` and related env; frontend gets `PUBLIC_RUNLAYER_DEPLOY=K8S`.

### Wait for Ready

```bash theme={null}
kubectl wait runlayerinstance/acme-prod -n runlayer-system \
  --for=jsonpath='{.status.phase}'=Ready --timeout=20m

kubectl get runlayerinstance acme-prod -n runlayer-system -o yaml
```

Phases: `Pending` → `Installing` → `Migrating` / `Upgrading` → `Ready` (or `Degraded` / `Failed`).

`Available=True` only when every **enabled** core and optional component Deployment is Ready (for example `ToolguardReady`, `TopicCpuReady`, `TopicCpuFastReady`, `LLMGatewayReady`). Disabled optionals are ignored. Ingress and Gateway are separate: when either is enabled, also watch `IngressReady` or `GatewayReady` for traffic (on GCE, `IngressReady` includes the llm-gateway GLB backend when the Ingress routes to it).

Then create MCP env Secrets in the MCP namespace and apply `MCPServer` CRs (create `MCPServer` CRs in the MCP namespace after Ready).

***

## 6. Optional: `runlayer-instance` Helm chart

The optional `runlayer-instance` Helm chart (same Customer Distribution OCI registry as the operator) renders **one** `RunlayerInstance` CR per Helm release. Prefer it for GitOps when you do not apply the CR with kubectl/Terraform.

| Chart | Owns |
| - | - |
| `runlayer-operator` | CRDs + controller (**once per cluster**) |
| `runlayer-instance` | One tenant CR (**once per tenant**) |

v1 owns **only the CR** — Secrets and (when not using `spec.ingress`) Ingress stay outside Helm.

```bash theme={null}
helm upgrade --install acme-prod \
  oci://088332244652.dkr.ecr.us-east-1.amazonaws.com/runlayer-helm-charts/runlayer-instance \
  --version <chart-version> \
  --namespace runlayer-system \
  -f values-acme.yaml
```

Values: `name`, `namespace`, `labels`, `annotations`, and `spec` (full `RunlayerInstanceSpec` passthrough). Do **not** put tenant CRs in the operator chart — operator upgrades must not re-render tenants.

***

## 7. Ingress, NetworkPolicy, scheduling, resources

### Ingress

Opt-in (`spec.ingress.enabled`, default `false`). When enabled, the operator reconciles path routing:

| Path | Service | Port |
| - | - | - |
| `/api/`, `/.well-known`, `/mcp`, `/docs`, `/redoc` | `{name}-backend` | 8000 |
| `/anthropic`, `/openai` | `llm-gateway` | 8090 (only when `components.llmGateway.enabled`) |
| `/` | `{name}-frontend` | 80 |

| Mode | Config |
| - | - |
| AWS ALB + ACM | `ingressClassName: alb` + `alb.ingress.kubernetes.io/certificate-arn` |
| GCP GLB + managed cert | `ingressClassName: gce` + `gcp.managedCertificate.enabled: true` |
| cert-manager | `certManager.enabled` + `issuerRef` + `tls.secretName` |
| External | Leave `ingress.enabled: false`; manage Ingress in Terraform / GitOps |

On `gce` / `gce-internal`, the operator creates `BackendConfig`s (backend, frontend, and llm-gateway when enabled) **before** annotating Services / applying Ingress so GKE GLBC does not stick on missing BackendConfig. Set `controllerNamespace` so NetworkPolicies allow the ingress controller → backend (AWS LBC, nginx). GKE also uses GCP health-check CIDR defaults.

On `gce` / `gce-internal`, and on Gateway classes `gke-l7-*`, the operator sets `PRE_AUTH_TRUSTED_PROXY_HOPS=2` on backend-image workloads when every enabled edge is a Google load balancer. Google's load balancer appends `<client-ip>, <lb-ip>` to `X-Forwarded-For`, and per-IP rate limits, the audit `ip_address` and the `meta.request.ip` policy field must all key on the client, not the load balancer. Other classes keep the backend default of `1` (ALB and nginx append only the client). A one-hop class beside a Google edge is rejected. With an external Ingress or Gateway, set the value yourself in `runlayer-app` (see [App secret](#app-secret)).

Do not enable `certManager` and `gcp.managedCertificate` on the same instance.

### Gateway

Opt-in (`spec.gateway.enabled`, default `false`). Independent of Ingress: enabling one does not delete the other. The path table matches Ingress, including `/anthropic` and `/openai` when `components.llmGateway.enabled` is true. `paths` is a full replace. GKE does not allow one Service on both an Ingress and a Gateway, so `gce` / `gce-internal` and `gke-l7-*` together are rejected. A one-hop edge (ALB, nginx, or any other non-Google class, including attach mode with no `gatewayClassName`) beside a Google edge is also rejected: the backend would treat a caller-supplied `X-Forwarded-For` entry as the client IP.

| Mode | What the operator creates |
| - | - |
| Managed Gateway | `gatewayClassName` set and `parentRefs` empty. Gateway plus HTTPRoute in the platform namespace. |
| Attach | `parentRefs` only. HTTPRoute attached to a Gateway the cluster already has. |
| Attach plus cloud policies | Both `parentRefs` and `gatewayClassName`. HTTPRoute plus Service health policies for that class. The operator does not create or edit the Gateway. |

`gatewayClassName: alb` reconciles `LoadBalancerConfiguration` (internet-facing, TLS 1.2 policy, optional `aws.certificateArn`) and a `TargetGroupConfiguration` per Service (IP targets, the same health checks as Ingress, frontend stickiness). The AWS controller ignores Kubernetes TLS Secrets. Gateway, HTTPRoutes, Certificates, and target-group configs stay in the platform namespace. In attach mode the load balancer config is the exception: it is created in each parent Gateway's namespace, because `infrastructure.parametersRef` cannot name an object in another namespace. Set that Gateway's `parametersRef` to `status.gateway.loadBalancerConfiguration`. The object name is `{instance namespace}.{instance name}-lb-config`, so two instances can share one Gateway namespace. A hyphen would collide (`team-a`/`prod` and `team`/`a-prod`), and a namespace cannot contain `.`. Hostname discovery uses `spec.domain` when `certificateArn` is empty. The operator deletes a Gateway object only when it carries this instance's UID, so a customer Gateway that shares an inventory name is left in place.

`gatewayClassName: gke-l7-*` reconciles `HealthCheckPolicy` and `GCPBackendPolicy` per Service. TLS on a managed Gateway is one of a Kubernetes Secret (`tls` / `certManager`), `gcp.certMap`, or `gcp.preSharedCerts`. GKE Gateway does not support `ManagedCertificate`. `gcp.staticIPName` becomes a named address. The operator does not create Certificate Manager resources. Regional classes (`gke-l7-rilb`, `gke-l7-regional-external-managed`) need an active proxy-only subnet in the same region and VPC. Google rejects the forwarding rule without one, and the operator does not create the subnet. Global classes do not use it.

Any other class gets a generic Gateway and HTTPRoute. `certManager` reconciles a Certificate. The HTTPS listener is added only after the TLS Secret exists, and HTTP then redirects to HTTPS.

The cluster must already have the Gateway API CRDs. The operator does not install a GatewayClass. When Gateway is enabled, watch `GatewayReady`.

### NetworkPolicies

Defaults isolate tenants and allow required DNS / platform / MCP paths. Extensions are **append-only**:

```yaml theme={null}
spec:
  security:
    networkPolicy:
      enabled: true
      additionalEgressRules:
        - to:
            - ipBlock: { cidr: 10.0.0.0/8 }
          ports:
            - protocol: TCP
              port: 5432
            - protocol: TCP
              port: 6379
```

When `deploy.enabled: true`, platform policies come from `RunlayerInstance`; **MCP** policies come from each `MCPServer.spec.security.networkPolicy`.

### Workload scheduling

* `spec.workloadScheduling` — default `nodeSelector` / `affinity` / `tolerations` for platform pods + migration Job
* `spec.components.<name>.scheduling` — per-component override (e.g. ToolGuard → GPU pool)

### Default container resources

When `components.<name>.resources` is omitted, the operator applies these defaults:

| Component | CPU request | Memory request/limit |
| - | - | - |
| backend¹ | 4000m | 8192Mi |
| frontend | 250m | 512Mi |
| worker | 1000m | 4096Mi |
| mcpCatalogApi | 100m | 256Mi / 512Mi limit |
| sentryRelay | 1000m | 2048Mi |
| toolguard | 1000m | 6144Mi |
| llmGateway | 1000m | 2048Mi |
| topicCpu (slow) | 2000m | 8192Mi |
| topicCpu.fast | 1000m | 6656Mi |
| topicCpu.rev (opt-in) | 1000m | 5632Mi / 6144Mi limit |
| auditConsumer / siemExport / agentEventTrigger | 500m | 1024Mi |
| sessionMaterializer | 512m | 4096Mi |
| sessionMaterializer.compactor | 1000m | 4096Mi |

¹ backend also carries a 2Gi ephemeral-storage request (no limit) for the audit-log spool; it is kept even when `components.backend.resources` is overridden, unless the override sets an explicit `ephemeral-storage` request.

Override per component for smaller clusters. Topic CPU also enforces ECS-parity memory floors vs `gunicornWorkers` / `fast.gunicornWorkers`: the slow pool needs 4096 MiB per worker (one worker holds about 3 GiB of models resident and skill scans peak about 0.5 GiB above that), the fast pool 1024 MiB per worker and at least 2048 MiB. A `RunlayerInstance` below a floor fails validation, and a failed instance is not reconciled at all, not even a version bump, until the memory is raised or the worker count lowered. If you set `deploy.resourceQuota.hard`, ensure requests fit the quota.

### Autoscaling and PDBs

* `spec.autoscaling.<component>` — HPA when `enabled: true` **and** a CPU or memory target is set (`backend`, `frontend`, `worker`, `sentryRelay`, `llmGateway`, `auditConsumer`, `siemExport`)
* `llmGateway` gets a **default** HPA (70% CPU, min 1, max 3) when enabled and `autoscaling.llmGateway` is unset — set `autoscaling.llmGateway.enabled: false` to disable
* `auditConsumer` and `siemExport` have no default HPA. The HPA averages CPU across pods, while ECS scales on the busiest task; shard leases spread load unevenly, so leave headroom in the target (ECS uses 75%). Keep their CPU request at 1 core or less, and set a request for every resource the HPA targets (the operator rejects a missing request, or a CPU request above 1 core; a `resources` override replaces the defaults, so it must carry those requests itself): the consumer is one process, so a pegged 2-core pod reads 50%. Before turning the HPA off, set `components.<component>.replicas` to the current pod count and step it down, or every lease moves at once
* Default HPA `behavior` (when unset): scale-up waits 60s and adds up to 50% or 2 pods per minute. Scale-down waits for a quiet fleet — 1800s for `backend` (keeps replicas added by a spike until it is over), 300s for other components — and removes at most 10% per minute. Set `behavior` to replace the whole block.
* `auditConsumer` and `siemExport` scale-down instead waits 900s and removes one pod per 900s: on Kinesis every scale-in moves shard leases.
* An HPA needs a request for every resource it targets, on every container in the pod, native sidecars included, and the pod's requests must not sum to zero; otherwise that metric fails (`FailedGetResourceMetric`). An HPA with no other working metric never scales; one with a working metric (say, memory beside a broken CPU target) still scales up on it but never scales down. A `components.<name>.resources` override replaces the defaults, so a memory-only override drops the CPU request a CPU target needs (also check `otelCollector.resources`, the backend's sidecar). The operator still reconciles, and sets the `AutoscalingReady` condition to `False` (reason `MissingResourceRequest`) naming the component, resource and container: `kubectl get runlayerinstance <name> -o jsonpath='{.status.conditions[?(@.type=="AutoscalingReady")]}'`. A limit with no request counts. The check reads the operator's pod spec, so a LimitRange default request or GKE Autopilot defaults can make it a false alarm (set the request explicitly to clear it), and it does not see sidecars injected by a mutating webhook.
* `spec.podDisruptionBudget` — optional PDBs for core Deployments

### Trusted CA

`spec.trustedCa` mounts a customer CA ConfigMap and sets `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `NODE_EXTRA_CA_CERTS` for enterprise TLS inspection.

### OTEL collector sidecar

`spec.otelCollector.enabled` injects a native sidecar on the **backend** Deployment (Kubernetes ≥ 1.29). Requires reachable OTLP endpoints; hostname endpoints may need extra NetworkPolicy CIDRs. Configure reachable OTLP endpoints; see observability notes below. Name the Runlayer-operated endpoint `runlayer-…` and give it `protocol: http`: the sidecar exports its own health metrics (export queue depth, send failures, receiver refusals — no application data) to endpoints with that prefix and only those, which is how Runlayer monitors your deployment's telemetry export.

### Audit log spool

The backend's local audit-log spool is **enabled by default**: audit records are appended to a spool on the pod's local disk (a dedicated `emptyDir` at `/var/audit-spool`) and delivered asynchronously by an in-process tailer, so MCP proxy requests do not wait on audit delivery. Records are typically delivered within seconds, and delivery is at-least-once with deduplication. If the spool cannot keep up or its disk budget fills, individual records fall back to inline delivery on the request path, so nothing is lost to backpressure.

* **Node-disk encryption is required.** The spool briefly holds pre-redaction audit payloads at rest on the node's disk. On GKE, node disks are encrypted by default with Google-managed keys (CMEK optional). On EKS, encrypted EBS node volumes must be explicitly enabled. The operator cannot verify either.
* The backend pod's shutdown drain window for the spool is 110 seconds (grace period 140s minus 30s headroom); records not delivered before the window expires are lost with the pod.
* After an outage of a delivery target (database or Kinesis), expect elevated write load while each backend pod drains its accumulated backlog. On small database instances, `AUDIT_LOG_SPOOL_DELIVERY_CONCURRENCY` (default 8, per pod) can be lowered via the app secret to throttle the catch-up.
* Each backend pod can hold up to \~512MB of spool data on node disk by default (`AUDIT_LOG_SPOOL_MAX_BYTES`, settable via `spec.auditSpool.maxBytes`; dead-letter bytes count against the same budget — a soft cap that worker processes re-check every 5 seconds, so bursts can briefly overshoot it). Budget node ephemeral storage accordingly when running many instances per cluster. The spool volume is bounded by an emptyDir `sizeLimit` derived as max(2 × `maxBytes`, 1Gi) — raising `maxBytes` automatically keeps the backstop above the budget — and backend pods carry an ephemeral-storage request (2Gi, no limit) so the scheduler accounts for the disk footprint. If spool usage ever exceeds the `sizeLimit`, the kubelet evicts the backend pod and its undelivered spool is discarded — `spec.auditSpool.volumeSizeLimit` overrides the derivation; if you set it, keep it comfortably above the `maxBytes` budget.
* **Alert on spool health.** A spool that persistently rejects appends degrades silently to inline delivery (a latency regression, not data loss), and nothing alerts on it out of the box. See [Monitoring the audit log spool](#monitoring-the-audit-log-spool) below.

To revert to inline audit delivery, set `spec.auditSpool.enabled: false`. New pods write audit logs inline again, and each old pod drains its residual spool within the shutdown window as it stops. No data migration is needed in either direction.

Disabling requires the operator 0.2.22 CRD: `helm upgrade` does not apply `crds/`, and against an older CRD the API server silently prunes `spec.auditSpool`, leaving the spool on. Apply the updated CRD first — see [Upgrading the operator](#upgrading-the-operator-manual-crd-apply).

### Monitoring the audit log spool

The spool degrades gracefully — records that it rejects are delivered inline instead of lost — so a persistently unhealthy spool is invisible unless you alert on it. The operator does not ship a spool alert; use the metrics and alert rules below to build one.

#### Prerequisite: metrics export

The backend exports spool metrics over OTLP. `spec.otelCollector.enabled` (above) injects a collector sidecar and wires the backend's OTLP/gRPC endpoint for you — but at least one configured endpoint must carry metrics: an endpoint restricted to `signals: [traces]` (or a `configMapRef` collector config without a metrics exporter) leaves the sidecar's metrics pipeline on the `nop` exporter, and the spool metrics go nowhere.

Each backend worker process exports its own cumulative counters, tagged with a unique `service.instance.id` resource attribute. The operator's generated sidecar config promotes that identity onto every datapoint, so the per-process series survive into your storage. If you replace the config via `configMapRef`, replicate that promotion (or enable `resource_to_telemetry_conversion` on a Prometheus/remote-write exporter): if the workers collapse into one series, the merged counters zigzag, every dip reads as a counter reset, and `rate()` / `increase()` overcount by orders of magnitude — the alerts below will page on fabricated spikes.

Metric names below are the Prometheus-translated forms (OTLP ingestion appends the `_total` / `_seconds` / `_milliseconds` / `_bytes` suffixes), as stored by Prometheus-compatible backends such as Mimir.

#### Fallback reasons

Every rejected append increments `runlayer_audit_spool_fallback_count_total` with a `reason` label. Each reason has a different operational meaning:

| `reason` | What it means | First move |
| - | - | - |
| `over_budget` | Spool + dead-letter bytes hit `AUDIT_LOG_SPOOL_MAX_BYTES` (default 512MB) — the disk is genuinely full of backlog. | Check `runlayer_audit_spool_accounted_size_bytes` (the exact bytes the budget charges: whole on-disk segment bytes, including delivered-but-unreclaimed prefixes, plus the `dead/` quarantine) against `runlayer_audit_spool_size_limit_bytes` (the configured budget). `runlayer_audit_spool_depth_bytes` and `runlayer_audit_spool_dead_size_bytes` decompose it into undelivered backlog vs quarantined poison records. |
| `budget_unmeasurable` | The budget scan could not **read** the spool volume, so appends fail closed. Mount or disk-health problem, not capacity. | `stat -f` on `AUDIT_LOG_SPOOL_DIR` (`/var/audit-spool`) in the backend container — a tmpfs there means the volume is shadowed or missing. |
| `write_error` | An append raised or short-wrote — the disk is failing writes. | Check `audit_spool_append_failed` / `audit_spool_short_write` backend logs for the exact `OSError`. |
| `writer_degraded` | An earlier rotation failure or short write cleared the writer's segment handle, and every append since falls back. Persistent until the worker restarts. | Restart the backend pod (degraded writers self-heal on worker recycle). |
| `spool_unavailable` | The worker wanted a spool and couldn't get or keep one at boot (bad mount, unwritable dir, or tailer start failure rolled the spool back) — every emit bypasses the spool. Persistent until the worker restarts healthy. | Check `audit_spool_start_failed` / `audit_spool_disabled_tailer_start_failed` backend logs and `stat -f` the spool volume; fix the mount, then restart the pod. |
| `spool_closed` | An in-flight request raced a graceful shutdown's spool close — deploy-window traffic by construction. | Exclude from ratio alerting (the rules below do). |

#### Prometheus alert rules

A ready-to-adapt `PrometheusRule` (kube-prometheus-stack shape — adapt the labels/selectors to your stack, or lift the PromQL into whatever rule format your Prometheus uses). The operator does not ship these as manifests:

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: runlayer-audit-spool
  labels:
    release: prometheus # match your Prometheus rule selector
spec:
  groups:
    - name: runlayer-audit-spool
      # Severity split: fallback ratio = hot-path latency regression (page); dead-letters pruned = quantified audit-record loss (page); oldest-age stays warning as the early-drift signal.
      rules:
        # More than 1% of spool-eligible audit emits are falling back to
        # inline delivery, as a % against delivered + fallen-back records —
        # the denominator is confirmed deliveries, so the ratio deflates
        # while a post-outage backlog drains. spool_closed is excluded: it
        # only occurs when a request races a graceful shutdown, i.e.
        # ordinary deploy traffic.
        # The >= 5 fallbacks / 10m floor keeps one-off blips in quiet hours
        # from paging; on a deployment emitting fewer than 5 spool-eligible
        # audit events per 10 minutes it suppresses the alert entirely, so
        # lower or drop that clause on low-traffic deployments.
        # No counter-birth guard on the fallback counter: current backend
        # builds pre-seed every reason series to 0 at process start, so
        # increase() already sees the 0 -> N step on a fresh process — a
        # birth term here would double-count a young process's fallbacks.
        # (On older builds without the zero baselines, a fallback series
        # born by its first loss event hides from increase() until its
        # second export; the dead-letters rule below shows the birth-branch
        # pattern if you must cover such builds.)
        # The delivery histogram is NOT pre-seeded: until the first
        # successful delivery its _count has no series at all, and an empty
        # denominator would silence the alert in exactly the worst case
        # (everything falling back). The "or <fallbacks> * 0" branch keeps
        # the denominator non-empty then, so the ratio pins to 100 instead
        # of going missing.
        - alert: RunlayerAuditSpoolFallbackRatioHigh
          expr: |
            (
              100 * sum(increase(runlayer_audit_spool_fallback_count_total{reason!="spool_closed"}[10m]))
              /
              (
                (
                  sum(increase(runlayer_audit_spool_delivery_duration_milliseconds_count[10m]))
                  or
                  sum(increase(runlayer_audit_spool_fallback_count_total{reason!="spool_closed"}[10m])) * 0
                )
                + sum(increase(runlayer_audit_spool_fallback_count_total{reason!="spool_closed"}[10m]))
              )
              > 1
            )
            and
            (
              sum(increase(runlayer_audit_spool_fallback_count_total{reason!="spool_closed"}[10m])) >= 5
            )
          for: 10m
          labels:
            severity: critical
          annotations:
            summary: "Runlayer audit spool is rejecting appends; delivery is back on the request hot path"
            description: "Split runlayer_audit_spool_fallback_count_total by the reason label — each reason has its own first move (see the Runlayer Operator docs, Monitoring the audit log spool)."

        # The oldest undelivered spool record is more than 5 minutes old:
        # the tailer is not draining (wedged leader, or delivery target
        # slow/unreachable). Expected to spike briefly after a database or
        # delivery-target outage while backlog drains.
        - alert: RunlayerAuditSpoolBacklogStale
          expr: max(runlayer_audit_spool_oldest_age_seconds) > 300
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "Runlayer audit spool backlog is not draining"
            description: "Oldest undelivered audit record is over 5 minutes old. Check backend logs for tailer/delivery errors and runlayer_audit_spool_depth_bytes for backlog growth."

        # The age gauge is emitted on every tailer pass while a leader is
        # measuring (an explicit 0 when the spool is empty), so a gap in the
        # series is itself a signal: no tailer leader is measuring, or the
        # spool head is unreadable with backlog present. The rule above
        # evaluates to an empty vector in exactly those states and stays
        # green. Each backend pod's tailer leader emits its own series, so
        # count the reporting pods against your replica count rather than
        # testing global absence — with absent(), one healthy pod hides
        # every broken one. Set the threshold to your backend replica count
        # (spec.components.backend.replicas; join against
        # kube-state-metrics' kube_deployment_spec_replicas if you want it
        # to track scaling automatically). Only deploy this companion rule
        # where the spool and OTEL export are enabled — otherwise the gauge
        # is legitimately absent and it will fire constantly.
        - alert: RunlayerAuditSpoolAgeGaugeMissing
          expr: (count(runlayer_audit_spool_oldest_age_seconds) or vector(0)) < 2 # match spec.components.backend.replicas
          for: 15m
          labels:
            severity: warning
          annotations:
            summary: "Runlayer audit spool age gauge reporting from fewer pods than expected"
            description: "At least one backend pod has no tailer leader measuring its spool (or an unreadable spool head). That pod's backlog delivery may be stopped entirely. Check backend logs for tailer leadership and audit_spool_gauge_emit_failed errors."

        # Records were deleted from the dead-letter directory to keep it
        # bounded. Unlike fallbacks, this is real audit-log loss.
        # dead_prune_uncounted covers files the pruner deleted without being
        # able to read a record count first (counts files, not records) —
        # the same irreversible loss, kept on a separate series so
        # dead_pruned stays record-denominated.
        # Birth branches: current backend builds pre-seed both counters to
        # 0 at process start, so increase() catches a first prune on its
        # own. The "unless last_over_time(...)" branches cover builds
        # without the zero baselines, where a prune counter is born already
        # positive and increase() reports nothing until a second prune in
        # the same process — which may never come, since prunes are rare.
        # The per-series unless runs BEFORE the sum: a recycled worker's
        # pre-seeded zero baseline (new series, first sample 0) sums to 0
        # and is dropped by the > 0 filter, and the windowed presence check
        # (last_over_time over (t-20m, t-5m], not an instant offset) means
        # a false birth needs a 15m+ metrics-ingestion gap, not one missed
        # scrape, before old series could masquerade as newborn.
        - alert: RunlayerAuditSpoolDeadLettersPruned
          expr: |
            sum(increase(runlayer_audit_spool_dead_pruned_count_total[1h])) > 0
            or sum(runlayer_audit_spool_dead_pruned_count_total unless last_over_time(runlayer_audit_spool_dead_pruned_count_total[15m] offset 5m)) > 0
            or sum(increase(runlayer_audit_spool_dead_prune_uncounted_count_total[1h])) > 0
            or sum(runlayer_audit_spool_dead_prune_uncounted_count_total unless last_over_time(runlayer_audit_spool_dead_prune_uncounted_count_total[15m] offset 5m)) > 0
          labels:
            severity: critical
          annotations:
            summary: "Runlayer audit records pruned from the dead-letter directory (audit-log loss)"
            description: "Poison records were deleted to keep dead/ bounded. Investigate what is producing poison records (audit_spool_record_dead_lettered backend logs) before retention erases the evidence."
```

One residual false-fire mode: after a metrics-ingestion gap of 15 minutes or more (collector or scrape-pipeline outage), the dead-letters rule's birth branches can re-fire on pre-existing series when ingestion resumes — silence the alert on pipeline recovery rather than treating it as new loss.

One loss path is not covered by these rules: when the tailer fails to write a poison record into `dead/` in the first place, the record is dropped outright. The matching counter (`runlayer_audit_spool_dead_letter_write_failed_count_total`) is disabled by default on self-hosted deployments, so a metric alert on it would silently never fire. If your stack supports log-based alerting, alert on the `audit_spool_dead_letter_write_failed` backend log line instead — it fires unconditionally.

***

## Related docs

> [card] [Kubernetes prerequisites](https://docs.runlayer.com/deployment/kubernetes-prerequisites.md)
>
> Cluster requirements for EKS and GKE

> [card] [External dependencies](https://docs.runlayer.com/deployment/external-dependencies.md)
>
> Postgres, Redis, streams, buckets + Terraform samples

> [card] [Runlayer-provided inputs](https://docs.runlayer.com/deployment/runlayer-provided-inputs.md)
>
> Catalog key, WorkOS, download token, images

> [card] [Workload identity](https://docs.runlayer.com/deployment/workload-identity.md)
>
> IRSA / GKE Workload Identity matrix

> [card] [Deployment overview](https://docs.runlayer.com/deployment/overview.md)
>
> Account strategy and isolation models

> [card] [Network firewall](https://docs.runlayer.com/network-firewall-requirements.md)
>
> Client egress allowlists for the tenant hostname


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