# Operating the AI Gateway

URL: https://www.elchi.io/docs/ai-gateway/operations

> How an AI gateway change reaches the edges and how to verify it: deploy jobs and their per-edge results, Sync, per-edge status and files, refused pushes and last-good, older edges, loopback endpoints, logs, restarts, upgrades and removal.

This page follows a change from the AI Gateway page to the edges, and shows how to check each step and what happens when one fails. The REST examples use the `ELCHI`, `PROJECT` and `H` (headers) variables from [Getting started](https://www.elchi.io/docs/ai-gateway/getting-started#rest-setup).

## How configuration reaches the edge

```mermaid
sequenceDiagram
  participant U as UI / REST
  participant C as Controller
  participant J as AI_GATEWAY_DEPLOY job
  participant A as elchi-client (each edge)
  participant G as elchi-ai-gateway
  U->>C: save (provider, gateway, consumer, key, MCP server, policy)
  C->>C: validate the whole set with the edge's rules
  C->>J: queue a deploy (deduplicated per project)
  J->>C: Envoy resources first when a gateway requires a key
  J->>A: the file set (00-providers.yaml, 00-consumers.yaml, gw-*.yaml)
  A->>A: stage *.tmp, run "elchi-ai-gateway validate"
  A->>G: rename into conf.d (pruning files not in the set)
  G->>G: merge, render, reload the engine, verify
  A->>G: read /configz until config_version = the pushed version
  A-->>J: applied version, reload ok, or the error
  J->>C: Envoy resources after the edges otherwise
```

### One configuration per project

The configuration belongs to the project, not to an edge. The control plane stores it in MongoDB (`ai_gateway_configs`): one providers document (providers with sealed credentials, global limits, prices, the request-log key, the sensitive-data policy, MCP servers), plus one document per gateway, consumer, AI listener and MCP server.

Every edge of the project that runs the AI gateway gets the same file set, written to `/etc/elchi/elchi-ai-gateway/conf.d/` with mode 0600:

| File | Contents |
|---|---|
| `00-providers.yaml` | Providers and their credentials, global limits, prices, the request-log recipient key, the sensitive-data policy, MCP servers. Always present. |
| `00-consumers.yaml` | Consumers with their key **hashes**, allowlists, quotas and MCP grants. Only when the project has consumers. |
| `gw-<name>.yaml` | One per gateway: hosts, models, limits, request-log policy, failover, MCP. |

The push is a full sync: a file in `conf.d` that is not in the set is removed. Only `conf.d` is ever touched; `config.yaml` is the operator's ([Installation](https://www.elchi.io/docs/ai-gateway/installation#configyaml)).

AI listeners are not part of this set. Their Envoy resources (listener, HTTP connection manager, route, TLS context) are generated by the control plane and reach Envoy over xDS; a change to a deployed listener reaches its clients live, without a restart. See [Listeners](https://www.elchi.io/docs/ai-gateway/listeners).

### Every save deploys

Each save on the AI Gateway page (and each write through `/api/v3/ai-gateway`) is validated against the whole project configuration with the same rules the edge uses, stored, and followed by an `AI_GATEWAY_DEPLOY` job:

- A change the edge would refuse is refused here with `400` naming every problem.
- Two people editing at once: a write made on a stale version gets `409` "ai gateway configuration changed since it was loaded; reload it". In the UI the form offers **Load the stored version**. Through the API, send the `version` you read as `expected_version` (0 skips the check), or `create: true` to refuse a name that already exists (`409` "the name is already used…").
- The answer carries `deploy`: `{"enqueued": true, "deploy_job": "<id>"}`. When a deploy of the project is already queued, `{"enqueued": true, "deduped": true}`: the queued job reads the stored configuration when it runs, so it carries this change too.

The job's order matters for security and for availability:

- **A gateway requires a key, or the configuration was removed:** Envoy's resources are updated first, then the edges. A gateway turning keyed is enforced by Envoy before the edges know it as keyed.
- **Otherwise:** the edges first, then Envoy. A model an edge knows before Envoy routes it answers; the other order would `404` the new model meanwhile.
- The edges get the set even when the Envoy resources fail: a key revocation never waits for an unrelated Envoy error. The job then fails and says so.

### Which edges get it

Only clients that **report the AI gateway installed** get the set (it carries provider credentials). The agent reports the gateway's version (`ai_gateway_version`) when it registers. A project deploy targets every **connected** such client of the project.

- An offline edge gets the current set when it connects again: each (re)connect queues a deploy for that one client (reason `client_connect`). If the configuration changed while that push ran, it pushes again.
- A project with no client running the AI gateway: the job completes with the note "no connected client of the project runs the AI gateway".
- A gateway installed after the agent registered is unknown to the control plane until the agent registers again (restart `elchi-client`).

### On the edge: the agent's two-phase write

The agent (`elchi-client`) writes the set in two phases:

1. **Stage.** Each file is written as `<name>.tmp`. The gateway's loader and watcher ignore that extension, so staging never triggers a reload.
2. **Validate.** The agent runs `elchi-ai-gateway validate` on the staged set together with the live files it does not replace. Exit code 0 is valid (or empty), 1 invalid, 2 a usage error.
3. **Commit.** On success the files are renamed into place and files not in the set are removed. On failure nothing changes: `conf.d` and the running configuration stay as they were, no staged file is left, and the agent answers "ai gateway rejected the config: …" with the gateway's own verdict.
4. **Confirm.** The agent reads `http://127.0.0.1:9002/configz` until `config_version` equals the version the control plane computed for this set. A growing `reload.failures` with the version unchanged means the engine refused it.

The gateway reacts to `conf.d` changes after 300 ms of quiet, and re-scans the directory every 5 minutes regardless. It merges every file into one configuration; any error rejects the whole set.

### The deploy job and its per-edge result

**UI.** After a save a notification follows the job:

| Notification | Meaning |
|---|---|
| "AI gateway configuration saved and applied" — "applied on N/N edge(s), version …" | Every targeted edge confirmed the exact version. |
| "AI gateway configuration saved, but the edges did NOT apply it" | The job failed. The description names the first edge error and says the previous configuration stays active. It stays until you close it and links the job. |
| "AI gateway configuration saved, but its deploy failed" | The job failed before any edge answered (for example the Envoy resources). |
| "AI gateway deploy … is still running" | Check its per-client results when it finishes (the job link). |
| "AI gateway deploy … was cancelled" | The edges keep their previous configuration. Use **Sync**. |
| "AI gateway configuration saved, but the deploy could not be queued" | Check the controller logs; use **Sync** to retry. |

**REST.**

```bash
curl -s "$ELCHI/api/v3/jobs/<deploy_job>?project=$PROJECT" "${H[@]}" \
  | jq '.data | {status, error, result: .execution_details.ai_gateway_result}'
```

```json
{
  "status": "FAILED",
  "error": "ai gateway deploy: 1 of 2 targeted client(s) failed: 3f9c… (applied version 4b1e0a7c9d21, pushed 75e51a5b8234)",
  "result": {
    "version": "75e51a5b8234",
    "total": 2, "succeeded": 1, "failed": 1,
    "clients": [
      {"client_id": "a71d…", "ok": true, "reload_ok": true, "applied_version": "75e51a5b8234"},
      {"client_id": "3f9c…", "ok": false, "reload_ok": true, "applied_version": "4b1e0a7c9d21",
       "error": "applied version 4b1e0a7c9d21, pushed 75e51a5b8234"}
    ]
  }
}
```

- `status`: `ANALYZING`, `PENDING`, `CLAIMED` or `RUNNING` while it is open; then `COMPLETED`, `NO_WORK_NEEDED`, `FAILED` or `CANCELLED`.
- An edge counts as `ok` only when the command was delivered, the gateway accepted the set, the reload was confirmed, **and** it reports exactly the pushed version. "no response from client" means it did not answer.
- **Any failed edge fails the job.** The edges that applied the set keep it; the failed ones keep their previous set (with a revoked key or a removed gateway still served there), so the failure is surfaced for you to fix and retry. The per-client rows are kept on the failed job.
- `note` explains a job that pushed nothing (no configuration, no edge running the gateway).

### Sync

**Sync** (top right of the AI Gateway page, Owners and Admins, shown once a configuration exists) sends the stored configuration to every connected edge again. Use it after fixing an edge, after a failed or cancelled deploy, or when an edge shows **behind**. The notification reads "AI gateway configuration sync requested" and then follows the job like a save.

```bash
curl -s -X POST "$ELCHI/api/v3/ai-gateway/sync" "${H[@]}" -d '{"project": "'"$PROJECT"'"}'
# {"data": {"enqueued": true, "deploy_job": "..."}}
```

Re-pushing an unchanged set is harmless: rendering is deterministic, so the edge's reload is a no-op.

## Per-edge Status and Files

**UI:** **Administration → Clients**, open the client, tab **AI Gateway** (Owners and Admins; it sends a command to the client).

- **AI gateway service**: the systemd state, `cfg <version>` (the `config_version` the gateway reports applied), `behind: <version>` when the project's configuration for this edge is another version ("this edge missed a deploy. Sync on the AI Gateway page pushes it again."), `extproc <version>`, and **Recent logs** with chips for `component`, `version`, `config_version`, `error` and `reason`.
- **Live config files**: **Path**, **SHA-256** and **Mode** of every file in this edge's `conf.d`.
- "The client returned no AI gateway status (is elchi-ai-gateway installed on this edge?)": the gateway is not installed or the agent cannot reach it.

**REST:**

```bash
curl -s "$ELCHI/api/v3/ai-gateway/status?project=$PROJECT&client_id=<client id>" "${H[@]}"
curl -s "$ELCHI/api/v3/ai-gateway/files?project=$PROJECT&client_id=<client id>" "${H[@]}"
```

`data[0].ai_gateway` holds `service_status`, `applied_version`, `reload_ok`, `extproc_version`, `logs[]` (`timestamp`, `level`, `component`, `message`) and, for `/files`, `current_files[]` (`path`, `sha256`, `mode`). `/status` also returns `desired_version`: the version this edge should run (its own set: an edge older than MCP has a different one). The client must be connected and belong to the project; otherwise `404` "client not found in this project (or not connected)".

## When a push is refused: last-good

The gateway never serves half a configuration. What it does when something fails:

| Situation | What happens | Where you see it |
|---|---|---|
| The set does not validate | The agent refuses it before it lands; nothing changes on the edge. | Job: "ai gateway rejected the config: …". |
| It validates but cannot be rendered | "config render failed; keeping last-good". The applied configuration keeps serving. | `/configz` `render.failures` and `render.last_error`. |
| The engine refuses it on reload | "config reload failed; last-good keeps serving". The bundle on disk is reverted to the applied configuration, so a restart never starts from a refused one. | `/configz` `reload.failures` grows (also when the same set is pushed again); `config_version` stays. The job fails for that edge. |
| `conf.d` emptied while running | The rendered configuration keeps serving. | Log "config directory empty; keeping last-good rendered config". |
| `conf.d` unusable at start | The last accepted configuration is restored from `/var/lib/elchi/ai-gateway/last-good.json`. | `/configz` `restored_last_good: true`, `render.last_error` says why; log "serving the persisted last-good". |
| The engine refuses the `conf.d` configuration at start twice | The gateway falls back to the last-good configuration and counts a reload failure. | Same as above. |
| No configuration and no last-good | Nothing to run: state `degraded`, `/readyz` 503. | Elchi OS `show health`: information while nothing was pushed; critical when a pushed one was refused and none could be restored. |

Fix the cause (the job's error, the gateway's log), then save again or **Sync**.

## Edges with an older gateway

MCP needs AI gateway **v0.4.0** or later on the edge. An older gateway decodes its set strictly and would refuse every MCP field, and with them its LLM gateways. So:

- An edge reporting a version older than v0.4.0 gets the **set without MCP**: no MCP servers, no gateway serving MCP, no MCP grants, no MCP call quotas, no MCP directions in the sensitive-data policy. Its LLM gateways keep working. Its `desired_version` is that set's version, so it does not show as behind.
- The AI listeners' MCP egress (`127.0.0.1:10088`) is added only when **no client of the project**, connected or not, reports a version older than v0.4.0. Older gateways have no firewall on that port. Until then, MCP is not served on any AI listener of the project.
- The **MCP servers** tab says "MCP is not served yet: an edge runs an AI gateway older than v0.4.0" and names the edges. `GET /api/v3/ai-gateway/mcp-readiness?project=…` answers `{"ready": false, "holding": ["<client id>", …], "min_version": "v0.4.0"}`.
- A development build (`dev`, `dev-…`) counts as current; a client with no reported version counts as not running the gateway.

Upgrade the gateway on the named edges ([Installation](https://www.elchi.io/docs/ai-gateway/installation#re-runs-and-upgrades)); the agent must register again to report the new version.

## A client moved to another project

When an edge's agent registers with a token of another project, the agent drops the previous project's WAF and AI gateway configuration after the new registration is accepted, points the gateway's `config.yaml` `project:` at the new project and restarts the gateway, so usage, request and decision rows are recorded under the new project. The new project's configuration (if any) then arrives with the connect deploy.

## Loopback endpoints

The supervisor serves HTTP on `127.0.0.1:9002` only (it refuses a non-loopback `--http-addr` unless `--allow-non-loopback` is given):

| Endpoint | Answer |
|---|---|
| `/healthz` | `200 ok` while the process runs. |
| `/readyz` | `200 ready` when the state is `ready` and the engine is ready; else `503 not ready`. |
| `/configz` | The applied configuration as JSON, credentials always redacted. |
| `/metrics` | Prometheus metrics of the supervisor (`elchi_ai_gateway_*`). |

States: `init`, `ensuring-binary` (waiting for the engine), `rendering`, `starting`, `ready`, `degraded` (no valid configuration; engine not running), `crash-loop` (the engine keeps exiting; restarts back off from 1 s, doubling, up to 30 s), `stopping`.

```bash
curl -s http://127.0.0.1:9002/configz
```

```json
{
  "instance": "edge-01",
  "state": "ready",
  "config_version": "75e51a5b8234",
  "gateways": [
    {"name": "team-a", "hosts": ["llm.example.com"], "models": ["gpt-4o-mini"], "capture": "metadata"}
  ],
  "providers": [{"name": "openai", "type": "openai", "credentials": "[REDACTED]"}],
  "extproc": {"binary_version": "v1.3.0", "version_string": "v1.3.0", "binary_path": "/var/lib/elchi/ai-gateway/v1.3.0/extproc",
              "pid": 4242, "ready": true, "restarts": 0, "started_at": "2026-12-05T09:12:03Z"},
  "render": {"failures": 0},
  "reload": {"last_at": "2026-12-05T09:40:11Z", "failures": 0},
  "authz": {"quota_totals": "shared"},
  "build": {"version": "v0.4.3", "upstream_pin": "v1.3.0", "go_version": "go1.27.4"}
}
```

- `config_version`: 12-hex hash of the applied configuration (`empty` before the first). It is what the deploy job compares.
- `render` / `reload`: `failures` are cumulative since the process started, never reset; `last_error` and `last_at` describe the last one.
- `restored_last_good`: present and `true` while the applied configuration is the persisted last-good.
- `authz.quota_totals`: `shared` (quotas summed from every edge's usage in ClickHouse; `last_refresh`, `last_refresh_error`) or `edge-local` (no ClickHouse: each edge counts only what it saw since it started, so N edges allow N times a quota and a restart resets it).
- `mcp_servers[]`: `{name, personal_token}`; `credentials[]`: the state of Azure Entra ID identities, never a token. `sources` lists the files the configuration came from.

Useful metrics: `elchi_ai_gateway_up`, `elchi_ai_gateway_state{state}`, `elchi_ai_gateway_build_info`, `elchi_ai_gateway_extproc_restarts_total`, `elchi_ai_gateway_render_failures_total`, `elchi_ai_gateway_reload_failures_total`, `elchi_ai_gateway_authz_decisions_total`, `elchi_ai_gateway_upstream_responses_total`, and the `*_rows_written_total` / `*_rows_dropped_total` pairs for usage, request log, decisions, provider answers and MCP calls (a growing dropped counter means ClickHouse is not taking rows).

## Logs

The gateway logs JSON to the journal (`SyslogIdentifier=elchi-ai-gateway`):

```bash
journalctl -u elchi-ai-gateway -f -o cat | jq -c '{time, level, msg, config_version, error, reason}'
```

On Elchi OS: `logs ai-gateway [n] [follow] [grep <pattern>]`, and `show ai-gateway` lists the recent configuration events.

| Line | Meaning |
|---|---|
| `extproc reloaded config` (with `config_version`) | A configuration was applied. |
| `config render failed; keeping last-good` | The set could not be rendered. |
| `config reload failed; last-good keeps serving` (`reason`) | The engine refused the set. |
| `serving the persisted last-good config` | Started on `last-good.json`. |
| `adopting extproc's version string from mismatch report` | The version gate self-heal (see [Installation](https://www.elchi.io/docs/ai-gateway/installation#the-version-gate)). |
| `extproc ready`, `extproc started`, `extproc stopped` | The engine's lifecycle. |
| `consumer quotas are edge-local: …` | No ClickHouse DSN; quotas are per edge. |

## Restarts

```bash
sudo systemctl restart elchi-ai-gateway
```

On Elchi OS: `restart ai-gateway` (it asks first). The supervisor gets SIGTERM, stops the engine (the engine drains for up to 15 s; the supervisor kills it after 20 s; systemd after 60 s) and comes back with `conf.d` or the last-good configuration. Requests in flight finish first; during the restart the AI listeners of that edge cannot serve LLM requests, for a few seconds. `config.yaml` changes need a restart; `conf.d` changes never do.

## Upgrades of the gateway and the engine

- **Gateway:** re-run the installer with `--version=` (plain Linux) or `system component update elchi-ai-gateway` (Elchi OS). The engine pin follows the gateway release. See [Installation](https://www.elchi.io/docs/ai-gateway/installation#re-runs-and-upgrades).
- **Engine:** the gateway downloads the pinned engine at start and keeps the previous one in the store. A gateway renders for one engine release: change the engine only by installing the gateway release built for it.
- **After either:** the agent must register again to report the new gateway version (Elchi OS does this itself). Then check the client's **AI Gateway** tab: `cfg` equals the project's version, `extproc` shows the new engine.

## Removing the whole configuration

**UI:** **Remove** (top right of the AI Gateway page). The dialog "Remove the AI gateway from this project?" says what happens: providers, gateways, consumers and every consumer key are deleted (applications using those keys get `401`), every edge gets an empty configuration (the provider credentials leave the edges) and the generated Envoy resources are removed. Usage history stays. The checkbox **Also destroy the request-log key** makes captured request content unreadable forever (crypto-shredding).

**REST:**

```bash
curl -s -X DELETE "$ELCHI/api/v3/ai-gateway?project=$PROJECT&shred=true" "${H[@]}"
# {"message": "removed", "shredded": true, "deploy": {"enqueued": true, "deploy_job": "..."}}
```

- **`409` while used.** "the AI gateway is in use: remove its listeners (Listeners tab) and stop these resources from using what it generates first", with `dependents` naming them. The UI shows "The AI gateway is in use" with the list. Undeploy and remove the AI listeners first.
- **`409` while a deploy or listener change runs.** The removal waits up to 2 minutes for the project's deploy lease, then answers "an AI gateway deploy or listener change of the project is running; try again in a moment". Nothing is removed.
- **Without `shred`** the request-log key is kept, so content captured before stays readable on the Request log.
- **Leftovers.** The generated resources go with the removal's deploy. If that deploy does not finish, the page shows "N resources generated by the removed configuration are still here" with **Remove them**, which runs the deploy again (the edges get the empty configuration once more).
- The edges receive `00-providers.yaml` with an empty spec; the full sync removes the other files.

Removing a single gateway, consumer or provider is a normal save: a gateway a listener serves cannot be deleted (`409` naming the listener), and a provider a gateway or consumer uses cannot be deleted until they stop using it.

## Related

- [Installation](https://www.elchi.io/docs/ai-gateway/installation) — the sidecar, `config.yaml`, upgrades.
- [Troubleshooting](https://www.elchi.io/docs/ai-gateway/troubleshooting) — symptoms and fixes.
- [Ports, files and tables](https://www.elchi.io/docs/ai-gateway/reference/ports-files-and-tables) and [REST API](https://www.elchi.io/docs/ai-gateway/reference/rest-api).
