# Configure a deployment

After you [deploy to Cloudflare](/docs/deploy-cloudflare/), change a cluster by
editing its [settings file](#settings-file) and running `kite deploy`.

## Settings

| Setting                                 | What it changes                                                | First deploy only?                      | Section                                                                           |
| --------------------------------------- | -------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------- |
| `KITE_HOSTNAME`, `KITE_ZONE`            | Serves the API at your hostname instead of `workers.dev`       | Choose it before nodes join             | [Use your own hostname](#use-your-own-hostname)                                   |
| `KITE_CONSOLE_HOSTNAME`, `KITE_CONSOLE` | Where the web console is, or turns it off                      | No                                      | [Open the web console](#open-the-web-console)                                     |
| `KITE_LOCATION_HINT`                    | The region where Cloudflare stores the data                    | Yes                                     | [Data location](#data-location)                                                   |
| `KITE_JURISDICTION`                     | Keeps the data inside a jurisdiction, such as `eu`             | Yes. `kite deploy` refuses a change.    | [Data location](#data-location)                                                   |
| `KITE_OIDC_*`, `KITE_ACCESS_*`          | Who can sign in                                                | No                                      | [Set who can sign in](#set-who-can-sign-in)                                       |
| `KITE_POD_CIDR`, `KITE_SERVICE_CIDR`    | The pod and Service address ranges                             | Yes                                     | [Set the pod and Service networks](#set-the-pod-and-service-networks)             |
| `KITE_CLUSTER`                          | The name that node pools label their machines with             | Yes                                     | [Share a cloud project between clusters](#share-a-cloud-project-between-clusters) |
| `KITE_SCHEDULER_SCORING_STRATEGY`       | Which node gets a pod when several have room                   | No. Placed pods stay where they are.    | [Choose how pods spread over nodes](#choose-how-pods-spread-over-nodes)           |
| `KITE_MEMORY_MB`                        | The memory the control plane may use                           | No                                      | [Size the cluster for its memory](#size-the-cluster-for-its-memory)               |
| `KITE_NETWORK_PUBLIC_ENDPOINTS`         | Lets nodes in different networks connect                       | No                                      | [Join nodes in different networks](#join-nodes-in-different-networks)             |
| `KITE_REPLICAS`                         | The number of relays that hold node connections                | No                                      | [Keep nodes connected through a restart](#keep-nodes-connected-through-a-restart) |
| `KITE_COPY`                             | Copies the cluster to an S3 or R2 bucket                       | No                                      | [Keep a copy of the cluster](#keep-a-copy-of-the-cluster)                         |
| `KITE_BACKEND`, `KITE_CONTAINER_*`      | Runs the control plane in a Cloudflare Container, and its size | Set by `kite deploy move --container`   | [Move to a Cloudflare Container](/docs/move/#move-to-a-cloudflare-container)      |
| `KITE_AUTO_GROW`                        | Moves the cluster to a Container before memory refuses a pod   | No                                      | [Grow into a Container on its own](/docs/move/#grow-into-a-container-on-its-own)  |
| `KITE_SNAPSHOTS`                        | The bucket that stores sandbox snapshots                       | No                                      | [Store snapshots of sandboxes](#store-snapshots-of-sandboxes)                     |
| `KITE_AUDIT`                            | Writes a record of each API request to R2                      | No                                      | [Audit logs](#audit-logs)                                                         |
| `KITE_TELEMETRY_URL`                    | Where nodes and the control plane post telemetry               | No. Set it in the Cloudflare dashboard. | [Send node telemetry](#send-node-telemetry)                                       |

## Settings file

Each deployment keeps its settings and credentials in
`~/.kite/deployments/<name>/deploy.env`. The deployment's name is also the name
of its Worker. It is the value of `--name` or `KITE_WORKER`, and
`kite-control` by default. A variable that you export in your shell overrides
the same variable in the file.

:::caution
This directory contains the administrator token, the node bootstrap token, and
the key that encrypts your Secrets. Keep it private and back it up.
:::

## Cloudflare tokens

`kite deploy init` and `kite deploy credentials` use a short-lived
provisioning token to create the deploy token, `CLOUDFLARE_API_TOKEN`, which
later deploys use. To create the provisioning token:

1. Go to **My Profile → API Tokens → Create Token → Custom token**.
2. Add `API Tokens → Edit`. Add `Workers R2 Storage → Edit` for an audit log,
   and `Zone → Read` for a hostname.
3. Set it to expire in a day or less.

Kite deletes the provisioning token when setup finishes. To keep it for
setting up more clusters, set `KITE_KEEP_PROVISION_TOKEN=1`.

| Token                        | Kept in                  | Permissions                                               |
| ---------------------------- | ------------------------ | --------------------------------------------------------- |
| `CLOUDFLARE_PROVISION_TOKEN` | your shell, during setup | create tokens, write R2, read zones                       |
| `CLOUDFLARE_API_TOKEN`       | `deploy.env`             | see [Make the tokens yourself](#make-the-tokens-yourself) |
| `KITE_R2_TOKEN`              | `deploy.env`             | write objects in the audit bucket                         |

## How `kite deploy` changes the Worker

`kite deploy` shows a plan and asks you to approve it before it changes
anything. `--dry-run` shows the plan and stops. `--yes` skips the question.

`deploy.env` decides the Worker's `KITE_` settings that `kite deploy` passes,
such as the `KITE_OIDC_` settings, `KITE_ADDRESS`, `KITE_COPY` and
`KITE_SNAPSHOTS`. A deploy sets each one that the file sets,
and removes from the Worker each one that the file does not set, even one that
you set in the dashboard. The plan lists each variable that the deploy removes.
The Worker keeps `KITE_JURISDICTION`, `KITE_CLUSTER`, the `KITE_ACCESS_`
variables and any other variable that you set in the dashboard. If you edit a
variable in the dashboard while a deploy runs, the deploy overwrites your edit.

:::caution
If the account already has a Worker with this name and this settings file did
not deploy it, `kite deploy` stops with
`a Worker called <name> is already in this account`. Confirm that it is the
cluster you mean to manage, then run `KITE_ADOPT=1 kite deploy`.
:::

If your first deploy fails partway, run `kite deploy` again to finish it, or
`kite deploy destroy` to delete what it created. Neither needs `KITE_ADOPT`,
because the settings file records the Worker before the first upload.

## Deploy from CI

To give each pull request its own cluster, deploy it under a name for the pull
request, and pass `--yes` so that `kite deploy` and `kite deploy destroy` run
without asking. Put a deploy token in `CLOUDFLARE_API_TOKEN`, with the
permissions in [Make the tokens yourself](#make-the-tokens-yourself). For a
hostname or an audit log, [create the credentials first](#deploy-without-prompts).
In this example, `$PR` is the pull request's number:

```bash

kite deploy --name "kite-pr-$PR" --yes              # on each push
kite deploy destroy --name "kite-pr-$PR" --yes      # once it merges or closes
```

Keep `$KITE_HOME/deployments/kite-pr-$PR` between the jobs, where only they
can read it. It contains the cluster's credentials, and the record of the
Worker that it deployed. Without that record, a later deploy and `destroy`
refuse the Worker.

### Deploy without prompts

In a script, skip the questions of `kite deploy init`. Export the settings
that it asks for and the provisioning token, then run
`kite deploy credentials`:

```bash

kite deploy credentials
unset CLOUDFLARE_PROVISION_TOKEN
```

`kite deploy credentials` writes these variables to `deploy.env`. It does not
change a value that is already set.

| Name                    | Written when                                  |
| ----------------------- | --------------------------------------------- |
| `CLOUDFLARE_ACCOUNT_ID` | `kite deploy credentials` creates anything    |
| `CLOUDFLARE_ZONE_ID`    | `KITE_ZONE` is set                            |
| `CLOUDFLARE_API_TOKEN`  | always                                        |
| `KITE_R2_TOKEN`         | `KITE_AUDIT=1`, which also creates the bucket |

:::caution
It does not write `KITE_ZONE`, `KITE_HOSTNAME`, or `KITE_AUDIT`. Without them,
`kite deploy` deploys to `workers.dev` with no audit log, so add them to
`deploy.env`:

```bash
KITE_ZONE=example.com
KITE_HOSTNAME=kite.example.com
KITE_AUDIT=1
```

:::

#### Make the tokens yourself

To skip `kite deploy credentials`, set these variables in `deploy.env`
yourself. Kite does not create a credential for a variable that already has a
value.

| Name                    | Value                                              | Needed for                    |
| ----------------------- | -------------------------------------------------- | ----------------------------- |
| `CLOUDFLARE_API_TOKEN`  | a token with the permissions below                 | every deployment              |
| `CLOUDFLARE_ZONE_ID`    | the zone ID of `KITE_ZONE`                         | a hostname                    |
| `CLOUDFLARE_ACCOUNT_ID` | the account ID                                     | an audit log with no hostname |
| `KITE_R2_TOKEN`         | `<access-key-id>:<secret-access-key>` of an R2 key | an audit log                  |

| `CLOUDFLARE_API_TOKEN` permission            | Scope       | Needed for                         |
| -------------------------------------------- | ----------- | ---------------------------------- |
| `Account → Workers Scripts → Edit`           | the account | the Worker upload                  |
| `Zone → DNS → Edit`                          | the zone    | the DNS record for `KITE_HOSTNAME` |
| `Zone → Workers Routes → Edit`               | the zone    | the route to the Worker            |
| `Zone → Zone → Read`                         | the zone    | checking `CLOUDFLARE_ZONE_ID`      |
| `Account → Access: Apps and Policies → Edit` | the account | Cloudflare Access                  |
| `Account → Logs → Edit`                      | the account | the Logpush job                    |

Give the R2 key `Object Read and Write` on the
[audit bucket](#audit-logs) only.

## Use your own hostname

By default the API is at a `workers.dev` address. To use your own hostname,
answer yes to the hostname question in `kite deploy init`, or add:

```bash
KITE_ZONE=example.com
KITE_HOSTNAME=kite.example.com
```

The deploy also requires `CLOUDFLARE_ZONE_ID`, which `kite deploy credentials`
writes.

:::note
Cloudflare's Universal SSL certificate does not cover a hostname more than one
label below the zone, such as `kite.eu.example.com`. For such a hostname, order
an edge certificate.
:::

## Open the web console

With a hostname, the deploy also serves the web console on a hostname of its
own, one label below the zone, so that Universal SSL covers it:

| `KITE_HOSTNAME`    | Console                    |
| ------------------ | -------------------------- |
| `kite.example.com` | `kite-console.example.com` |
| `example.com`      | `console.example.com`      |

The console calls the API with each person's own sign-in, so it shows only what
their role allows. It never shares the API's hostname, because the API serves
pages from pods through its proxy, and such a page could read a signed-in
person's token.

To use another hostname in the zone, or to turn the console off:

```bash
KITE_CONSOLE_HOSTNAME=ops.example.com
KITE_CONSOLE=0
```

With an OIDC issuer, add the console's address, such as
`https://kite-console.example.com/`, to the redirect URIs of the client that
`KITE_OIDC_AUDIENCE` names. Behind Cloudflare Access, the console signs in
through the cluster and needs nothing more.

A deployment on `workers.dev` has no console yet.

## Data location

Cloudflare stores the cluster's data near where its first request came from,
and the data stays there. Set either value before the first deploy:

| Setting              | Example | Effect                                                                                                                    |
| -------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- |
| `KITE_LOCATION_HINT` | `weur`  | Stores the data near a [location hint](https://developers.cloudflare.com/durable-objects/reference/data-location/) region |
| `KITE_JURISDICTION`  | `eu`    | Keeps the data inside the jurisdiction. Overrides the location hint.                                                      |

A hint set on a cluster that already exists changes nothing.

:::caution
The first deploy sets the cluster's jurisdiction. A Worker that used another
jurisdiction would read a new, empty cluster. So when `KITE_JURISDICTION`
differs from the Worker's jurisdiction, `kite deploy` stops with
`refuses to change it`. To keep data in another jurisdiction, deploy a second
cluster with `kite deploy --name`, or [move the cluster](/docs/move/).
:::

## Set who can sign in

| Method                                        | Requires                                          | Variables                                |
| --------------------------------------------- | ------------------------------------------------- | ---------------------------------------- |
| [OIDC provider](#use-an-oidc-provider)        | A client registered with your provider            | `KITE_OIDC_ISSUER`, `KITE_OIDC_AUDIENCE` |
| [Cloudflare Access](#use-cloudflare-access)   | Your own hostname                                 | `KITE_ACCESS_ALLOW`, `KITE_ACCESS_ROLE`  |
| [Front proxy](#sign-in-through-a-front-proxy) | A proxy that signs people in and sends their name | `KITE_FRONT_PROXY_TOKEN`                 |

If you set up both OIDC and Access, the CLI uses OIDC. Then follow
[Sign in to a cluster](/docs/sign-in/).

### Use an OIDC provider

Set both values. If you set only one, OIDC stays off.

```bash
KITE_OIDC_ISSUER=https://issuer.example.com
KITE_OIDC_AUDIENCE='replace-with-client-id'
```

:::note
`kite login` signs in only at an `https` issuer whose discovery document names
that same issuer and lists `https` endpoints. Plain `http` works only for an
issuer on your own machine, at `127.0.0.1` or `localhost`.
:::

### Register a client with your OIDC provider

Register one client for the cluster:

| Setting      | Value                                                              |
| ------------ | ------------------------------------------------------------------ |
| Client type  | Public. `kite login` sends no client secret.                       |
| Grant        | Authorization code with PKCE, method `S256`                        |
| Redirect URI | `http://127.0.0.1/callback`, on any port                           |
| Scopes       | `openid email offline_access`, or `KITE_OIDC_SCOPES` if you set it |
| Client ID    | The value of `KITE_OIDC_AUDIENCE`                                  |

Without `offline_access`, a sign-in lasts only as long as the provider's ID
token. The ID token must contain the username and groups claims that
[Identity and access](/docs/identity/#usernames-and-groups) lists.

### Use Cloudflare Access

Access requires your own hostname. Add:

```bash
KITE_ACCESS_ALLOW=operator@example.com
KITE_ACCESS_ROLE=cluster-admin
```

| Setting             | Value                                                                                           |
| ------------------- | ----------------------------------------------------------------------------------------------- |
| `KITE_ACCESS_ALLOW` | One email address, a comma-separated list of addresses, or `@` followed by a domain             |
| `KITE_ACCESS_ROLE`  | An existing ClusterRole. The deploy binds it to each email address in the allow list.           |
| `KITE_ADMIN_GROUP`  | A group at your identity provider. The deploy binds it to `cluster-admin`, as `access:<group>`. |

After the first deploy, change who Access allows in Cloudflare Access, not in
the settings file. `kite deploy init` asks whether to make the allowed emails
cluster admins, and sets `KITE_ACCESS_ROLE=cluster-admin`.

Access does not put a domain in the token, so with `@example.com` in
`KITE_ACCESS_ALLOW`, bind a group instead: set `KITE_ADMIN_GROUP`, and have
your identity provider pass groups to Access. With `KITE_ACCESS_ROLE` and a
domain, the deploy stops before it changes anything.

A later deploy replaces the bindings named `kite-access` and
`kite-admin-group`, so a changed list or group takes effect.

### Sign in through a front proxy

A proxy in front of the cluster can sign people in and send each person's
identity to the cluster. Add a token that only the proxy knows, then run
`kite deploy`:

```bash
KITE_FRONT_PROXY_TOKEN='replace-with-a-long-random-token'
```

On each request, the proxy sends:

- the token as its bearer token
- the person's username in `X-Remote-User`
- each of their groups in `X-Remote-Group`

RBAC then grants what that user and those groups are allowed. The cluster
ignores these headers on a request without the token. When a person runs
`kubectl --as`, the cluster checks the impersonation against that person's own
permissions. To stop trusting the proxy, delete the line and deploy. The
deploy removes the token from the Worker.

:::caution
The proxy can assert any user and any group, including `system:masters`. Keep
the token as secret as `KITE_ADMIN_TOKEN`. Make the proxy remove any
`X-Remote-User` and `X-Remote-Group` headers that clients send.
:::

## Back up and rotate credentials

When the settings file does not contain them, `kite deploy` generates three
secrets:

| Secret                 | What it is                                                   |
| ---------------------- | ------------------------------------------------------------ |
| `KITE_ADMIN_TOKEN`     | The `system:masters` credential for bootstrap and recovery   |
| `KITE_BOOTSTRAP_TOKEN` | The credential a new node uses to join                       |
| `KITE_STORAGE_KEY`     | The key that encrypts stored Secrets and cluster credentials |

:::danger
Cloudflare never returns a stored secret, so the settings file contains the
only copy. If you lose `KITE_STORAGE_KEY`, nobody can read the encrypted data again.
:::

`kite deploy secrets` uploads the file's credentials to the Worker again.

### Rotate the storage key

Never replace `KITE_STORAGE_KEY` on its own. Rotate it in two steps:

1. Set `KITE_STORAGE_KEY` to the new key and `KITE_STORAGE_KEYS_RETIRED` to the
   old one. Deploy. When the cluster starts, it encrypts every Secret again
   under the new key.
2. Wait at least seven days. Then remove `KITE_STORAGE_KEYS_RETIRED` and deploy.

`deploy.env` records when a deploy first sent the retired key, as
`KITE_STORAGE_KEYS_RETIRED_SINCE`. A deploy that would drop the key sooner
refuses and says when it may.

### Rotate the signing key

Members of the admin group manage signing keys with the context that
`kite login` wrote. The admin token works too, for when sign-in is down:

```bash
kite signing-key list
kite signing-key rotate
```

The rotation disconnects each node whose credential the old key signed. Each
node connects again within seconds and gets a credential that the new key
signs. The old key stays until the last token it signed expires. To remove it
sooner, sign in again, because a token that the old key signed cannot manage
keys, and retire it:

```bash
kite login https://kite.example.com
kite signing-key retire <kid>
```

`retire` refuses a key that still signs a node's credential, and names the
nodes. A node that is offline holds its old credential until it connects
again. `retire` also refuses the active key: rotate it first.

If a key is compromised, retire it at once with `--force`, even if it is the
active key:

```bash
KITE_TOKEN=<admin-token> kite signing-key retire <kid> --force --server https://kite.example.com
```

:::caution
A forced retirement invalidates every credential the key signed, including
each node's credential that it signed. Those nodes go `NotReady` and stay so.
To join one again, [leave and remove the node](/docs/manage-nodes/#leave-and-remove-a-node),
then [join the host](/docs/manage-nodes/#join-an-existing-host) with a new
bootstrap token.
:::

## Set the cluster address

Set `KITE_ADDRESS` when the cluster serves more than one hostname, such as
while you move it to a new hostname:

```bash
KITE_ADDRESS=https://kite.example.com
```

The cluster then uses this address, whichever hostname a request arrived on:

- Machines that a node pool creates join the cluster at this address.
- Browsers sign in at this address.
- The node pool issuer is this address followed by `/kite/nodepools`. This is
  the issuer that `kite nodepool verify` prints, and that your cloud provider
  trusts.
- Tokens that the cluster signs have this address as their issuer, unless you
  set `KITE_ISSUER`.

Without `KITE_ADDRESS`, the cluster takes its address from each request.
On your own servers, the server then serves only the hostnames in its
certificate: `localhost`, its loopback addresses, the address it listens on,
and each `--tls-name`. It refuses a request for any other hostname with `421
Misdirected Request`, because the hostname decides which tokens authenticate.
Behind a proxy that sends its own hostname, set `KITE_ADDRESS`.

:::caution
Your cloud provider trusts one node pool issuer. Without `KITE_ADDRESS`, a
request to the cluster's other hostname changes the node pool issuer, and the
address that new machines join at. The provider then refuses the pool's
credentials, and the pool creates no machines.
:::

## Set the cluster issuer and browser origins

`KITE_ISSUER` sets the `iss` claim in the tokens that the cluster signs. Set it
only when a pod, or another program that verifies the tokens, cannot connect
to the cluster's address:

```bash
KITE_ISSUER=https://issuer.example.com
```

:::caution
Setting `KITE_ADDRESS` without `KITE_ISSUER` also changes the issuer of every
token that the cluster signs. Tokens signed for another address stop working.
People must sign in again, and the cluster refuses a pod's token until the pod
renews it.
:::

To let a browser application on another origin call the API, add its origin:

```bash
KITE_ALLOWED_ORIGINS=https://app.example.com
```

The web console signs in through the cluster when Cloudflare Access is in
front of it, so the cluster sends it a sign-in code. Set its origin, which must
use HTTPS, or HTTP on `localhost`:

```bash
KITE_CONSOLE_ORIGIN=https://console.example.com
```

The cluster then sends a code to a page on that origin as well as to
`kite login` on your own machine, and lets the console read its responses, so
the origin needs no entry in `KITE_ALLOWED_ORIGINS`. A value that is not an
origin, such as one with a path, stops the cluster from starting, and the error
names the setting.

## Set the pod and Service networks

Choose both ranges before the first deploy, in the same IP family, with no
overlap. Dual-stack is not supported.

| Setting             | IPv4 default   | IPv6 example           |
| ------------------- | -------------- | ---------------------- |
| `KITE_POD_CIDR`     | `10.64.0.0/11` | `fd12:3456:789a::/48`  |
| Per-node pod prefix | `/24`          | `/64`                  |
| Most nodes          | 8,192          | 65,536                 |
| `KITE_SERVICE_CIDR` | `10.96.0.0/16` | `fd12:3456:789b::/112` |

Each node gets one per-node prefix from the pod range, so an IPv4 `/16` has
room for 256 nodes. Pick a range for the largest cluster you expect. When the
pod range is full, the cluster refuses the next node with
`the pod network 10.64.0.0/11 is full`.

:::caution
You cannot change either range on an existing cluster, and `kite deploy` does
not stop you. If you change a range, node joins and Service writes fail with
`cannot change KITE_POD_CIDR or KITE_SERVICE_CIDR on an existing cluster`.
Deploy again with the original values to recover.
:::

## Share a cloud project between clusters

A node pool labels its machines with the cluster name, `KITE_CLUSTER`. The
deploy that creates a cluster sets it to the deployment's name, which is
`kite-control` unless you pass `--name`, and writes it to `deploy.env`. A
cluster with no `KITE_CLUSTER` set is called `kite`. To choose the name, set it
before the first deploy:

```bash
KITE_CLUSTER=production
```

A deploy to an existing cluster never sets its name. If you change
`KITE_CLUSTER` on a cluster that has machines, its pools no longer find the
machines labelled with the old name, and nothing deletes those machines.

:::caution
A node pool deletes each machine in its project that has the pool's
`kite-cluster` and `kite-pool` labels, if the pool has no claim for that
machine. So two clusters with the same `KITE_CLUSTER` and pool name delete
each other's machines. Give every cluster in a shared project its own value.
:::

`kite nodepool connect gcp` and `kite nodepool connect aws` read the name from
the cluster, so the commands that they print use the same cluster name as the
machines' labels.

## Choose how pods spread over nodes

`KITE_SCHEDULER_SCORING_STRATEGY` sets which node the scheduler picks for a pod
when several nodes have enough free capacity:

| Value            | The scheduler prefers                 | Use it for                     |
| ---------------- | ------------------------------------- | ------------------------------ |
| `LeastAllocated` | the node with the most free capacity  | spreading load (the default)   |
| `MostAllocated`  | the node with the least free capacity | node pools that fit large pods |

Use `MostAllocated` with a node pool. With `LeastAllocated`, small pods spread
over every node. Once the pool reaches its `limits`, a large pod then stays
Pending with `Insufficient cpu`. Changing the strategy does not move pods that
are already placed.

## Size the cluster for its memory

`KITE_MEMORY_MB` is the memory, in megabytes, that the cluster's control plane
may use. Set it when a Worker in your own workerd has more memory, or when the
control plane shares its machine with other work:

```bash
KITE_MEMORY_MB=2048
```

| Where the control plane runs | Default                                                                                             |
| ---------------------------- | --------------------------------------------------------------------------------------------------- |
| A Cloudflare Worker          | 128, the memory of a Cloudflare Worker                                                              |
| Your own hosts               | A quarter of the machine's memory, or of its container's memory limit when lower, from 128 to 4,096 |

On your own servers, the self-hosted control plane can use up to twice this
memory. A value that is not a whole number stops the cluster from starting,
with `KITE_MEMORY_MB must be a whole number of megabytes`.
[How it works](/docs/how-it-works/#memory) says how the control plane
divides this memory.

On a Worker, the control plane refuses new pods once either of its Durable
Objects has allocated more than three quarters of this memory, and keeps
running the pods it has. A create fails as an exceeded ResourceQuota fails it,
with `exceeded the control plane's memory`, and a ReplicaSet records the
refusal in a `FailedCreate` Event and creates the pod once memory frees. To run
more pods, [move the cluster to a Cloudflare Container](/docs/move/#move-to-a-cloudflare-container)
or [to your own server](/docs/move/#move-from-a-worker-to-your-own-server). With
`KITE_AUTO_GROW=container`, the cluster
[moves itself to a Container](/docs/move/#grow-into-a-container-on-its-own)
once its memory has stayed at `MemoryLow` for 10 minutes.

You learn of it before the first refusal:

- The [cluster summary](/docs/reference/resources/#read-the-cluster-summary)
  shows each object's memory, and names it in `attention` from four fifths of
  that three quarters, with the reason `MemoryLow`, and past it, `MemoryFull`.
- A Warning Event on the summary says when the memory passes each.
- The API server's `/metrics` serves `kite_control_plane_memory_bytes`, by
  `object`, and `kite_control_plane_memory_refusal_bytes`.

If the Durable Object that schedules pods and runs the controllers stops
responding, the other one takes over that work only when both together are
below that three quarters. Otherwise pods wait to be scheduled until it
responds, and the control plane tries it again within 5 minutes.

## Join nodes in different networks

Nodes in one VPC connect to each other on their private addresses. To let
nodes in different networks or clouds connect to each other:

1. Set `KITE_NETWORK_PUBLIC_ENDPOINTS` and deploy again:

   ```bash
   KITE_NETWORK_PUBLIC_ENDPOINTS=Allowed
   ```

2. In each cloud's firewall, open UDP port 51820 from anywhere to each node
   that has a public address.

| Value      | The cluster                                               |
| ---------- | --------------------------------------------------------- |
| `Disabled` | sends no node's public address to its peers (the default) |
| `Allowed`  | sends each node's public address to its peers             |

A node tries a peer's private address first, so nodes in one VPC keep using
private addresses. To check how many peers a node connects to on a public
address, run:

```bash
kubectl get nodenetworkstatus node-1 -o jsonpath='{.status.peers}'
```

```
{"noPath":0,"public":1,"reachable":2,"unknown":0,"unreachable":0,"unreachableFrom":0}
```

## Keep nodes connected through a restart

Each node connects to one of four relays, which keep it connected when the
cluster's Durable Object restarts. [How it works](/docs/how-it-works/#serverless)
explains them. Set the number of relays and deploy again:

```bash
KITE_REPLICAS=8
```

- With more or fewer relays, most nodes move to another relay the next time
  they connect.
- With `KITE_REPLICAS=0`, every node connects to the cluster's Durable Object
  instead. An idle cluster then costs less, but every node disconnects and
  connects again each time the object restarts, and a burst of new pods can
  disconnect most of them.

[Control plane costs](/docs/cost/) shows what a cluster with relays costs.

## Keep a copy of the cluster

The cluster's Durable Object can copy the cluster to an S3 or R2 bucket that
you own. A [server of your own](/docs/deploy-servers/) with the same
`KITE_STORAGE_KEY` can restore the cluster from the copy, and
[Move a cluster](/docs/move/) moves it through the copy. Set the bucket and the
access key that writes to it, then deploy again:

```bash
KITE_COPY=s3://<bucket>/<prefix>
KITE_COPY_ACCESS_KEY_ID=<key id>
KITE_COPY_SECRET_ACCESS_KEY=<secret>
KITE_COPY_ENDPOINT_URL=https://<account>.r2.cloudflarestorage.com
KITE_COPY_REGION=auto
```

Point `KITE_COPY` at an empty prefix. For an S3 bucket, leave out
`KITE_COPY_ENDPOINT_URL` and set `KITE_COPY_REGION` to the bucket's region.

The object uploads writes to the bucket after they commit, at most four times
a second. To start uploads further apart, set `KITE_COPY_SPACING_MS`, such as
`1000` for at most one a second. The copy then costs fewer requests, and the
latest writes reach it later.
[Control plane costs](/docs/cost/#a-copy-in-a-bucket) lists what each costs.

The copy contains everything that the cluster stores. Secrets in the copy are
encrypted with the cluster's `KITE_STORAGE_KEY`.

:::note
Once another server takes over the copy, the Durable Object returns 503 for
every request.
:::

To move the cluster to another Worker or to your own servers, see
[Move a cluster](/docs/move/).

## Store snapshots of sandboxes

You take a snapshot of a sandbox in a [SandboxPool](/docs/sandbox-pools/)
through the pool's `snapshots` subresource. Kite stores each snapshot in an S3
or R2 bucket that you own. Set the bucket and an access key that can read and
write objects under its prefix, then deploy again:

```bash
KITE_SNAPSHOTS=s3://<bucket>/<prefix>
KITE_SNAPSHOTS_ACCESS_KEY_ID=<key id>
KITE_SNAPSHOTS_SECRET_ACCESS_KEY=<secret>
KITE_SNAPSHOTS_ENDPOINT_URL=https://<account>.r2.cloudflarestorage.com
KITE_SNAPSHOTS_REGION=auto
```

For an S3 bucket, leave out `KITE_SNAPSHOTS_ENDPOINT_URL` and set
`KITE_SNAPSHOTS_REGION` to the bucket's region. For a temporary key, also set
`KITE_SNAPSHOTS_SESSION_TOKEN`. Without `KITE_SNAPSHOTS`, the cluster refuses
a request for a snapshot.

Your nodes upload and download each snapshot through a URL that the control
plane signs, so they never get the key. They must be able to connect to the
bucket's endpoint over HTTPS. Kite stores each snapshot as
`<prefix>/snapshots/<namespace>/<id>.tar`, and the memory of a memory snapshot
beside it as `<id>.memory.tar`.

:::note
On a gVisor node that an earlier release prepared, a sandbox that starts from
a snapshot fails with `RestoreFailed`. Run the prepare script on the node
again, as in
[Add a runtime to a host you joined](/docs/sandboxed-runtimes/#add-a-runtime-to-a-host-you-joined).
:::

## Audit logs

With audit logs on, the cluster writes one [record](/docs/security/#audit-logs)
per API request to an R2 bucket that you own. Create the R2 key and the bucket
with `kite deploy credentials`, then run:

```bash

kite deploy
```

If a credential is missing, the deploy says so and deploys the Worker without
the Logpush job. Add the credential, then run `kite deploy audit` and
`kite deploy control`.

| Setting                 | Default                                       |
| ----------------------- | --------------------------------------------- |
| `KITE_AUDIT_BUCKET`     | The Worker's name plus `-audit`               |
| `KITE_AUDIT_OMIT_USERS` | None                                          |
| Object prefix           | `YYYYMMDD`, one per day, at the bucket's root |
| Retention               | Your bucket's lifecycle rule. Kite sets none. |

`KITE_AUDIT_OMIT_USERS` accepts a comma-separated list of usernames. A request
from one of these users writes no record, even when it impersonates someone
else. List only a caller whose changes you record another way, such as a
proxy's own service account.

:::note
Every deploy of the Worker, `kite deploy control` and `kite deploy secrets`
included, creates the Logpush job first. A Worker deployed before the job
exists writes empty records until you deploy it again.
:::

To turn audit logs off, set `KITE_AUDIT=0` and deploy. The Logpush job stays
until you delete it.

### Read the audit records

Logpush writes each record inside a trace event. This example reads one day's
records through an rclone remote named `r2`, and extracts them with `jq`:

```bash
rclone cat r2:kite-control-audit/20260910/ | jq -r '.Logs[].Message[]' | jq .
```

## Send node telemetry

Set `KITE_TELEMETRY_URL` as a Worker variable in the Cloudflare dashboard. Each
node then posts [OTLP/JSON telemetry](/docs/reference/node-agent/#agent-telemetry)
under that URL.

The control plane also posts under that URL once a minute, as the service
`kite-control`:

| Path            | What it sends                                                                                                                                                     |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<url>/metrics` | The cluster's counts and the request, pod start and sandbox histograms. See [Control plane metrics](#control-plane-metrics).                                      |
| `<url>/logs`    | One record per node milestone: a node pool machine created, launched, registered, ready or failed, and each agent update's start and end. A failure is at `WARN`. |
| `<url>/traces`  | One span per request that included a credential, named by its verb and resource.                                                                                  |

A server error's span also has the error's message as its status, its
namespace as `k8s.namespace.name`, and, for a request to a sandbox, its pool as
`kite.sandboxpool.name`.

### Control plane metrics

| Metric                                                                               | Measures                                                                                            | Labels                                                                         |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| OpenTelemetry's names, such as `k8s.pod.status.phase`                                | Pods by namespace and phase, containers by the reason they wait or ended, node conditions, Job Pods | OpenTelemetry's                                                                |
| `apiserver_request_duration_seconds`                                                 | API request time                                                                                    | As the API server's `/metrics`                                                 |
| `kubelet_pod_start_sli_duration_seconds`, `kubelet_pod_start_total_duration_seconds` | Pod start time                                                                                      | As the API server's `/metrics`                                                 |
| `kite_sandbox_start_duration_seconds`                                                | From a sandbox's create to the first report of it Running                                           | `placement`: `reserved` or `new_reservation`. `source`: `image` or `snapshot`. |
| `kite_sandbox_wake_duration_seconds`                                                 | From the request that woke a sleeping sandbox to the first report of it Running                     | `placement`: `reserved` or `new_reservation`                                   |

As upstream does, the pod start histograms leave out a pod that the scheduler
could not place at once, such as one that waited for a node pool to add a
machine. The sandbox histograms time sandboxes in a
[SandboxPool](/docs/sandbox-pools/). `placement` is `reserved` when the
pool placed the sandbox at once, and `new_reservation` when it waited for room.

:::note
Each point is a delta. It counts the requests, pod starts and sandbox starts
since the last post that the receiver accepted, so a post that fails loses
nothing. A restart of the control plane loses what it counted since its last
accepted post.
:::

The API server's own `/metrics` also serves what an operator acts on:

| Metric                                    | Measures                                                                                                                                                                                         |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `kite_nodes_agent_behind`                 | Nodes whose running agent or settings differ from the ones the cluster serves. `kite node update` brings them up to date.                                                                        |
| `kite_signing_key_active_age_seconds`     | Seconds since the active token signing key became active. `kite signing-key rotate` replaces it. A cluster that made its key before it recorded the time serves no line until the next rotation. |
| `kite_copy_lag_seconds`                   | Seconds since the copy of the store in its bucket last held every write. Zero while it is up to date. It grows while uploads fail. A cluster with no copy serves no line.                        |
| `kite_copy_last_upload_timestamp_seconds` | When an upload to the copy last succeeded, in seconds since the epoch.                                                                                                                           |

## Upgrade a cluster

Upgrade the control plane first, then the nodes.

1. Install the newer CLI. `kite deploy` deploys the same release as the CLI.

   ```bash
   curl -fsSL https://get.runkite.io | sh
   ```

2. Run `kite deploy --dry-run`, then `kite deploy`. The plan names the
   release that the cluster runs and the one that replaces it. If it warns
   that an old build still serves requests, run `kite deploy wait` before you
   update nodes.
3. Update each node as [Upgrade a node](/docs/manage-nodes/#upgrade-a-node) describes.
   After the deploy, `kite deploy` says how many nodes run an older agent.
   With automatic updates on, the cluster updates them. Otherwise it asks
   whether to start the update, one node at a time. With `--yes`, or with no
   terminal, it starts nothing and prints the command. A
   node pool does not replace its existing machines.

Check the result with `kubectl get nodes -o wide`. After a successful upgrade,
every node is `Ready`, and its `Agent` digest equals its `Desired` digest.

When the new release changes the node protocol, the plan says so, and
`kite deploy` asks you to type the cluster's name, unless you pass `--yes`.
After the deploy, every node shows `NotReady` and its agent logs
`rejected by control plane` until its agent is updated, and the cluster evicts
the node's pods. [Update each node from its host](/docs/manage-nodes/#update-a-node-from-the-host).
The plan cannot tell when the cluster runs a release from before releases
recorded their protocol, or, on your own servers, when another deploy.env
deployed it.

:::caution[You cannot downgrade a cluster]
A newer control plane can rewrite stored data so that older builds cannot read
it. `kite deploy` refuses a release with an older storage version.
:::

## Delete a cluster

1. Run `kite deploy destroy`, and type the Worker's name when it asks, not the
   value of `KITE_CLUSTER`. In a script, which has no terminal to ask on, pass
   `--yes` to skip the question.
2. `destroy` deletes the cluster's NodePools, and waits until the provider has
   deleted their machines.
3. Last, it removes the Worker and its Durable Objects.

| What                                                        | Kept or deleted                           | Flag                                                               |
| ----------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------ |
| NodePools and their machines                                | Deleted                                   | `--keep-machines` keeps the machines, and you delete them yourself |
| The Worker and its Durable Objects                          | Deleted                                   | None                                                               |
| The audit bucket                                            | Kept                                      | `--bucket` deletes it                                              |
| The tokens `kite-deploy-<worker>` and `kite-audit-<worker>` | Kept when `destroy` uses the deploy token | Set `CLOUDFLARE_API_TOKEN` to a token that can manage API tokens   |

:::danger
The Durable Objects contain the cluster: every object that a client wrote.
Cloudflare keeps no copy. Unless you keep a
[copy of the cluster](#keep-a-copy-of-the-cluster), the data is gone.
:::

Only the cluster can delete its machines. So `destroy` stops without removing
anything if it cannot list the NodePools, or if a pool still has machines
after 30 minutes. `kubectl describe nodepool <name>` shows why a pool still
exists. If the cluster's first deploy did not finish, the cluster has no
NodePools, so `destroy` deletes its Worker without waiting for machines.

The deploy token cannot manage API tokens, so `destroy` says when it leaves
the two tokens. Delete them in the dashboard, then remove
`CLOUDFLARE_API_TOKEN` from the settings file before you deploy again under the
same name.

## Recover from common failures

| What you see                                               | What to do                                                                           |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `kubectl` cannot authenticate                              | Check that the settings file contains `KITE_ADMIN_TOKEN`. Run `kite deploy secrets`. |
| `kite login` says `cannot sign in to this cluster`         | Set up OIDC or Cloudflare Access, deploy, and sign in again.                         |
| Access lets a person in but Kubernetes returns `Forbidden` | Bind a role to the user `kite whoami` reports.                                       |
| A browser app reports a network error with no API status   | Add its exact origin to `KITE_ALLOWED_ORIGINS` and deploy.                           |
| A node cannot join                                         | Check its API origin, outbound HTTPS, and bootstrap token.                           |

## Next

- [Manage nodes](/docs/manage-nodes/): add capacity and upgrade the node agent.
- [Sign in to a cluster](/docs/sign-in/): create kubeconfigs and RBAC
  bindings.
- [Move a cluster](/docs/move/): move a cluster to another Worker or to your own
  servers.
- [CLI reference](/docs/reference/cli/): every `kite` and `kite-agent` command.
