# Run on Kubernetes in production

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

This guide takes you from a first cluster to a gateway that survives the loss of a node, a zone, its database primary and, if you need it, a whole region. Follow it in order: each stage builds on the one before, and you can stop at the stage your availability target needs.

1. [One node or a small cluster](#1-one-node-or-a-small-cluster): what you can and cannot expect.
2. [One cluster across nodes and zones](#2-one-cluster-across-nodes-and-zones): the production profile most installations need.
3. [Several clusters or regions](#3-several-clusters-or-regions): one database primary, a gateway fleet per region and a global load balancer.

Every recommended value below comes with the reason for it, and where a number is given it was measured, not estimated. The measurements come from one campaign on GKE in November 2026: a three-zone cluster in us-central1 (one `e2-standard-2` node per zone) and a two-zone cluster in us-east1, Cloud SQL for PostgreSQL 17 in regional HA with a cross-region replica, Vault in HA, Redis, Prometheus and Vector, under a steady load of 5–20 requests per second (a quarter of them streams in the single-region runs) against a simulated provider that answers in about 0.87 s. The values and manifests of that run are in [`deploy/validation/gke-multiregion/`](https://github.com/m7gtw/gateway/blob/main/deploy/validation/gke-multiregion/README.md); it is a test setup, not a deployment profile, but every snippet on this page comes from it, without its secrets. [What was measured](#what-was-measured) lists every result in one table.

Before you start, read [operating on Kubernetes](/docs/operate/operations/) for the image, the Secret and the first Helm or Kustomize install. This page assumes that install works.

## 1. One node or a small cluster

The chart's defaults and the root Kustomization run **one gateway replica and one PostgreSQL** (the bundled StatefulSet), on whatever nodes the scheduler picks. That is a good start for evaluation and for a small team, and it gives you:

- **Upgrades without failed requests**, as long as the node has room for one extra Pod: the rollout starts the new replica first (`rollout.maxSurge: 1`, `maxUnavailable: 0`) and the old one drains before it stops ([drain](#drain-delay-and-termination-grace)).
- **Restarts that recover on their own**: liveness restarts a stuck gateway, and the gateway reconnects to PostgreSQL by itself when the database comes back.

It cannot give you:

- **Survival of a node loss.** One replica on a lost node is an outage until Kubernetes reschedules it; two replicas on the same node are no better.
- **A highly available database.** The bundled PostgreSQL is a single Pod on a single volume. When it restarts, every request that needs the database (managed keys, budgets, rate limits, team policies, usage) gets `503` until it is back; an upgrade that changes its environment restarts it once.
- **Zero-downtime database maintenance.** Backups, version upgrades and restores of the bundled server are yours to schedule.

When any of these matter, move to stage 2. You do not need to reinstall: the same release gains replicas, a managed database and the rest by `helm upgrade`.

## 2. One cluster across nodes and zones

Do these in order. The first four are values of the chart; the rest are the services around it.

### Replicas and topology spread

Run **at least three replicas, one per zone**, and spread them by node and by zone:

```yaml
autoscaling:
  enabled: true
  minReplicas: 3          # one per zone: losing a zone still leaves two
  maxReplicas: 6
  targetCPUUtilizationPercentage: 70
topologySpread:
  enabled: true           # spreads by node (kubernetes.io/hostname)
  maxSkew: 1
  whenUnsatisfiable: ScheduleAnyway
affinity:
  podAntiAffinity:        # and prefers a different zone for each replica
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          topologyKey: topology.kubernetes.io/zone
          labelSelector:
            matchLabels:
              app.kubernetes.io/name: gateway
              app.kubernetes.io/instance: gateway   # your release name
```

- **Why three:** with two replicas in three zones, a zone loss can leave one replica carrying all traffic while the replacement starts. With three, the run deleted a node's VM without draining it (two gateway replicas and a Vault member were on it) under 20 requests per second: **one request of 6,905 failed**, the one in flight on that node; the other replicas served everything else while GKE recreated the VM (about two minutes).
- **Why `ScheduleAnyway` and a preferred zone rule:** the chart's spread is by node. When the HPA adds replicas beyond one per node, a hard rule (`DoNotSchedule`) would leave them Pending; the preferred zone rule keeps the spread across zones whenever there is room. Use `DoNotSchedule` (as `values-ha.yaml` does) only when you have more nodes than `maxReplicas`.

### PodDisruptionBudget

```yaml
podDisruptionBudget:
  enabled: true
  maxUnavailable: 1
```

A node drain or a cluster upgrade then evicts one gateway Pod at a time and waits for its replacement. Keep `maxUnavailable: 1` (or `minAvailable` below `minReplicas`): a budget that allows no eviction blocks every node drain. Details in [high availability](/docs/operate/kubernetes-availability/#poddisruptionbudget-with-minavailable).

### Autoscaling

Start with CPU at 70% of the request, three to six replicas, and the shipped scale-down window of **300 s**. In the run, about 190 requests per second took the HPA from 3 to its maximum of 6 within the first minute, with **no failed request of 12,425**; once the load dropped, it was back at 3 replicas about 97 s later (the run shortened the window to 60 s to fit the test; keep 300 s in production, because a gateway's memory and connections fall later than its CPU). The HPA needs Metrics Server, and CPU utilization is a share of `resources.requests.cpu`: change the request and you change when it scales. To scale on tokens per second or in-flight requests instead, use [KEDA](/docs/operate/kubernetes-availability/#optional-keda).

### Drain delay and termination grace

Leave both at their defaults: a **10 s drain delay** in a Pod and a **180 s termination grace**.

- **Why 10 s:** when a Pod starts terminating, each node's kube-proxy stops sending it new connections on its own schedule. On a three-zone GKE cluster new connections kept arriving for up to about 3.5 s after SIGTERM. During the delay the replica is out of readiness but still serves everything that arrives, and it turns keep-alive off so clients reconnect elsewhere; 2 s was too short on a multi-node cluster and 10 s left no refused connection ([the measurements](/docs/operate/kubernetes-availability/#measured-on-a-multi-node-cluster)). With it, every rolling update, rollback and scale-down of the run finished with zero failed requests.
- **Why 180 s:** after the delay the replica waits up to `lifecycle.shutdown_timeout` (130 s, enough for a request at the two-minute budget to finish) and then flushes logs, traces and usage writes (up to 40 s). Helm refuses a `gateway.lifecycle.terminationGracePeriodSeconds` below drain + shutdown + 40 s. If your streams last longer than two minutes, raise `lifecycle.shutdown_timeout` and the grace together ([graceful shutdown](/docs/operate/shutdown/#size-the-external-grace-period)).

### Requests, limits and memory

```yaml
resources:
  requests: {cpu: 100m, memory: 128Mi}
  limits: {cpu: "1", memory: 384Mi}
```

These held every scenario of the run on `e2-standard-2` nodes, with no OOM kill of a main replica. Size them from your own traffic: the memory a replica needs follows in-flight streams, request bodies and caches, not the request rate.

**What an OOM kill does.** A second, small release with a 96 MiB limit and the gateway's own memory guards turned off was driven with 6 MB request bodies: the kernel killed it four times, and every request it held failed; the main release on the same nodes kept serving (1,109 of 1,109). So keep the guards on: with the defaults (`runtime.memory_limit_mib: 0` and `network.admission_memory_percent: 50`), the gateway reads the container's limit, sizes its heap and its request admission from it, and refuses excess load with a `503` that carries a `request_id` instead of being killed mid-response ([runtime](/docs/operate/runtime-configuration/), [network budgets](/docs/operate/network-configuration/)). A limit far below the default 384 Mi leaves those budgets too small to be useful.

### The database: managed PostgreSQL with HA

Use a managed PostgreSQL in high-availability mode (Cloud SQL `REGIONAL`, RDS Multi-AZ or similar), reached over a private address with TLS, and turn the bundled one off:

```yaml
# Helm values
database:
  bundled:
    enabled: false   # GATEWAY_DATABASE_URL in gateway.existingSecret names your database
gateway:
  existingSecret: gateway-secrets
  existingTrustSecret: gateway-trust   # mounts database-ca.pem at /var/run/gateway/trust
```

```yaml
# gateway YAML
storage:
  database:
    max_connections: 5     # per replica; see the sizing rule below
    min_connections: 1
    acquire_timeout: 2s
    startup_timeout: 60s
    tls:
      mode: dsn            # the URL's sslmode applies
```

```text
GATEWAY_DATABASE_URL=postgres://gateway:PASSWORD@10.100.0.3:5432/gateway?sslmode=verify-ca&sslrootcert=/var/run/gateway/trust/database-ca.pem
```

- **TLS:** Cloud SQL's server certificate does not name its private IP, so verify the CA (`sslmode=verify-ca` with the instance's server CA). With a database whose certificate names the host you connect to, use `tls.mode: verify_full` instead ([PostgreSQL](/docs/operate/managed-postgres/)). To keep the password out of the URL, let the chart build it from `database.external` and a username/password Secret ([external database](/docs/operate/operations/#external-database-from-a-username-and-password-secret)).
- **Pool size:** `max_connections` is per replica. Make the sum fit the server: `maxReplicas` + `rollout.maxSurge` + any other release, times `max_connections`, plus your own tools and the server's reserved connections, must stay below the server's `max_connections`. The run used 5 per replica: up to nine gateway replicas held at most 45 of the roughly 100 connections of a `db-custom-1-3840` instance. A larger pool is not more throughput; it only helps while requests wait for a free connection.
- **What a failover looks like.** The run triggered a Cloud SQL HA failover under load (10 requests per second on managed keys, 20 on a static key). For about **14 s** every request that needed the database was refused with `503` (`auth_unavailable`, `team_policy_unavailable`, `quota_unavailable`): fail-closed, so no request reached a provider without its key, policy and budget checks. Then service came back by itself; **no replica restarted** and nothing was redeployed. Static YAML keys are refused too, because their team policy and usage ledger live in the database. Clients should retry a `503`; the official OpenAI and Anthropic SDKs do by default.
- **Why readiness does not check the database:** every replica shares it, so an outage would take all of them out of the load balancer and replace the gateway's own `503` and its logs with a load balancer error. Alert on `gateway_database_up` instead ([alert rules](#prometheus-scraping-and-alert-rules)).

### Secrets: Vault in HA, or Kubernetes Secrets

**The simple option** is a Kubernetes Secret (`gateway.existingSecret`) with the database URL, the session and provider encryption keys and the provider keys. Every replica, and every region, must read the **same** session signing key and provider encryption key: a different one in a replica logs users out and cannot open the provider credentials stored in the database.

**For rotation without a rollout**, read the credentials from Vault (`secret_manager`, [secret managers](/docs/operate/secret-managers/)). Run it as three Raft members, one per zone, with TLS and a disruption budget:

```yaml
# HashiCorp Vault chart 0.34.1
server:
  ha:
    enabled: true
    replicas: 3
    disruptionBudget: {enabled: true, maxUnavailable: 1}   # quorum is two
    raft:
      enabled: true
      setNodeId: true
  topologySpreadConstraints: |
    - maxSkew: 1
      topologyKey: topology.kubernetes.io/zone
      whenUnsatisfiable: DoNotSchedule
      labelSelector:
        matchLabels:
          app.kubernetes.io/name: {{ template "vault.name" . }}
          app.kubernetes.io/instance: "{{ .Release.Name }}"
          component: server
```

with a `storage "raft"` block that has one `retry_join` per member, and point the gateway at the active member's Service (`secret_manager.address: https://vault-active.vault.svc:8200`).

- **Measured:** deleting the leader Pod under load elected a new leader in 9.5 s with **no failed request of 1,103**, because the gateway keeps serving its last good values while Vault is unreachable. A client key rotated in Vault took effect on every replica within about 3 s (`refresh_seconds: 10`), without a restart.
- **Auto-unseal for production.** A Vault member that restarts comes back **sealed** and serves nothing until it is unsealed. The run unsealed each member by hand after every restart (the node loss above left one sealed for about five minutes). With three members one sealed member is harmless, but a second restart before someone unseals the first loses quorum. Configure auto-unseal with your cloud's KMS so members rejoin by themselves.

### NetworkPolicy

Turn the chart's policy on, with egress restricted to what the gateway really calls. Your CNI must enforce it (GKE Dataplane V2 does):

```yaml
networkPolicy:
  enabled: true
  ingressFrom:
    - podSelector: {matchLabels: {gateway-client: "true"}}               # your in-cluster clients
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: monitoring}}   # Prometheus
    - ipBlock: {cidr: 130.211.0.0/22}   # Google load balancers and health checks:
    - ipBlock: {cidr: 35.191.0.0/16}    # container-native NEGs reach the Pods directly
  egress:
    enabled: true                       # DNS, the chart's own Collector and analytics store are added for you
    extraRules:
      - to: [{ipBlock: {cidr: 10.100.0.0/16}}]          # the managed database's private range
        ports: [{port: 5432, protocol: TCP}]
      - to:
          - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: vault}}
            podSelector: {matchLabels: {app.kubernetes.io/name: vault}}
        ports: [{port: 8200, protocol: TCP}]
      - to: [{podSelector: {matchLabels: {app: redis}}}]   # the shared cache
        ports: [{port: 6379, protocol: TCP}]
      - to: [{podSelector: {matchLabels: {app: vector}}}]  # the log shipper
        ports: [{port: 4318, protocol: TCP}]
      - to:                                                 # providers: public HTTPS only
          - ipBlock:
              cidr: 0.0.0.0/0
              except: [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16]
        ports: [{port: 443, protocol: TCP}]
```

- **Measured:** a client without the label could not reach the gateway; from inside a gateway Pod, port 80 on the internet and the Prometheus server were unreachable; HTTPS to a provider opened, and a real provider call through the gateway answered 200.
- **Why the last rule excludes private ranges:** a NetworkPolicy matches addresses, not names, and providers sit behind CDNs whose addresses change, so allow public 443 and keep everything inside your network closed unless a rule names it. A cloud workload identity needs its token endpoint too ([NetworkPolicy](/docs/operate/operations/#networkpolicy)). With the policy on and a load balancer that reaches Pods directly, forgetting the load balancer's ranges makes every backend unhealthy.

### Load balancer, Ingress and TLS

Put the gateway behind an Ingress or a cloud load balancer that terminates TLS, and give it a **backend timeout long enough for your longest stream** and **connection draining above the drain delay**. On GKE that is a `BackendConfig` on the gateway Service:

```yaml
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata: {name: ai-gateway}
spec:
  timeoutSec: 600                       # bounds a whole response, a stream included
  connectionDraining:
    drainingTimeoutSec: 30              # above the 10 s drain delay
  healthCheck:
    type: HTTP
    requestPath: /health/ready          # a draining replica answers 503 and leaves the backend
    port: 8080
    checkIntervalSec: 5
    timeoutSec: 5
    healthyThreshold: 2
    unhealthyThreshold: 2
```

```yaml
# Helm values
service:
  annotations:
    cloud.google.com/neg: '{"ingress": true}'
    cloud.google.com/backend-config: '{"default": "ai-gateway"}'
ingress:
  enabled: true
  className: ""                         # GKE reads the class from the annotation below
  annotations:
    kubernetes.io/ingress.class: gce
    kubernetes.io/ingress.allow-http: "false"
  hosts:
    - host: gateway.example.com
      paths: [{path: /, pathType: Prefix}]
  tls:
    - secretName: gateway-tls           # a kubernetes.io/tls Secret, or one a certificate controller writes
      hosts: [gateway.example.com]
```

- **Why 600 s:** a load balancer's default backend timeout (30 s on Google Cloud) cuts a stream that is still generating. Set it above the gateway's own [stream budgets](/docs/features/stream-timeouts/).
- **Why `/health/ready`:** readiness turns 503 at SIGTERM, so the load balancer stops choosing a draining replica before it closes its listener; liveness would keep sending traffic to it.
- **Behind HTTPS, set `admin.allow_insecure_http: false`** in the gateway YAML, so the console session cookie is `Secure` ([hardening](/docs/security/hardening/)).
- **Measured** through the GKE Ingress with TLS: 40 of 40 requests served (half of them streams), and a rolling update through it served **2,155 of 2,155**. The run used a certificate from a Secret; a cloud-managed certificate changes only where the certificate comes from.

With another controller, set the same three things through its annotations: response buffering off for streaming, a read timeout above the longest stream, and readiness as the health check ([Ingress](/docs/operate/operations/#ingress)).

### A shared cache on Redis over TLS

The default cache lives in each replica's memory, so with several replicas the same request can miss on every one of them. To share the [exact cache](/docs/features/exact-cache/) across replicas, run Redis (or use a hosted one) with TLS and a password, and select it:

```yaml
features:
  exact_cache: true
  distributed_exact_cache: true
cache_backend:
  backend: redis
  namespace: gateway_production
  url_env: GATEWAY_CACHE_URL            # rediss://user:password@redis.m7gtw.svc:6379/0, in the Secret
  key_env: GATEWAY_CACHE_KEY            # random 32 bytes, base64: encrypts the entries
  tls:
    enabled: true
    ca_file: /var/run/gateway/trust/ca.pem
    server_name: redis.m7gtw.svc
```

- **Measured:** an embeddings request answered as a miss by one replica was a hit on another. With the Redis Pod deleted, requests kept being served (straight from the provider). When Redis came back empty (it ran without persistence), the next request was a miss and the one after a hit again, with no restart of the gateway.
- **Why a cache can be lost safely:** it is never a source of truth. Keys, budgets and usage stay in PostgreSQL, and every request is authorized before the lookup. Size Redis's `maxmemory` with an eviction policy, keep it on a private network behind a NetworkPolicy that admits only the gateway Pods, and leave persistence off unless warm restarts matter to you ([cache backends](/docs/operate/cache-backends/)).

### Adding the analytics store later

You can start with PostgreSQL alone and add the [analytics store](/docs/features/analytics-store/) to a running release. Upgrade with an overlay that turns the bundled store on, and a gateway YAML whose `analytics_store` block names it and whose `analytics_store_usage` flag is on:

```yaml
# analytics-store.yaml
analyticsStore:
  bundled:
    enabled: true
    storage: 20Gi
```

```bash
helm upgrade gateway deploy/helm/gateway -n m7gtw --reuse-values \
  -f analytics-store.yaml --set-file gateway.config=gateway.yaml --atomic --wait --timeout 15m
```

The chart adds the gateway's egress rule to the store and the store's own NetworkPolicy. **Measured:** the upgrade ran under load with **no failed request of 1,859**; new usage rows reached the store within 1.5 s, survived a restart of its Pod (they live on its volume), and the copy resumed 1.5 s after it was back. `gateway-secrets` must hold `GATEWAY_ANALYTICS_STORE_PASSWORD` before the upgrade.

### Shipping logs over OTLP

The gateway exports its logs over OTLP. To keep them in object storage without running a Collector, send them to a [Vector](/docs/features/observability/#on-kubernetes-vector-to-cloud-storage) Deployment that writes NDJSON to a bucket, and point the gateway at it:

```yaml
# Helm values: the chart's variable wins over the YAML whenever its Collector is on
gateway:
  otlpLogsEndpoint: http://vector:4318/v1/logs
```

plus `features.otlp_logs: true` and `telemetry.otlp.logs_endpoint` in the gateway YAML, and an egress rule to Vector on 4318.

- **Measured:** turning it on was a `helm upgrade` under load with **no failed request of 1,782**. The request IDs of 40 requests were all found in the bucket within about 27 s (Vector writes an object every 10 s), and no secret value or secret-shaped string (provider keys, gateway tokens, bearer values) appeared in any object. Deleting the Vector Pod under traffic did not affect a request.
- **Make the shipper durable.** The gateway's log queue holds 1,024 records and does not retry a failed batch, so records produced while Vector is down are dropped and counted in `gateway_otel_dropped_total{signal="logs"}` (none were lost in the run's short outage). Give Vector a persistent buffer or two replicas when the logs must survive its restarts, and alert on that counter (`GatewayTelemetryDropping` does).

### Prometheus scraping and alert rules

With the Prometheus Operator, let the chart render the scrape target, the shipped alert rules and the SLO rules:

```yaml
serviceMonitor:
  enabled: true
  interval: 15s
  scrapeTimeout: 10s
  labels: {release: monitoring}   # must match your Prometheus's serviceMonitorSelector and ruleSelector
  alertRules: true
  sloRules: true
```

Allow the Prometheus namespace in `networkPolicy.ingressFrom`. **Measured:** every replica was scraped, the shipped alert rules and the two SLO burn-rate alerts were loaded, and `GatewayDatabaseDown` fired about 140 s after the database was cut off (its `for` is two minutes) and resolved 27 s after it came back. Route `GatewayDatabaseDown`, `GatewayUsageWriteFailures` and `GatewayCircuitOpen` to a pager: the gateway's own operational events are stored in PostgreSQL and cannot announce a database outage ([alert rules](/docs/features/observability/#alert-rules)).

### Upgrades and rollbacks

Pin the image by digest, back up the database, and roll out with Helm or Kustomize:

```bash
# Helm
helm upgrade gateway deploy/helm/gateway -n m7gtw -f values.yaml \
  --set image.repository=registry.example.com/gateway --set image.digest=sha256:<digest> \
  --set-file gateway.config=gateway.yaml --atomic --wait --timeout 15m
helm rollback gateway <revision> -n m7gtw --wait

# Kustomize: one overlay per version, applied server-side
kubectl apply --server-side --field-manager=ai-gateway -k overlays/production
kubectl -n m7gtw rollout status deploy/ai-gateway --timeout=10m
```

**Measured, each under 20 requests per second with a quarter of them streams:** a Helm upgrade to a new image (1,752 requests), a Helm rollback (1,552), a Kustomize upgrade (1,384) and a Kustomize rollback (2,467) all finished with **zero failed requests**. The first new Pod applies pending migrations under a lock while the others wait. A rollback restores the Deployment, not the schema: once a release has migrated, roll back by restoring the backup or fix forward ([upgrading and rolling back](/docs/operate/operations/#upgrading-and-rolling-back)).

**From 0.0.1-rc.2:** rename the infrastructure keys first ([upgrading from 0.0.1-rc.2](/docs/operate/operations/#upgrading-from-001-rc2-infrastructure-names)), then upgrade with the new chart, values, YAML and image in one `helm upgrade` **without `--reuse-values`** (the old value names are refused) and **with `nameOverride: ai-gateway` in the values** (the chart's earlier name, which keeps every object name and label; [names and upgrading](/docs/operate/product-names/)). In the run, that upgrade served 1,612 requests with **no failed request**; 67 of them (about 4%) were `503 draining` answers from the old replicas, which drain with rc.2's 2 s delay. The first new Pod applied the two pending migrations. Clients that retry a `503` see none of it.

### Checklist for one cluster

- [ ] Image pinned by digest, pushed to a registry the nodes can pull from.
- [ ] Three or more replicas, HPA 3–6 on CPU, spread by node and zone; PDB `maxUnavailable: 1`.
- [ ] Drain delay and grace left at 10 s and 180 s, or raised together for longer streams.
- [ ] Requests and limits set; memory guards at their defaults.
- [ ] Managed PostgreSQL in HA, private address, TLS verified; bundled PostgreSQL off; pool sum below the server's limit; backups and point-in-time recovery on.
- [ ] One set of session and encryption keys for every replica; Vault in HA with auto-unseal, or Kubernetes Secrets.
- [ ] NetworkPolicy on, egress limited to the database, secrets, cache, log shipper and public 443, load balancer ranges admitted.
- [ ] Load balancer with TLS, backend timeout above the longest stream, draining above 10 s, health check on `/health/ready`; `admin.allow_insecure_http: false`.
- [ ] Shared cache on Redis over TLS (when you use the exact cache).
- [ ] Logs shipped over OTLP to a durable destination; Prometheus scraping with the alert and SLO rules; `GatewayDatabaseDown` paged.
- [ ] An upgrade and a rollback rehearsed under load in a staging namespace.

## 3. Several clusters or regions

### The model: one write authority

Run **one PostgreSQL primary** (in HA in its home region) as the only place that accepts writes, **a gateway fleet in each region** that serves inference, **a cross-region replica** of the database that you promote if the home region is lost, and **a global load balancer** that sends each client to the nearest healthy region.

| | Shared by every region | Per region |
| --- | --- | --- |
| Database | The primary, and later the promoted replica | — |
| Managed keys, budgets, rate limits, team policies, usage, audit | Yes: they are rows in that database, so they are exact everywhere | — |
| Session signing key, provider encryption key | Yes: the same values in every fleet | — |
| Gateway YAML | — | Each fleet has its own (providers, static keys with their own IDs, the regional cache URL) |
| Exact cache (Redis) | — | One per region |
| Prometheus, log shipper | — | One per region, with an external label `region` |

**Why one writer:** keys, budgets and limits stay exact without conflict resolution, and a revoked key is revoked everywhere at once. The cost, which the rest of this section sizes for: a region far from the primary pays the round trips on every request, and while the home region is lost nobody can write until you promote the replica.

### The database URL lists both hosts

Give every fleet a URL with the primary first and the replica second, and ask for the one that accepts writes:

```text
GATEWAY_DATABASE_URL=postgres://gateway:PASSWORD@10.100.0.3:5432,10.100.1.5:5432/gateway?sslmode=verify-ca&sslrootcert=/var/run/gateway/trust/database-ca.pem&target_session_attrs=read-write
```

```yaml
storage:
  database:
    connect_timeout: 1s    # below acquire_timeout: a dead first host costs at most 1 s
    acquire_timeout: 2s
    startup_timeout: 60s
    tls:
      mode: dsn            # multi-host URLs need it
```

- **`target_session_attrs=read-write`** makes each new connection skip a host that only reads, so after a promotion the fleets find the new primary without a redeploy.
- **`connect_timeout` below `acquire_timeout`.** A stopped primary usually stops answering instead of refusing, so every new connection waits `connect_timeout` on it before trying the replica. If that wait is longer than `acquire_timeout`, a request that needs a new connection always fails. The gateway refuses to start with two hosts and `connect_timeout` not below `acquire_timeout`. **1 s worked** on a private network in the run.
- **`sslrootcert`** is one bundle holding both instances' server CAs.

### A global load balancer in front

Put one global load balancer over the gateway endpoints of both clusters (on Google Cloud, an external Application Load Balancer over the clusters' standalone zonal NEGs), with the same health check, backend timeout and draining as in stage 2:

```yaml
# A second Service over the same gateway Pods, for the global load balancer's NEGs;
# the chart's Service keeps the Ingress NEG, so each NEG has one owner.
apiVersion: v1
kind: Service
metadata:
  name: gateway-global
  annotations:
    cloud.google.com/neg: '{"exposed_ports": {"8080": {"name": "gateway-region-a"}}}'
spec:
  type: ClusterIP
  selector:
    app.kubernetes.io/name: gateway
    app.kubernetes.io/instance: gateway
  ports:
    - {name: http, port: 8080, targetPort: http}
```

- **Measured:** clients in each region reached their own region. When region A's gateways were scaled to zero under 10 requests per second, traffic moved to region B: **53 of 1,400 requests failed, all within about 40 s**, while the load balancer's health checks (every 5 s, two failures to mark a backend down) caught up with the endpoints that had gone; then region B served everything. That window is the cost of losing a region's fleet: shorter health-check intervals narrow it, client retries hide most of it.

### Size the remote region for the round trips

Every request in a region far from the primary pays several round trips to it: the key, the team policy and the budget on the way in, the usage on the way out. Between us-central1 and us-east1 that added about **0.66 s per request** (median 1.53 s against 0.87 s in the home region), for managed and static keys alike. Three settings follow from it, in the remote region only:

- **A larger pool.** Each request holds a connection for longer, so the same rate needs more of them: 5 connections per replica refused requests under 20 requests per second, **25 held**. Recheck the server's connection budget with the larger number.
- **A longer `admission_timeout`.** Each database step of a request's admission must finish within `storage.database.admission_timeout` (default 2 s), or the request is refused with `503` before any provider call. Start the remote region at **5 s**, watch the rate of `auth_unavailable`, `team_policy_unavailable`, `rate_limit_unavailable` and `quota_unavailable`, and raise it in steps ([a database far from the gateway](/docs/operate/managed-postgres/#a-database-far-from-the-gateway-admission_timeout)).
- **Latency budgets that include the trip.** Client timeouts, SLOs and alert thresholds for the remote region should expect the extra time.

```yaml
# gateway YAML of the remote region
storage:
  database:
    max_connections: 25
    connect_timeout: 1s
    acquire_timeout: 2s
    admission_timeout: 5s
```

### Promote the replica when the home region is lost

1. **Confirm the primary is really gone,** not just unreachable from one place. Promoting while the old primary still accepts writes would give you two writers.
2. **Fence the old primary** if you can still reach its control plane: stop it (on Cloud SQL, `gcloud sql instances patch PRIMARY --activation-policy=NEVER`). It must not come back as a writable server while the fleets still list it first.
3. **Promote the replica:** `gcloud sql instances promote-replica REPLICA` (or your provider's equivalent).
4. **Do nothing to the gateways.** With the two-host URL above, both fleets find the new primary by themselves.
5. **Verify:** a key created shortly before the stop authenticates in both regions (nothing was lost), and the `GatewayDatabaseDown` alerts resolve.
6. **Afterwards:** the promoted instance is a standalone server. Make it highly available, create a new cross-region replica, and in your next rollout reorder the URL (new primary first, new replica second) and remove the old primary from it.

**Measured** under 5 requests per second per region: requests were refused with `503` for about **48 s** in each region, from the moment the primary began to stop until the replica accepted writes. The promotion command returned 58 s after the stop command, and both regions were answering again 3–4 s after it (they had already resumed before it returned). A managed key written about two seconds before the stop worked in both regions afterwards: **no data lost**. **Nothing was redeployed or restarted.**

### What a partition does

When a region loses its path to the database (but not its clients), its gateways refuse with `503` every request whose admission needs the database, and no such request reaches a provider. In practice that is nearly every request: managed keys need their lookup, and static YAML keys still need their team policy and usage ledger. **Measured** with region B cut off for about 170 s: 1,657 of its 1,680 requests were refused; `GatewayDatabaseDown` fired in that region's Prometheus after about 134 s; the region served again as soon as the path came back, with no restart. Region A was unaffected.

Two things follow. A partitioned region is out of service, but its replicas stay ready (readiness deliberately does not check the database), so the global load balancer keeps sending it clients: when `GatewayDatabaseDown` fires in one region only, take that region's backend out of the global load balancer (or set its capacity to zero) until the path is back. And never "fix" a partition by pointing the region at a replica it can still reach: a replica only reads, and every admission check needs a writer.

### Shared limits and budgets across regions

A key's request rate limit or budget is one row in the one database, so it is exact across regions, but both regions contend for it.

- **Rate limits held exactly.** A key limited to 60 requests per minute, hit with 600 requests from both regions in the same minute, admitted exactly 60 (34 in the home region, 26 in the remote one) and refused the rest with `429`.
- **Budgets were never overspent, but the remote region lost the contention.** With a 0.50 USD budget hammered from both regions, the committed spend stopped at 0.48 USD. The home region admitted 23 requests; the remote region admitted none, because its reservations waited on the same row while carrying the cross-region round trips, and ran out of time (`503`).

So **give each region its own team, key or budget where the business allows it** (for example a budget per region that adds up to the total): each region then contends only with itself. Where a budget must be shared, raise `admission_timeout` in the remote region and expect it to win fewer reservations under contention.

### Checklist for several regions

- [ ] One primary in HA, a cross-region replica, both on private addresses reachable from every region.
- [ ] Every fleet: the two-host URL with `target_session_attrs=read-write`, `connect_timeout: 1s`, `tls.mode: dsn`, the same session and encryption keys.
- [ ] Remote regions: a larger pool (25 per replica held 20 requests per second), `admission_timeout` from 5 s, the server's connection budget rechecked.
- [ ] A cache, a Prometheus and a log shipper per region; the `region` label on every series.
- [ ] A global load balancer with readiness health checks, a long backend timeout and draining; clients retry `503`.
- [ ] Budgets and limits per region where possible.
- [ ] The promotion runbook written down, with who decides and how the old primary is fenced; rehearsed once.

## What was measured

GKE, November 2026; load as described at the top of this page. "Failed" counts requests that got no answer or a 5xx other than the documented `503 draining`.

| Scenario | Requests | Result |
| --- | --- | --- |
| Helm upgrade from 0.0.1-rc.2 (chart, values, YAML, image) | 1,612 | 0 failed; 67 `503 draining` from the old replicas |
| Helm upgrade to a new image | 1,752 | 0 failed |
| Helm rollback | 1,552 | 0 failed |
| Kustomize upgrade, then rollback | 1,384 + 2,467 | 0 failed |
| Node VM deleted without a drain (two gateway replicas and a Vault member on it) | 6,905 | 1 failed (in flight); VM back in about 2 min; the Vault member needed an unseal |
| Cloud SQL HA failover | 4,375 | `503` for about 14 s, then recovered; no restart |
| Vault leader Pod deleted | 1,103 | 0 failed; new leader in 9.5 s |
| Client key rotated in Vault | — | Applied on every replica within about 3 s |
| HPA 3 → 6 → 3 at about 190 requests per second | 12,425 + 1,852 | 0 failed; back to 3 replicas about 97 s after the load dropped |
| NetworkPolicy | — | Unlabelled client blocked; port 80 and Prometheus unreachable from the gateway; provider HTTPS open |
| Prometheus | — | All replicas scraped; alert and SLO rules loaded; `GatewayDatabaseDown` fired after about 140 s and resolved |
| Exact cache on Redis over TLS | — | Hit across replicas; served during Redis loss; miss then hit after it came back |
| Analytics store added by `helm upgrade` | 1,859 | 0 failed; rows in 1.5 s; survived the store's restart |
| Memory limit exceeded (small release, guards off) | 1,799 + 1,109 | The small release was OOM-killed and restarted; the main release had 0 failed |
| Ingress with TLS, then a rolling update through it | 40 + 2,155 | 0 failed |
| OTLP logs to Vector and Cloud Storage turned on by `helm upgrade` | 1,782 | 0 failed; all 40 request IDs shipped; no secret in any object |
| Two regions through the global load balancer | 900 | 0 failed; remote region about 0.66 s slower per request |
| Rate limit of 60 per minute hit from both regions | 600 | Exactly 60 admitted |
| Budget of 0.50 USD hit from both regions | 400 | 0.48 USD committed, never more; the remote region was refused under contention |
| Region B cut off from the database | 1,680 | Refused with `503`; alert after about 134 s; recovered with no restart |
| Region A's gateways scaled to zero | 1,400 | 53 failed within about 40 s; the rest served by region B |
| Primary stopped, replica promoted | 1,744 | About 48 s of `503` per region; no data lost; nothing redeployed |

## See also

- [Operating on Kubernetes](/docs/operate/operations/): the first install, NetworkPolicy, Ingress and upgrades in detail.
- [High availability on Kubernetes](/docs/operate/kubernetes-availability/): the HPA, PDB, spread and drain values, with earlier measurements.
- [PostgreSQL](/docs/operate/managed-postgres/): pool, timeouts, several hosts and a database far from the gateway.
- [Secret managers](/docs/operate/secret-managers/), [cache backends](/docs/operate/cache-backends/), [observability](/docs/features/observability/), [graceful shutdown](/docs/operate/shutdown/).
