
# Deploy to production

Run the gateway where your team can rely on it, and check that it is ready before anyone uses it.

From the root of a clone of the repository, with the Secrets and the values file from the sections below:

```bash
helm upgrade --install tokedex ./helm/tokedex \
  --namespace tokedex \
  -f release-values.yaml \
  --wait --timeout 10m
helm test tokedex --namespace tokedex
curl -sS https://gateway.example.com/readyz
```

```json
{"ok":true,"release":{"environment":"local"},"service":"tokedex"}
```

`helm test` passes when the gateway reports ready inside the cluster.

You need: Kubernetes 1.32 or later, `kubectl`, Helm 3.17 or later or Helm 4, a managed Postgres database and a role that owns it, a managed Redis endpoint, a StorageClass that provides `ReadWriteMany`, and an ingress controller with a TLS certificate for the gateway's hostname.

To try the gateway on your own computer first, follow the [Gateway quickstart](/gateway/quickstart).

## Create the gateway's keys

The release reads four keys from a Secret you create. Generate them once and keep them for the life of the installation.

```bash
kubectl create namespace tokedex
{
  printf 'TOKEDEX_MASTER_KEY=%s\n' "$(openssl rand -hex 32)"
  printf 'TOKEDEX_FINGERPRINT_KEY=%s\n' "$(openssl rand -hex 32)"
  printf 'TOKEDEX_VERIFIER_ROOT=%s\n' "$(openssl rand -hex 32)"
  printf 'TOKEDEX_PASSWORD_PEPPER=%s\n' "$(openssl rand -hex 32)"
} | kubectl -n tokedex create secret generic tokedex-keys --from-env-file=/dev/stdin
```

Copy the values into your secret manager: a restore needs them. Name the Secret in `release-values.yaml`, which each section below adds to; keep it outside the chart directory.

```yaml
secrets:
  existingSecret: tokedex-keys
```

The master key signs in to the dashboard. The other three must be the same on [every replica](#run-several-replicas).

## Pin the image

Pin the release you run. The `tokedex/gateway` image runs on AMD64 and ARM64; `0.1.1` is the current release.

```yaml
image:
  repository: tokedex/gateway
  tag: "0.1.1"
```

`image.digest` pins an immutable build and takes precedence over `image.tag`; set it in production, so every Pod, restore and rehearsal runs the build you tested. For a private registry, set `image.repository` to your mirror and list its pull Secrets in `imagePullSecrets`. To move to another release, see [Upgrades and migrations](/gateway/upgrades).

## Supply provider credentials

Save them in the dashboard after you sign in, as [Provider credentials](/gateway/provider-credentials) shows, or pass them in the gateway's environment under the provider's own variable, such as `OPENAI_API_KEY`.

Keep environment credentials in their own Secret, and pass each one as an entry of the `extraEnv` list in `release-values.yaml`:

```bash
printf 'OPENAI_API_KEY=%s\n' "$OPENAI_API_KEY" \
  | kubectl -n tokedex create secret generic tokedex-providers --from-env-file=/dev/stdin
```

```yaml
extraEnv:
  - name: OPENAI_API_KEY
    valueFrom:
      secretKeyRef:
        name: tokedex-providers
        key: OPENAI_API_KEY
```

## Connect Postgres and Redis

The gateway keeps its state in managed Postgres and Redis, which several replicas share. Put each connection string in a Secret under the key `url`, with the password percent-encoded and your provider's TLS parameters; use `rediss://` for Redis over TLS.

```bash
kubectl -n tokedex create secret generic tokedex-postgres \
  --from-literal=url='postgresql://tokedex:<password>@<postgres-host>:5432/tokedex'
kubectl -n tokedex create secret generic tokedex-redis \
  --from-literal=url='rediss://:<password>@<redis-host>:6379'
```

Several replicas also need a `ReadWriteMany` volume claim, which holds spend not yet written to Postgres and the key that encrypts stored provider credentials.

```yaml
postgresql:
  mode: external
  external:
    secretName: tokedex-postgres
redis:
  mode: external
  external:
    secretName: tokedex-redis
replicaCount: 3
persistence:
  accessMode: ReadWriteMany
  storageClass: <rwx-storage-class>
podDisruptionBudget:
  enabled: true
  minAvailable: 1
```

The gateway creates its database schema at first start. Choose the stores before the first install: a bound claim's access mode and StorageClass are fixed, and a later change of store copies no data. Helm uninstall keeps the gateway's volume claim.

The chart can also run Postgres and Redis inside the cluster (`mode: bundled`). For failover, TLS to the stores and managed backups, use managed services; keep bundled stores for a trial or staging cluster. Every value is in the [Helm chart guide](https://github.com/ArtificialAnalysis/tokedex/blob/main/helm/tokedex/README.md).

## Redis requirements

The Redis endpoint needs:

- `maxmemory-policy noeviction`, since every key the gateway writes is live state: an evicted cooldown sends traffic back to a provider key that was cooling.
- Persistence on, so a Redis restart keeps stored conversations.
- A standalone endpoint that runs scripts and answers before the gateway starts.

## Run several replicas

Every replica must share:

- Postgres, Redis and the `ReadWriteMany` claim.
- The verifier root, which checks every key and session; the fingerprint key, which identifies callers in the audit log; and the password pepper. All three are in `tokedex-keys`.
- The key that encrypts stored provider credentials, on the claim. To keep it in AWS KMS instead, set `custody.mode: kms` and `custody.kmsKeyId`, and pass `TOKEDEX_KEK_KMS_REGION` and AWS credentials with `extraEnv`.

Revoking KMS access blocks future unwraps. A running replica can still use provider credentials it has already decrypted. To stop that use, revoke the provider credential at the provider or stop every replica that loaded it.

To scale on CPU in place of `replicaCount`, which needs the Kubernetes resource metrics API:

```yaml
autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 10
```

A rollout replaces Pods one at a time. Keep `podDisruptionBudget.minAvailable` below the smallest replica count, and spread replicas across nodes with `topologySpreadConstraints`, as the [Helm chart guide](https://github.com/ArtificialAnalysis/tokedex/blob/main/helm/tokedex/README.md) shows, so a rollout or a lost node leaves one serving. Without the `ReadWriteMany` claim and Postgres, the chart runs one replica and stops the old Pod before it starts the new one, so a rollout briefly stops serving.

Once the first install has created the schema, set `postgresql.migrationMode: check`, so an upgrade never migrates the database under a replica of the earlier release; see [Upgrades and migrations](/gateway/upgrades#database-migrations).

## Serve the gateway over HTTPS

Set the public URL and the ingress to the same hostname. The chart refuses a `publicUrl` other than `https://` followed by `ingress.host`.

```yaml
publicUrl: https://gateway.example.com
ingress:
  enabled: true
  className: <ingress-class>
  host: gateway.example.com
  tlsSecretName: gateway-tls
```

[HTTPS and reverse proxies](/gateway/https) creates the TLS Secret, sets your controller's limits and timeouts, and names the proxies the gateway trusts.

## Check the release

1. Check that every gateway Pod is `Running` and ready, and that the log names both stores:

   ```bash
   kubectl -n tokedex get pods \
     -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway
   kubectl -n tokedex logs deployment/tokedex | grep 'State backends'
   ```

   ```text
   State backends (postgres+redis):
   ```

2. Open `https://gateway.example.com` and sign in with the master key, read from the Secret:

   ```bash
   kubectl -n tokedex get secret tokedex-keys \
     -o jsonpath='{.data.TOKEDEX_MASTER_KEY}' | base64 -d
   ```

Before the ingress is ready, run `kubectl -n tokedex port-forward svc/tokedex 4000:4000` and check `http://127.0.0.1:4000/readyz`. The dashboard answers only at the public URL, or at `127.0.0.1` while `publicUrl` is unset.

`/readyz` needs no key. It answers `503` and names the store in `unavailable` while Postgres or Redis does not answer.

## Hardening in the Helm chart

- The gateway runs as user and group 1000, never root, with a read-only root filesystem.
- Every Linux capability is dropped, privilege escalation is off, and the seccomp profile is `RuntimeDefault`.
- No service account token or service links are mounted.
- While `networkPolicy.bundledBackends` is `true`, the default, NetworkPolicies admit only the gateway and its migration Job to a bundled Postgres or Redis. Your cluster's network plugin must enforce them.

A claim you bring with `persistence.existingClaim` must be writable by user 1000. The chart sets `fsGroup: 1000`, which grants that on storage that honours it; the gateway need not own the claim's root.

## Outbound hosts

The gateway calls your Postgres and Redis endpoints, your providers' API hosts, your identity provider, your SMTP server, and, for Slack alerts, `slack.com` and Slack's webhook hosts. Requests to Slack go out directly, never through a proxy set in the gateway's environment.

## Recommendations

- **Keep the key-encryption key in AWS KMS, or back it up apart from the database.** One stolen backup then cannot open the stored provider credentials.
- **Restrict the dashboard to your network.** Clients need only `/v1`, and the dashboard is an administrative console.
- **Test a restore before anyone relies on the gateway.** A [backup](/gateway/backup-restore) you have not restored may lack a part, such as a Secret.

Next: [HTTPS and reverse proxies](/gateway/https), [Single sign-on](/gateway/single-sign-on) or [Backup and restore](/gateway/backup-restore).
