# High availability on Kubernetes

**Last updated:** 2026-11-27T14:42:00-03:00 (UTC-3)

For production, run several gateway replicas with autoscaling, a PodDisruptionBudget and spreading across nodes, and shut down each pod without dropping in-flight requests. The high availability profile uses only generic Kubernetes APIs. The default installation still has a single replica.

**The profile covers the gateway.** The availability of PostgreSQL, the Collector, the ingress and across regions needs its own planning, and the profile must be validated on your cluster. [Run on Kubernetes in production](/docs/operate/kubernetes-production/) is that plan, step by step: zones, a managed database in HA and its failover, Vault, NetworkPolicy, the load balancer, logs, alerts, upgrades and several regions, each with the values that were measured.

HTTP input budgets come from the behavior YAML. The base does not pin the read budget through an environment default; Helm leaves `gateway.httpReadTimeoutSeconds` unset by default and retains explicit overrides. A timeout change needs a rollout; the safe settings view does not change HPA, replicas, termination grace or shutdown behavior. See [HTTP budgets](/docs/operate/http-input-limits/).

Kubernetes HTTP GET probes use their configured manifest paths and ports independently of `server.healthcheck_url`, which selects the binary's standalone probe. Changing the CLI target does not rewrite cluster probes or certify readiness. See [CLI healthcheck](/docs/reference/cli/#healthcheck).

## Helm

```bash
helm template gateway deploy/helm/gateway \
  --namespace m7gtw \
  -f deploy/helm/gateway/values-ha.yaml
```

With the Secret and a shared PostgreSQL ready, apply with `helm upgrade --install`, `--atomic --wait` and a timeout that covers streams and drain, for example `--timeout 10m`.

| Values | Behavior |
| --- | --- |
| `replicaCount` | Fixed replicas when HPA is off |
| `autoscaling.enabled` | Renders an `autoscaling/v2` HPA; the Deployment stops declaring `replicas` so it does not compete with the autoscaler |
| `autoscaling.minReplicas/maxReplicas` | The HA profile uses a minimum of 2 and a maximum of 6 |
| `autoscaling.targetCPUUtilizationPercentage` | 70% by default and in the profile; depends on CPU requests and the cluster's metrics API. `null` drops the CPU metric |
| `autoscaling.targetMemoryUtilizationPercentage` | `null` (off) by default; 1–1000 adds a memory metric beside CPU, against `resources.requests.memory` |
| `podDisruptionBudget.enabled/maxUnavailable` | The profile tolerates one voluntary disruption (`maxUnavailable: 1`, the default); requires a minimum of two replicas |
| `podDisruptionBudget.minAvailable` | `null` by default; set it, together with `maxUnavailable: null`, to state how many Pods must stay instead of how many may go |
| `rollout.maxSurge/maxUnavailable` | Defaults 1/0; an update needs capacity for the additional pod |
| `rollout.minReadySeconds` | `5`: how long a new Pod must stay ready before the rollout counts it and moves on |
| `topologySpread.enabled/whenUnsatisfiable` | The profile uses hostname and `DoNotSchedule`; requires enough eligible nodes |
| `topologySpread.maxSkew` | `1`: the largest difference in gateway Pods between two nodes the scheduler accepts |
| `metrics.serviceAnnotations` | Annotates `/metrics` for scraping; does not install Prometheus or enable its flag in the application |
| `gateway.lifecycle` | Drain, HTTP deadline and termination period aligned |

The schema validates the values, and the template rejects an inverted HPA, an HPA with neither metric, a metric without its resource request, an invalid PDB and a grace period below the known selected lifecycle durations plus the 40-second cleanup allowance (external configuration remains the operator's responsibility). HPA needs `metrics.k8s.io`, usually provided by Metrics Server. Its CPU-based control does not reflect queue size or upstream latency; see the [official HPA documentation](https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/).

### Memory as a second HPA metric

```yaml
autoscaling:
  enabled: true
  targetCPUUtilizationPercentage: 70
  targetMemoryUtilizationPercentage: 80
```

With both targets the HPA computes a replica count for each and applies the larger one, so memory can only add replicas that CPU would not. A gateway's memory follows in-flight streams, request bodies and caches rather than request rate, and Go returns freed memory to the operating system slowly, so memory falls late after a peak; the scale-down stabilization window (`scaleDownStabilizationSeconds`, 300 s) absorbs that. Use memory as a backstop against a replica approaching its limit, and keep CPU (or [KEDA](#optional-keda) on load) as the scaling signal. Setting `targetCPUUtilizationPercentage: null` with a memory target leaves memory as the only metric; setting both to `null` is refused. Each metric needs its request (`resources.requests.cpu` or `.memory`), because utilization is a share of the request; the chart refuses the release otherwise instead of rendering an HPA that never scales.

Tested on 2026-11-08 with metrics-server: both metrics rendered, the HPA held two replicas from the memory reading (29% of the 96 Mi request against an 80% target) while the CPU reading was still pending for a Pod that had just started; three minutes later it read both (CPU 1%, memory 18%).

### PodDisruptionBudget with `minAvailable`

```yaml
podDisruptionBudget:
  enabled: true
  maxUnavailable: null   # the PodDisruptionBudget API takes one of the two
  minAvailable: 1
```

`maxUnavailable: 1` stays the default, so existing values render the same PDB. `minAvailable` suits a fixed floor ("never fewer than two serving Pods") whatever the HPA has scaled to; `maxUnavailable` suits a fixed disruption size as the fleet grows. Setting both is refused with a message that names `maxUnavailable: null`, and so is setting neither. `minAvailable` must stay below the minimum replica count (`replicaCount`, or `autoscaling.minReplicas` with the HPA): otherwise no Pod can ever be evicted, and every node drain blocks.

Tested on 2026-11-08 with two replicas and `minAvailable: 1`: the first eviction was accepted, the second, while the replacement was starting, was refused with 429 (`Cannot evict pod as it would violate the pod's disruption budget`), and `ALLOWED DISRUPTIONS` returned to 1 once the replacement was ready.

A PDB covers voluntary disruptions through the eviction mechanism; it does not prevent node failure or determine availability during a rolling update. The Deployment strategy is separate, as described in [disruptions in Kubernetes](https://kubernetes.io/docs/concepts/workloads/pods/disruptions/).

## Kustomize component

In the environment's root `kustomization.yaml`, add:

```yaml
components:
  - deploy/profiles/ha
```

Then apply the root. The directory is a **Component**, not a standalone installation (`kubectl apply -k deploy/profiles/ha` does not work on its own). It preserves the base's hashed ConfigMap, adds the HPA and PDB, removes `replicas` from the Deployment and spreads the pods by hostname.

The profile does not work around a lack of nodes or resources. In a single-node environment, the operator can use the development base or adjust spreading explicitly; two replicas on the same node offer no tolerance to losing that node.

## Process drain

All modes consume the same [lifecycle YAML, precedence and applied-source contract](/docs/operate/shutdown/). Defaults are drain 10s in a Pod (2s elsewhere) and shutdown 130s; the external base/Compose/Helm grace is 180s. Legacy Helm seconds are optional explicit overrides, with null defaults so YAML can apply. The chart checks known durations plus 40s cleanup allowance, not an aggregate process-exit guarantee; an external ConfigMap/Secret needs operator alignment. Compose exposes `GATEWAY_STOP_GRACE_PERIOD`. On macOS and Linux the NPX wrapper runs the binary in a process group of its own, forwards each signal it receives once (SIGHUP as SIGTERM) and waits for it; the binary ignores a repeated signal within 1 second of the first, so a stop delivered to both drains once. On Windows the console delivers Ctrl+C and Ctrl+Break to the binary itself, so the wrapper only waits ([stopping it](/docs/operate/shutdown/#stop-it-from-a-terminal-or-a-process-manager)).

**Readiness does not check PostgreSQL**, by design (owner decision, 2026-11-07):

- **The database is shared.** When it is down, every replica is equally unable to serve, so taking them out of the Service would leave no endpoint.
- **What clients would lose:** the gateway's own fast `503` with a `request_id`, in exchange for a load-balancer error. The request log, the metrics and the console would go dark too.
- **During the outage:** managed-key calls answer `503` and recover by themselves when the database returns.
- **Liveness never checks the database either.** Restarting every Pod cannot fix a database.

Alert on `gateway_database_up` instead. Each `/metrics` scrape pings PostgreSQL once, bounded by `storage.database.acquire_timeout`, and reports `1` or `0`, plus `gateway_database_ping_seconds`:

```yaml
- alert: GatewayDatabaseDown
  expr: gateway_database_up == 0
  for: 2m
```

This rule ships in `deploy/observability/alert-rules.yml` with the other [alert rules](/docs/features/observability/#alert-rules) (open circuit, provider error rate and latency, usage write, secret manager and OTLP failures). The bundled Prometheus loads them; with the Prometheus Operator, set `serviceMonitor.enabled` and `serviceMonitor.alertRules` in the Helm chart to get them as a `PrometheusRule`. The gateway's own [operational events](/docs/features/alerting/#operational-events) cannot deliver `database_down` during the outage, because their outbox is in PostgreSQL: page from this rule.

On SIGTERM/SIGINT, readiness switches to 503 and liveness stays 200, while every request is still served for the drain delay: kube-proxy on each node stops sending new connections when the endpoint removal reaches it, and what arrives before that is answered. HTTP keep-alive turns off at the same time: idle client connections close and every later response carries `Connection: close`, so a client reconnects through the Service to a ready replica. There is no public endpoint to start a drain. When the delay ends, new operations get a correlatable 503 (`draining`), the listener closes and the HTTP server waits for accepted handlers. The main function waits for Shutdown to finish **before** closing synchronization, the remaining connections, the database or exporters. That way, nothing is closed while a response is still going out.

Background work stops at SIGTERM, without waiting for the drain delay (it does not arrive through the Service, so there is nothing to wait for): batches and evaluation runs stop sending new items, durable queues and live-evaluation rules stop claiming jobs. Items already sent finish (their in-process calls are admitted like the request that started them) within the same deadline; past it they are cancelled and stay pending. The replica then releases their lease, so another replica resumes them; nothing is marked failed by the drain. Capture writes still in flight are awaited too.

The default deadline covers the current two-minute request budget. When it expires, connections are closed and the process logs a forced shutdown. There is no promise to complete streams longer than the deadlines, to survive SIGKILL or to recover jobs. Endpoint/Load Balancer behavior and readiness propagation depend on the environment, as described in the [pod lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/).

### Measured on a multi-node cluster

On 2026-11-20 (T176), on GKE 1.36.4 with one node per zone in three zones, three replicas behind a ClusterIP Service and a client sending 20 requests per second over keep-alive connections (a quarter of them streams):

| Disruption | Build, `drain_delay` | Sent | `503 draining` | Failed |
| --- | --- | --- | --- | --- |
| Rolling upgrade 0.0.1-rc.1 → rc.2 | before the fix, 2 s | 2,060 | 67 | 5 refused connections |
| Rolling restart | before the fix, 10 s | 1,120 | 430 (every request of the client for about 10 s) | 0 |
| Rolling restart | with keep-alive off at drain, 10 s | 1,100 | 9 | 0 |
| Rolling restart | with keep-alive off at drain, 2 s | 900 | 10 | 1 refused connection |
| Pod deleted (`kubectl delete pod`) | with the fix, 2 s | 540 | 0 | 0 |
| Node drained (`kubectl drain`) | with the fix, 2 s | 1,040 | 0 | 0 |
| Rolling restart (Kustomize) | serving through the delay, 10 s default in a Pod | 920 | 0 | 0 |
| Pod deleted (Kustomize) | serving through the delay, 10 s | 660 | 0 | 0 |
| Node drained (Kustomize) | serving through the delay, 10 s | 3,560 | 0 | 0 |

The last three rows are the follow-up on a fresh cluster of the same shape, deployed with the root Kustomization and its `ha` component (image `157d991d`): readiness withdrawn at SIGTERM while requests are still served, admission stopped only when the 10 s delay ends. The Pod deleted in that run logged its 10 s delay and answered 7 requests with `200` after SIGTERM, the ones the first rows refused. Before that change:

- **The remaining `503 draining`** (about 1% during a rolling restart) are requests on new connections that kube-proxy still sent to a terminating Pod before its endpoint removal reached every node: each gets one refusal and closes, and the client's next request reaches a ready replica. They are the documented refusal, with `request_id`; the official OpenAI and Anthropic SDKs retry a 503 by default.
- **A refused connection** happens when the drain delay ends, and the listener closes, before every node has removed the endpoint. On this cluster the refusals of a draining Pod kept arriving for up to about 3.5 s after SIGTERM, so 2 s was short and 10 s left none. On a multi-node cluster, set `lifecycle.drain_delay` above your measured endpoint propagation (5–10 s is typical); with keep-alive off at drain, a longer delay no longer costs extra refusals. Keep `terminationGracePeriodSeconds` at or above drain + shutdown + 40 s (Helm checks it).

## Shared state and updates

All replicas must point to the same PostgreSQL and the same external Secret references, including the session signing key and the master encryption key. The profile does not generate or rotate these secrets. Overrides and versions stay under the existing control; authentication, RPM and team policies do not switch to local state because of the HPA. There is a synchronization window for configuration snapshots, which needs to be measured in your environment.

Weighted sequences, queues and counters remain **per process**; circuits are per process unless `shared_circuit_breaker` shares them through PostgreSQL (see below). Autoscaling can multiply local capacity; it is not the same as a global provider limit. PostgreSQL, the Collector, Ingress and storage need their own operational profiles.

The console is a self-contained package: the HTML carries the JavaScript and CSS from the image itself. Navigating does not require fetching files from another pod, so replicas of different versions during a rollout do not break open pages.

## Optional KEDA

The chart creates a `ScaledObject` with `keda.enabled=true` and `keda.prometheus.serverAddress` (default trigger: `sum(gateway_http_inflight)` per Pod, threshold `"20"`). It is mutually exclusive with `autoscaling.enabled` and removes `replicas` from the Deployment. It requires KEDA installed and `metrics_endpoint` being scraped; `minReplicas: 0` is accepted, but the first request after idling waits for the cold start. Each replica admits up to `network.max_inflight_requests` concurrent inferences; scale before that, because a rising `gateway_inference_rejections_total` means 503s for clients.

| Value | Default | What it does |
| --- | --- | --- |
| `keda.enabled` | `false` | Renders the `ScaledObject` |
| `keda.minReplicas` | `2` | Fewest replicas; `0` allows scaling to zero with a cold start |
| `keda.maxReplicas` | `10` | Most replicas KEDA may run |
| `keda.pollingInterval` | `15` | Seconds between two queries of the trigger |
| `keda.cooldownPeriod` | `300` | Seconds after the last active trigger before scaling down to `minReplicas` |
| `keda.prometheus.serverAddress` | required | Address of the Prometheus that scrapes the gateway's `/metrics` |
| `keda.prometheus.query` | `sum(gateway_http_inflight{...})` | The PromQL whose value drives the scale |
| `keda.prometheus.threshold` | `"20"` | Target value of the query per replica, as a string |

### Scaling on tokens per second

In-flight requests are a coarse proxy for LLM load: one long stream and one short completion count the same. With `metrics_endpoint`, `gateway_tokens_total{type="output"}` counts the output tokens providers reported, per replica, so the trigger can follow generation throughput instead ([inference series](/docs/features/observability/#inference-series)):

```yaml
keda:
  enabled: true
  prometheus:
    serverAddress: http://prometheus.monitoring:9090
    query: sum(rate(gateway_tokens_total{type="output",app_kubernetes_io_name="gateway"}[2m]))
    threshold: "400" # output tokens per second per replica; measure yours
```

Pick the threshold from your own load: output tokens per second that one replica sustains before `gateway_inference_rejections_total` or p95 `gateway_time_to_first_token_seconds` rise. A stream without known usage (`stream_usage` off and no usage in the provider's stream) adds no tokens, so keep an in-flight trigger as well when such traffic matters; the chart's `keda.prometheus` takes one query, so a second trigger needs your own `ScaledObject` (the `deploy/profiles/keda` component is a starting point). The gateway does not proxy the provider's own capacity: scaling replicas does not raise a provider's rate limit.

With Kustomize, use the `deploy/profiles/keda` component (instead of `deploy/profiles/ha`, which already includes an HPA): it adds the `ScaledObject` and removes `replicas` from the Deployment. Set `serverAddress` to the Prometheus that scrapes the gateway's `/metrics`.

## See also

- [Run on Kubernetes in production](/docs/operate/kubernetes-production/).
- [Operations on Kubernetes](/docs/operate/operations/).
- [Deployment modes](/docs/operate/deployment-modes/).
- [Weights and capacity per target](/docs/features/routing-and-admission/) and [destination health and circuit state](/docs/features/resilience/): local by default, optionally shared through PostgreSQL.
