# AI Gateway Usage, Costs and Provider Health

URL: https://www.elchi.io/docs/ai-gateway/usage-and-costs

> Where the AI gateway's usage, cost, error rate, latency, refusals and provider status come from, how to read them in the UI and the API, and what each ClickHouse table keeps and for how long.

Every edge writes what its AI gateway saw to the project's ClickHouse. The control plane reads it back for the **Usage** tab, the consumers' quota bars, the providers' **Status**, and the API. This page explains each figure: where it comes from, how fresh it is, how long it is kept, and what happens when ClickHouse is unavailable.

![Usage tab](https://www.elchi.io/docs/img/docs/aigw-usage-light.webp)

## Where the figures come from

| Source (ClickHouse table) | Written by the edge from | Feeds | Kept |
|---|---|---|---|
| **Usage** `elchi_ai_gateway_usage` | The extproc's GenAI metrics, scraped every **30 s** as deltas per gateway, provider, model, consumer and token type | Requests, tokens, cost, average duration, time to first token; consumer quotas | **90 days** by default (`usage.clickhouse_ttl_days`, never below 32) |
| **Request log** `elchi_ai_gateway_requests` | One span per request ([Request log](https://www.elchi.io/docs/ai-gateway/request-log)) | Error rate, latency percentiles, error types, finish reasons | Each row's gateway retention (7 days by default) |
| **Decision log** `elchi_ai_gateway_decisions` | The consumer authorization's refusals and sensitive-data flags | Refused, blocked, flagged; refusals by reason; sensitive data by type | 90 days |
| **Provider answers** `elchi_ai_gateway_upstream` | Envoy's access log: what each provider answered, per minute | Provider **Status** | 30 days |
| **MCP call log** `elchi_ai_gateway_mcp_calls` | Envoy's MCP egress access log | [MCP call log](https://www.elchi.io/docs/ai-gateway/mcp/call-log) | As usage (90 days by default) |

Each table is created by the edge on its first write. Until then, the control plane reads it as "nothing yet".

A consequence: **Requests** and **Tokens** (from usage) cover every gateway. **Error rate** and **Latency p95** (from the request log) cover only gateways whose request log is on (level Metadata or Full) and only for their retention. The Usage tab says this under its figures.

## The Usage tab

**AI Gateway → Usage**. Every project member can read it.

### Period and filters

- **Period**: **Today**, **This week** (from Monday) or **This month**, cut in **UTC**, the same days and months the consumer quotas use. Today is drawn in hourly buckets, a week or a month in daily ones.
- Every figure is compared with **the period before, up to the same time**. Today until 14:10 is compared with yesterday until 14:10. If the month before is shorter than the time elapsed, it is compared whole.
- Filters: **Every gateway**, **Every model** (the models the chosen gateway serves), **Every consumer** (when the project has consumers). **Refresh** asks again. The previous answer stays on screen, dimmed, with "Updating…", until the new one arrives.

### Summary figures

| Figure | What it shows | Source |
|---|---|---|
| **Requests** | Requests, with the average duration and the average time to first token. | Usage |
| **Tokens** | Input + output tokens: "N in · N out", and the share of input the provider served from its cache ("N% cached"). | Usage |
| **Cost** (only when the project has [prices](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs)) | Priced tokens' cost. A "≥" prefix and "N tokens have no price" when some model in the window has no price; "every token priced" otherwise. | Usage + price table |
| **Error rate** | Errors among the logged requests ("N of M logged"), with "was N%" for the period before. Shown in alarm colour above 5%. "no request log in this window" when no gateway logs. | Request log |
| **Latency p95** | The 95th percentile, with p50 and p99. | Request log |
| **Sensitive data** | "N blocked" (refused with `sensitive_data`), then "N flagged · N refused otherwise" (other refusals: keys, quotas, scan limits). | Decision log |

### Charts and breakdowns

- **Traffic**: requests per bucket, plus **Errors** when there are any.
- **Tokens**: **Input**, **Cached input**, **Output**, stacked.
- **Latency**: **p95** (request log) and **Average** (usage).
- **Refused and flagged**: refusals and flags per bucket.
- **Models**, **Providers**, **Consumers**, **Gateways**: the top 10 of each by requests. Each line shows tokens, the average duration and, when priced, cost. Where the request log and decision log have data for the group, it also shows its error share, p95, and blocked / flagged / refused counts. A consumer group with an empty name is shown as "no key", meaning requests on gateways without keys.
- **Sensitive data found**: blocked and flagged requests per type.
- **Refusals by reason**: refusals per code (`invalid_api_key`, `quota_exceeded`, `sensitive_data`, …). See [Error codes](https://www.elchi.io/docs/ai-gateway/reference/error-codes).
- **Errors and finish reasons**: the request log's error types and finish reasons.

A consumer's own usage and quota bars are on its page. See [Consumers and keys](https://www.elchi.io/docs/ai-gateway/consumers-and-keys).

## Cost and unpriced tokens

Cost is computed **when you read it**, from the project's current price table. It is not stored. Each part of usage (one provider and model) is priced on its own:

- Input tokens at `inputPerMTok`, output tokens at `outputPerMTok`, per million tokens.
- Cached input tokens are part of the input count and cost `cachedInputPerMTok` instead, or the input rate when no cached rate is set.
- A price that names the provider wins over the model's price without a provider.
- **Unpriced tokens:** the input + output tokens of a provider and model with no price. They add nothing to cost and are counted in `unpriced_tokens`. Any unpriced token makes the shown cost a **lower bound** (the "≥").
- **A price change reprices the past.** Reading last month after a price change shows last month at the new price.

The UI shows cost with a `$` sign. The figures are in whatever currency your price table uses. Setting prices: [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).

## Provider status

How each provider is doing, from what it **actually answered the edges** in the last **15 minutes**:

- **Providers** list → **Status** column (hover for the details).
- A provider's page → **Status** card: "From what this provider answered the edges in the last 15 minutes; a client's malformed request does not count against it."

| Status | When |
|---|---|
| **Idle** | No answers in the window: no traffic, which does not mean the provider is down. |
| **OK** | Answers and no failures, or failures under 5%. |
| **Degraded** | Failures are 5% or more of the judged answers, or the provider rate-limited at least once. |
| **Failing** | Only failures, or at least 3 failures making 50% or more. |

Each answer gets a class. The edge counts it from Envoy's access log:

| Class | UI words | When |
|---|---|---|
| `ok` | answered | The provider answered below 400 (`RESPONSE_CODE_DETAILS = via_upstream`). |
| `auth_error` | refused the key | It answered 401 or 403. |
| `rate_limited` | rate limited | 429. |
| `client_error` | refused the request | Another 4xx. Not a failure of the provider. |
| `server_error` | server error | 5xx. |
| `unreachable` | unreachable | No connection: refused, DNS, TLS (Envoy flags UF, DF). |
| `timeout` | timed out | No answer in time (UT, duration or idle timeout). |
| `reset` | connection reset | The connection broke mid-answer (UR, UC, protocol error). |

Failures are `server_error`, `unreachable`, `timeout`, `reset`, `auth_error` and `rate_limited`. Some answers are never counted: those the extproc or the authorization made itself (a malformed body, an unsupported schema, a refused consumer key, a sensitive-data block). No provider was involved in them. A failed attempt that Envoy then retried successfully on another provider is not in the access log either. A pool member's trouble shows in Envoy's outlier ejection instead.

On a provider's page, Owners and Admins also have:

- **Check now**: asks the provider's model list with the stored key. No tokens are spent. The result is "Answered in N ms · N models", "Answered `<status>`: `<message>`" or "Not reached: …". Available for OpenAI-compatible and Anthropic providers. A provider on the edge itself (loopback) is reachable only from the edges, so its status comes from their traffic.
- **Ask the edges**: reads each edge Envoy's `/clusters` for this provider's hosts and shows each host as **healthy**, **ejected** (outlier detection: a pool member that kept failing), **unhealthy** or **unreachable**.

The per-minute rows also keep the HTTP `code` and `retried` (1 when Envoy made more than one attempt for the request), for your own queries:

```sql
SELECT provider, class, code, sum(count) AS answers, sumIf(count, retried = 1) AS after_retry
FROM elchi_ai_gateway_upstream
WHERE project = '<project-id>' AND ts >= now() - INTERVAL 1 DAY
GROUP BY provider, class, code ORDER BY answers DESC
```

## The decision list

Refusals and sensitive-data flags are listed, without any values:

- **Sensitive data → Recent decisions** shows the sensitive-data decisions. See [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data#where-decisions-are-recorded).
- `GET /api/v3/ai-gateway/decisions` (Owner/Admin) lists every refusal. A key, model, quota or sensitive-data decision is one row with `gateway`, `consumer`, `phase`, `result` (`denied` | `flagged`), `status`, `code`, `findings`, `finding_counts`, `request_id`.

## API

All under `/api/v3/ai-gateway`, with `project` as a query parameter. `from` / `to` are RFC 3339. Without them the window is the last 24 h. The longest window is **90 days**. See the [REST API reference](https://www.elchi.io/docs/ai-gateway/reference/rest-api).

| Call | Who | Returns |
|---|---|---|
| `GET /usage?group_by=…&bucket_seconds=…` | Members | Requests, tokens, cost per group, or a time series |
| `GET /usage/summary?period=today\|week\|month` (or `from`/`to`, `bucket_seconds`) | Members | What the Usage tab shows: current and previous period, series, breakdowns |
| `GET /provider-health` | Members | Each provider's status over the last 15 minutes |
| `POST /providers/{name}/check` | Owner/Admin | **Check now** |
| `GET /decisions` | Owner/Admin | The decision log |
| `GET /requests` | Owner/Admin | The request log |

`GET /usage` parameters:

- `group_by`: `gateway`, `provider`, `model`, `consumer`, `instance` (the edge), or empty for one total.
- Filters: `gateway`, `provider`, `model`, `consumer`.
- `bucket_seconds`: at least 60. It is widened so a window has at most 2000 buckets.

A totals answer lists at most 1000 groups, most requests first. A window with too many provider × model parts at the chosen bucket answers `400`: "use a larger bucket, a narrower window or a filter".

```bash
# this month, per consumer
curl -s "$ELCHI/api/v3/ai-gateway/usage?project=$PROJECT&group_by=consumer&from=2026-12-01T00:00:00Z" \
  -H "Authorization: Bearer $TOKEN"
# {"data":[{"key":"team-a","requests":1520,"input_tokens":2.1e6,"output_tokens":4.0e5,"cached_tokens":3.0e5,
#           "other_tokens":0,"avg_duration_ms":812.4,"avg_ttft_ms":0,"cost":11.27,"unpriced_tokens":0}, ...],
#  "from":"...","to":"..."}

# per edge, hourly, one gateway
curl -s "$ELCHI/api/v3/ai-gateway/usage?project=$PROJECT&group_by=instance&gateway=support&bucket_seconds=3600" \
  -H "Authorization: Bearer $TOKEN"
```

Without ClickHouse on the control plane, these calls answer `503` "clickhouse not configured; … unavailable".

## Hourly rollups

Reading a month of raw rows is slow. Each edge therefore keeps two hourly rollups next to the raw tables:

| Rollup | Holds | Kept |
|---|---|---|
| `elchi_ai_gateway_usage_1h` | Usage per UTC hour, project, gateway, provider, model, consumer and token type | As the usage table |
| `elchi_ai_gateway_requests_1h` | Requests per UTC hour, project, gateway, provider, model, consumer, status and latency bucket `floor(log_1.15(duration_ms))` | 90 days |

Each rollup is a `SummingMergeTree` that a materialized view fills on every insert. Measured on 30 days at 1M requests a day, a month's usage breakdown took 0.5–0.8 s from the raw table and about 10 ms from the rollup.

**What "never backfilled" means for you.** A rollup counts only rows inserted after its view was created. It is not filled with older rows: every edge runs the same setup, so a backfill per edge would count the past once per edge. Each edge notes in `elchi_ai_gateway_rollups (rollup, since)` when the view existed. The control plane reads whole UTC hours after the earliest note from the rollup, and the rest of the window (older hours, a partial first or last hour) from the raw table. So:

- **Figures are exact either way.** The rollup only makes them faster. Nothing needs to be rebuilt after an upgrade.
- **Instance breakdowns** (`group_by=instance`) and buckets that are not whole hours always come from the raw table.
- **Latency percentiles** from the rollup are within ±7.5% (half a latency bucket).
- **The request rollup holds counts only** (no ids, no content) and keeps them 90 days. Erasing request-log rows, or their shorter retention, does not remove these counts.

## ClickHouse tables at a glance

| Table | TTL | Change it with |
|---|---|---|
| `elchi_ai_gateway_usage` (+ `_1h`) | 90 days | `usage.clickhouse_ttl_days` in the edge's `config.yaml`. Raised to **32** if set lower, because monthly quotas and the month's usage are summed from it. Applied to the table at the next start. |
| `elchi_ai_gateway_requests` | Per row: the gateway's **Retention (days)** (default 7, 1–365) | The gateway page |
| `elchi_ai_gateway_requests_1h` | 90 days | Fixed |
| `elchi_ai_gateway_decisions` | 90 days | Fixed |
| `elchi_ai_gateway_upstream` | 30 days | Fixed |
| `elchi_ai_gateway_mcp_calls` (+ `_1h`) | As usage (raw); 90 days (rollup) | `usage.clickhouse_ttl_days` |

Table names can be changed on the edge (`--usage-clickhouse-table`, `--requests-table`, `--decisions-table`, `--upstream-table`, `--mcp-calls-table`), but the control plane reads the default names. See [Ports, files and tables](https://www.elchi.io/docs/ai-gateway/reference/ports-files-and-tables).

## When ClickHouse is down

Observability is best effort. **A ClickHouse outage never blocks a request.** What happens to the data:

- Each table has an in-memory queue on the edge. Usage, decisions and provider answers hold 4096 rows; the request log 8192; MCP calls 8192. Rows are written in batches.
- **ClickHouse unreachable** (connection refused, reset, timed out): the batch waits and is retried for as long as the outage lasts, with backoff up to 30 s. New rows queue behind it. When the queue is full, new rows are **dropped and counted**.
- **ClickHouse reachable but refusing a batch**: the batch is retried, then dropped after 6 attempts, so one bad batch never blocks the queue.
- **Service stop:** the edge takes one last usage scrape, then tries to write what is queued for up to 10 s. Rows still unwritten after that are lost.
- **Consumer quotas** keep the last totals they read. Failed reads are counted in `elchi_ai_gateway_authz_quota_refresh_failures_total`. An edge **without** a ClickHouse DSN counts quotas only from its own traffic since it started. See [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).

Losses are visible on the edge's loopback metrics:

```bash
curl -s 127.0.0.1:9002/metrics | grep -E 'elchi_ai_gateway_(usage|requestlog|decision|upstream|mcp_call)_rows_(written|dropped)_total|usage_scrape_failures_total'
```

| Metric | Meaning |
|---|---|
| `elchi_ai_gateway_usage_rows_written_total` / `_dropped_total` | Usage rows written / lost |
| `elchi_ai_gateway_usage_scrape_failures_total` | Failed scrapes of the extproc's metrics (expected briefly while it restarts) |
| `elchi_ai_gateway_requestlog_rows_*`, `elchi_ai_gateway_decision_rows_*`, `elchi_ai_gateway_upstream_rows_*`, `elchi_ai_gateway_mcp_call_rows_*` | The same for the other tables |

## Metrics endpoints and the GenAI metrics push

| Endpoint | Binds | What |
|---|---|---|
| `http://127.0.0.1:9002/metrics` | Loopback only (unless `--allow-non-loopback`) | The supervisor's own Prometheus metrics, all prefixed `elchi_ai_gateway_`: restarts, reloads, export health, authorization decisions, sensitive findings and scans, provider answers (`upstream_responses_total{provider,class}`), MCP calls |
| `http://<edge>:9064/metrics` | **All interfaces** (the upstream offers no option); the installer firewalls it | The extproc's own metrics, including the GenAI metrics the usage scraper reads: `gen_ai_client_token_usage`, `gen_ai_server_request_duration_seconds`, `gen_ai_server_time_to_first_token_seconds`. The port is set with `extproc.admin_port`. |

To send the GenAI metrics to a time-series system (for example the Elchi stack's OpenTelemetry collector and VictoriaMetrics), set this in the edge's `config.yaml`:

```yaml
telemetry:
  metrics_otlp_endpoint: https://elchi.example.com:443   # OTLP/gRPC
  # metrics_otlp_insecure: false
  # metrics_otlp_ca_cert: /etc/elchi/ca.crt
  # metrics_otlp_headers: {x-token: "..."}
```

- The extproc then **also** pushes its GenAI metrics every 30 s over OTLP/gRPC. Its Prometheus endpoint keeps working, so usage export is unaffected.
- The resource attributes `elchi.instance` and `elchi.project` identify the edge. The service name is `elchi-ai-gateway`.
- Leave the endpoint empty to keep the metrics on the admin port only.

Flags and environment variables: `--metrics-otlp-endpoint` / `ELCHI_AI_GATEWAY_METRICS_OTLP_ENDPOINT`, and the `-insecure`, `-ca-cert`, `-headers` variants. See [Installation](https://www.elchi.io/docs/ai-gateway/installation) for where `config.yaml` lives.

The usage scrape interval is `usage.scrape_interval` (default `30s`). Token and cost quotas lag by up to one scrape. Consumer labels on the extproc's metrics are not capped: the supervisor sets `OTEL_GO_X_CARDINALITY_LIMIT=0`, so usage keeps its consumer at any number of consumer × model pairs.

## Verify it

1. Send a few requests through a gateway.
2. Within about a minute (one 30 s scrape plus the batch interval), **Usage → Today** shows them.
3. If it does not, check on the edge:
   - `curl -s 127.0.0.1:9002/metrics | grep usage_rows` shows `written` growing and `dropped` at 0.
   - `curl -s 127.0.0.1:9002/configz` shows the applied configuration.
   - In ClickHouse: `SELECT gateway, sum(requests) FROM elchi_ai_gateway_usage WHERE ts > now() - INTERVAL 10 MINUTE GROUP BY gateway`.
4. Error rate and latency stay "—" until a gateway's request log is on.

Related: [Request log](https://www.elchi.io/docs/ai-gateway/request-log) · [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data) · [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs) · [Operations](https://www.elchi.io/docs/ai-gateway/operations) · [Troubleshooting](https://www.elchi.io/docs/ai-gateway/troubleshooting)
