Skip to main content

AI Gateway Usage, Costs and Provider Health

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 Usage tab

Where the figures come from​

Source (ClickHouse table)Written by the edge fromFeedsKept
Usage elchi_ai_gateway_usageThe extproc's GenAI metrics, scraped every 30 s as deltas per gateway, provider, model, consumer and token typeRequests, tokens, cost, average duration, time to first token; consumer quotas90 days by default (usage.clickhouse_ttl_days, never below 32)
Request log elchi_ai_gateway_requestsOne span per request (Request log)Error rate, latency percentiles, error types, finish reasonsEach row's gateway retention (7 days by default)
Decision log elchi_ai_gateway_decisionsThe consumer authorization's refusals and sensitive-data flagsRefused, blocked, flagged; refusals by reason; sensitive data by type90 days
Provider answers elchi_ai_gateway_upstreamEnvoy's access log: what each provider answered, per minuteProvider Status30 days
MCP call log elchi_ai_gateway_mcp_callsEnvoy's MCP egress access logMCP call logAs 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​

FigureWhat it showsSource
RequestsRequests, with the average duration and the average time to first token.Usage
TokensInput + 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)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 rateErrors 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 p95The 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.
  • 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.

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.

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."
StatusWhen
IdleNo answers in the window: no traffic, which does not mean the provider is down.
OKAnswers and no failures, or failures under 5%.
DegradedFailures are 5% or more of the judged answers, or the provider rate-limited at least once.
FailingOnly failures, or at least 3 failures making 50% or more.

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

ClassUI wordsWhen
okansweredThe provider answered below 400 (RESPONSE_CODE_DETAILS = via_upstream).
auth_errorrefused the keyIt answered 401 or 403.
rate_limitedrate limited429.
client_errorrefused the requestAnother 4xx. Not a failure of the provider.
server_errorserver error5xx.
unreachableunreachableNo connection: refused, DNS, TLS (Envoy flags UF, DF).
timeouttimed outNo answer in time (UT, duration or idle timeout).
resetconnection resetThe 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:

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.
  • 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.

CallWhoReturns
GET /usage?group_by=…&bucket_seconds=…MembersRequests, tokens, cost per group, or a time series
GET /usage/summary?period=today|week|month (or from/to, bucket_seconds)MembersWhat the Usage tab shows: current and previous period, series, breakdowns
GET /provider-healthMembersEach provider's status over the last 15 minutes
POST /providers/{name}/checkOwner/AdminCheck now
GET /decisionsOwner/AdminThe decision log
GET /requestsOwner/AdminThe 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".

# 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:

RollupHoldsKept
elchi_ai_gateway_usage_1hUsage per UTC hour, project, gateway, provider, model, consumer and token typeAs the usage table
elchi_ai_gateway_requests_1hRequests 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​

TableTTLChange it with
elchi_ai_gateway_usage (+ _1h)90 daysusage.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_requestsPer row: the gateway's Retention (days) (default 7, 1–365)The gateway page
elchi_ai_gateway_requests_1h90 daysFixed
elchi_ai_gateway_decisions90 daysFixed
elchi_ai_gateway_upstream30 daysFixed
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.

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.

Losses are visible on the edge's loopback metrics:

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'
MetricMeaning
elchi_ai_gateway_usage_rows_written_total / _dropped_totalUsage rows written / lost
elchi_ai_gateway_usage_scrape_failures_totalFailed 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​

EndpointBindsWhat
http://127.0.0.1:9002/metricsLoopback 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/metricsAll interfaces (the upstream offers no option); the installer firewalls itThe 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:

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 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 · Sensitive data · Quotas, limits and costs · Operations · Troubleshooting