Skip to content

Logs, traces and metrics

Last updated: 2026-11-27T14:42:00-03:00 (UTC-3)

When a user says “the response was slow” or “it failed”, you need to find that request and see what happened: which model, which provider, how many attempts, how long. The gateway gives every request an ID, propagates the W3C trace to the provider, records the metadata in the console and exports logs, traces and metrics to the tools you already use.

Telemetry and request history contain metadata only. Logs, traces and metrics omit prompts and responses. The separate encrypted content capture feature can retain request and response content only when explicitly enabled; it is not a telemetry exporter.

  1. The client can send X-Request-Id (1 to 128 characters) and a W3C traceparent. Without valid values, the gateway generates its own.
  2. The response returns X-Request-Id and the request’s traceparent.
  3. Each call to the provider gets the same X-Request-Id and the traceparent of a child span. Retries and fallbacks show up as separate spans in the same trace.

To investigate: copy the request_id or the trace_id from the console and find, in your log backend, the request log and every upstream_attempt with the same ID.

Internal model helpers called within a request retain its trace and use a fresh server span plus a separate provider-attempt span. Their existing derived request IDs, such as <request_id>.classify, .route, .route-index and .cache, identify the helper operation. A background operation without an existing request span starts its own trace.

Outbound model-catalog pages also carry the initiating request ID and a fresh child traceparent, including public catalogs and authenticated connection discovery. The catalog still uses the configured provider credential, refuses redirects and keeps its existing cache behavior; a cached result makes no outbound call. Correlation headers contain identifiers only, never a prompt, response or credential.

Unexpected server failures log one safe cause at their owning boundary, with status, code, route where available and the trusted HTTP request/trace/span IDs. A storage library returns its error to that owner; it does not add a second global logger. failAs preserves existing domain event names and finite provider/resource metadata, while canonical status/cause/correlation fields cannot be replaced by added attributes.

  • request_failed and domain events such as feature_refresh_failed identify gateway failures. A committed change whose refresh fails still reports the existing synchronization outcome; logging does not undo the write.
  • provider_response_failed and agent HTTP events describe an upstream attempt, using finite HTTP status/cause/provider metadata. They never include response bodies, authorization, headers or URLs. Join them to the final HTTP event with request_id; an attempt may fail before a successful fallback, so its status is not necessarily the client’s final status.
  • A client cancellation is Info/499, not a server/provider fault. Operator stop remains the expected 503 policy outcome. SCIM retains its SCIM error envelope when classifying these outcomes.
  • Cached failures still produce an event for the current request with cache_replayed; caching does not erase that request’s failure journey.
  • otlp_logs_export_failed and otlp_traces_export_failed use finite reason (encode, request, transport, http_status), status and dropped-record/span counts. They use the existing base JSON handler, bypassing export of their own diagnostics. This avoids recursive failures when a Collector is down; endpoint/query/response text is never logged. telemetry_shutdown_failed identifies the affected signal and cleanup failure. These are batch/background diagnostics, not invented single-request spans.

For example, filter structured output by the returned request ID:

Terminal window
jq 'select(.request_id == "example-request-id") | {msg, request_id, trace_id, span_id, route, status, code, error}' gateway.jsonl

The console’s request-log explorer remains persisted request metadata; it does not become an index of every stdout/OTLP event. Use the matching IDs in the configured log backend to find detailed causes. CLI/configuration errors before the runtime logger is initialized retain their existing stderr diagnostics.

With usage_analytics (PostgreSQL), each authorized call becomes an event with key, team, model, provider, status, duration and tokens. The console uses these events in Request logs and in Analytics, without Prometheus or Grafana.

Feature Flag
Selectable columns and server-side sorting request_log_columns
Filter by exact HTTP status request_log_status_code
CSV export of up to 10,000 filtered rows request_log_export
Automatic refresh of the first page every 5 s, while the tab is visible request_log_live_tail
Time to first byte (ttfb_ms; TTFT for streams) request_timing
How many attempts to the provider each request made (Attempts column) request_attempts
Which deadline ended an operation (timeout_kind; Timeout column) Recorded by timeout controls; column selection uses request_log_columns
The end user of your app (X-Gateway-End-User or OpenAI’s user field) end_user_tracking
Session (X-Gateway-Session-Id), to follow a conversation or an agent run session_tracking
Request journey: stages, related trace requests, recording gaps and a permalink in the request details request_journey
Agent session graph: the steps of a session with declared agents, turns and parent/child sessions, apart from what the gateway observed (below) agent_sessions
Agent runs: coding-agent runs recognized from the requests alone, listed by agent, task and owner and opened as a thread (agent runs) agent_recognition
Verified client address of each request, kept apart from usage with its own retention, for filtering, journey, export and erasure (details) client_source_metadata
Recycle bin: deleted keys, teams and workloads, with author and request ID recycle_bin
  • End user: 1 to 128 characters, declared by the key, not authenticated. It becomes a filter, a column and the by_end_user ranking. An invalid header gives 400.
  • Session: filtering Request logs by a session shows its summary (requests, errors, duration, tokens, models, keys and up to 20 end users). API: GET /api/v1/admin/sessions/{id}.
  • On a phone (below 768 px) each request is a card that names every column, and the filter form folds into its summary after Apply, so the first result is on screen. On a wider screen the default columns fit; long IDs are shortened in the middle (hover for the whole ID, or copy it), and a table wider than its box says so under it and scrolls sideways.
  • Team roles only see their own teams’ events.
  • With key owners and tags, each event also stores the owner and the tags.

request_journey (off by default; requires request_logs) replaces the fixed three-step sketch in the request details with what the gateway actually persisted:

features:
request_logs: true
request_journey: true
  • Stages of the latest record: client request received (principal, key, team, owner, end user, session, operation), admission and guardrails (passed, refused with the gateway error code, blocked with the guardrail), routing (requested and served model, auto-route alias and baseline, cache_hit), upstream provider (provider, attempts, service tier, timeout; failed, skipped after a cache hit, not_reached after a refusal), response (status, duration, time to first byte, tokens) and, when you may see cost, valuation (known, partial, unknown or unvalued, with its basis).
  • Not recorded: every journey states the storage contract’s own limits (per-attempt provider/status/timing, internal stage durations, guardrails that passed, spans, bodies) and the gaps of this record, such as attempts or time to first byte not recorded (the flag was off or the record predates it), token usage not reported (unknown is not zero) or no valuation.
  • Provider sends (journey_attempt_lines, off by default; requires request_journey and attempt_charge_lines): a retried or fallen-back request lists each send under the upstream stage, oldest first, from its charge lines: provider, upstream model, outcome (answered, provider_error, transport_failure, unmeasured_answer), HTTP status and which send was final; with cost visible also each send’s valuation, amount and tokens, never its rate. The “per-attempt provider/status/timing” gap then narrows to attempt_timing_not_persisted: only the timing of each send is unknown. A request with one send needs no list (the record is that send). A retried record from before the lines were on keeps the old gap. The lines are read in the journey’s own snapshot, after the team filter.
  • Stored spans (span_store, off by default): when the span store has the request’s spans, the journey links its trace (stored_trace with the trace and request span ID, and an Open trace button) and no longer lists the gaps the spans cover: stage_timing_not_persisted, attempt_detail_not_persisted, attempt_timing_not_persisted, guardrail_passes_not_persisted and spans_in_trace_backend. A request without stored spans (older, sampled out) keeps them.
  • Records with this request ID: clients may reuse an ID; up to 20 records are listed (the newest kept) and the stages describe the latest.
  • Same trace: up to 20 other requests that share the trace ID (the earliest kept), with request ID, operation, model, status and duration only; each opens its own journey.
  • Copy link gives https://<console>/ui/#/logs/request/<request-id>. The link carries only the request ID: opening it signs in as usual and asks the server again with that session. The Evals screens link every request ID they show to this permalink.
  • Reading the drawer: times are local, like the request table (hover for the exact UTC instant); amounts print as exact decimals (US$0.00000186), never rounded or zero-padded; long principals, keys and IDs stay on one line, shortened in the middle, with the whole value on hover and a copy button.

Authorization is the request log’s: logs:read, plus live team membership for team roles, applied in SQL before both limits, so another team’s records neither appear nor use up a limit. A missing and an out-of-scope request ID give the same 404, so a link reveals nothing to someone outside its team; removing a membership closes the link on the next request. Fields follow the same flags as the CSV export: tags with usage_tags, session with session_tracking, end user with end_user_tracking, owner with identity_ownership, requested model with model_aliases, savings fields (avoided and cached tokens, auto-route baseline) with cost_optimization, and cost with usage_valuation plus analytics:read. Bodies are never returned. API: GET /api/v1/admin/requests/{id}/journey, answered with Cache-Control: private, no-store:

{
"request_id": "f8a8a2afe721ea6dede1673b4af78962",
"permalink": "/ui/#/logs/request/f8a8a2afe721ea6dede1673b4af78962",
"stages": [
{"id": "upstream", "state": "recorded", "facts": [{"name": "provider", "value": "openai"}, {"name": "attempts", "value": "1"}]}
],
"trace": {"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "related": [], "truncated": false},
"gaps": [{"code": "attempt_detail_not_persisted", "stage": "upstream", "message": "Only the number of upstream attempts is stored; ..."}],
"valuation_shown": false
}

With the flag off the endpoint answers 404 feature_disabled and the drawer keeps the sketch built from the list row. No migration: the journey reads existing columns and indexes.

A coding agent needs none of the headers below: with agent_recognition the gateway reads the agent, the run and its subagents from the client’s own requests, and a recognized run appears here as a session (the run ID is the session, the client the agent, the run that spawned it the parent session). The headers are for your own agent code, and they win over what recognition reads.

agent_sessions (off by default; requires session_tracking, which requires request_logs) turns a session into a graph of its steps. An agent framework already groups its calls with X-Gateway-Session-Id; with the flag on it may also declare, per request:

Header Meaning Rules
X-Gateway-Agent-Id The agent that made the call (planner, researcher, …) 1–128 printable characters, one value
X-Gateway-Turn-Id The turn (one user message and the calls it causes) the call belongs to Same
X-Gateway-Parent-Session-Id The session that spawned this one, for a sub-agent run Same; ignored when equal to the session ID
features:
request_logs: true
session_tracking: true
agent_sessions: true
Terminal window
curl -s http://gateway/v1/chat/completions -H "Authorization: Bearer $KEY" \
-H 'X-Gateway-Session-Id: run-42' -H 'X-Gateway-Agent-Id: planner' -H 'X-Gateway-Turn-Id: turn-1' \
-H "traceparent: $TRACEPARENT_FROM_PREVIOUS_ANSWER" -d @request.json

An invalid or repeated header answers 400 invalid_agent_context before any provider call; with the flag off the headers are ignored. These labels are asserted: the client declares them, nothing authenticates them, and they never authorize, route, cache or bill. The graph sets them apart from what the gateway observed itself:

  • Steps: every usage event of the session (model calls, with operation, model, provider, status, duration and provider-reported tokens) and every MCP tool execution through the gateway (tool_call, by configured tool grant and server, with status and duration, including a call that failed at the MCP server; recorded with usage_analytics on, after the complete response). A step’s finish reasons come from the GenAI telemetry; tool_calls, tool_use and function_call (Chat Completions and Messages) mark a step that asked for a tool. Responses and Gemini answers report stop for a tool request, so their tool requests are not marked.
  • Observed links: caused_by_span when a request’s W3C traceparent names the server span of an earlier step (the client continued the trace from the gateway’s answer, which returns its own traceparent); traces group the steps that share a trace ID. Request IDs are never used to infer a link: a client chooses them. The gateway’s own helper calls (classification, routing, guardrail moderation) carry no session and are not steps; a semantic fallback is a step of its own, with the same session and agent headers.
  • Asserted links: agents and turns group steps; same_turn_next links each step to the previous step of its turn; parent sessions and child sessions (other sessions whose steps name this one as parent) are listed with their own step counts.
  • Totals add each listed step once (truncated says when later steps exist). Token sums are null when no model call reported them, with input_reported_steps and output_reported_steps out of model_calls: unknown is not zero. Child sessions are never added: their usage stays in their own graph, so a parent and its sub-agents are not double counted.

The console shows Show agent graph under the session summary of a session-filtered Request logs page: one lane per declared turn (and one for steps without a turn), a time ruler from the session’s start to its last step, a bar per step on that axis labelled with its duration, each link labelled observed or asserted, and child/parent sessions that open the same view. API: GET /api/v1/admin/sessions/{id}/graph?from=&to= (default the last 24 hours, at most 90 days), answered with Cache-Control: private, no-store:

{
"session_id": "run-42",
"parent_sessions": [],
"child_sessions": [{"session_id": "run-42-research", "basis": "asserted", "steps": 3, "first_at": "...", "last_at": "..."}],
"agents": [{"id": "planner", "basis": "asserted", "steps": [0, 1, 2]}],
"turns": [{"id": "turn-1", "basis": "asserted", "steps": [0, 1, 2]}],
"steps": [
{"index": 0, "kind": "model_call", "request_id": "r1", "span_id": "c8460d20618f472f", "operation": "chat", "model": "agent", "status": 200, "finish_reasons": ["tool_calls"], "tool_requested": true, "agent_id": "planner", "turn_id": "turn-1", "agent_context_recorded": true},
{"index": 1, "kind": "tool_call", "request_id": "r2", "tool_name": "lookup", "tool_server": "kb", "status": 200, "agent_id": "planner", "turn_id": "turn-1"},
{"index": 2, "kind": "model_call", "request_id": "r3", "parent_span_id": "c8460d20618f472f", "finish_reasons": ["stop"]}
],
"edges": [
{"from": 0, "to": 1, "relation": "same_turn_next", "basis": "asserted"},
{"from": 0, "to": 2, "relation": "caused_by_span", "basis": "observed"}
],
"totals": {"steps": 3, "errors": 0, "input_tokens": 14, "output_tokens": 4, "token_reported_steps": 2, "child_sessions": 1, "includes_child_sessions": false},
"gaps": [{"code": "bodies_not_recorded", "stage": "", "message": "..."}]
}
  • Authorization is the request journey’s: logs:read, plus live team membership for team roles, applied in SQL before every limit (200 steps, earliest kept; 50 child sessions; 5 parent declarations). A missing and an out-of-scope session give the same 404; a parent session is a link only when the reader may see one of its steps in the range. Removing a membership closes the graph on the next request. Session IDs are chosen by clients and not namespaced: two teams may send the same ID, so a global role sees the steps of both (each with its key and principal) and a team role only its own.
  • Partial, late and duplicate data: the graph is a read of what PostgreSQL holds at observed_at; a step written later appears on the next read. Requests made while the flag was off, or whose agent row could not be written, stay as steps with agent_context_recorded: false and the agent_context_missing gap. Each agent row belongs to exactly one usage event (request, trace, key and the event’s start), so a client that reuses a request ID gets one row per request, never another request’s labels; a repeated write of the same event keeps the first. Trace sampling (the traceparent flags) and exporter loss do not change the graph, which never reads exported spans. A cancelled request is a step with status 499 (client_closed).
  • Persistence and retention: migration 131 adds gateway_agent_steps, apart from usage events, receipts and the ledger, whose fingerprints do not change. A model-call row lives as long as its usage event: every replica deletes, each minute, rows older than the oldest remaining usage event, so the table follows metadata retention and never outlives it; a tool row has no usage event, so with an active metadata retention policy it expires after the same number of days, and while metadata is preserved it follows the oldest usage event, never before 90 days (the longest read range). Rows are written after the usage event, never affect the request and log agent_step_record_failed on error.
  • Never recorded: prompts, answers, tool arguments and tool results; per-attempt spans. Tools are known only from finish reasons and gateway MCP executions.

With the flag off the endpoint answers 404 feature_disabled, the console shows no graph and existing rows stay until retention removes them. Upgrade step: run migration 131 with this release and upgrade every replica before enabling the flag; an older replica ignores the headers and answers the endpoint 404.

timeout_kind is first_byte, idle, max_duration, client_stall, request or attempt when that timeout ended the operation; absent values remain absent. It is exported as gateway.timeout_kind on the root span and retained in usage/log metadata, without payloads. A successful fallback does not inherit the previous attempt’s timeout label. Historical metadata stays readable under existing team/log permissions when the timeout feature is later disabled.

A provider attempt to an openai target names the OpenAI API it used in openai.api.type (the OpenTelemetry OpenAI attribute: chat_completions or responses) on its span. On an api: auto target, its upstream_attempt log also carries wire_api (same values) and wire_api_reason, one of reasoning_effort_object, reasoning_effort_max, tools_with_reasoning_effort, responses_translation_refused or chat_completions_sufficient; the attempt log of any other target keeps its fields unchanged, since its API is the configured one. Each attempt of a fallback or retry has its own value.

An attempt to a Claude target with prompt_cache: {mode: auto} that placed cache points adds prompt_cache_points (how many, 1 to 4) to its upstream_attempt log; no other attempt gains the field.

With span_store the gateway also keeps its own spans (request, routing decision, provider attempts with timing and ledger cost, cache lookups, guardrails, MCP tools, helper calls) in PostgreSQL, written off the request path, and the console opens any request as a trace tree. The stored spans use the same trace and span IDs as the OTLP export below, so both views line up. Settings, retention, sampling, the API and the metrics are in Traces and the span store.

The structured request and attempt logs have request_id, correlation_id, trace_id, span_id, route, status and duration. Every other log written while serving a request (a failure, a stream cut short, a storage error) carries the same request_id, trace_id and span_id, so one search returns the whole journey. Once the request’s key is authenticated, every line also carries the identity hierarchy: key_id, principal, team and, with organizations on, organization_id (empty when none applies), on stdout and OTLP alike. That includes a request refused right after authentication (the source network, an invalid attribution header, a scope the key lacks, organization or team policy storage unavailable); a key that is unknown, expired or revoked authenticates nobody, so its 401 names no caller. The request line adds traceparent: ignored_malformed when the client’s traceparent did not parse and was replaced by a trace of the gateway’s own. Exported OTLP spans carry the same identity as gateway.key.id, gateway.principal, gateway.team.id and gateway.organization.id, and model call attempts carry the generation parameters the client sent (gen_ai.request.temperature, gen_ai.request.max_tokens and the others listed in traces). None of these are metric labels. The gateway sends logs and traces over OTLP/HTTP, in binary protobuf by default, to any OTLP receiver: an OpenTelemetry Collector, or directly a pipeline such as Vector (below). The send queue is bounded: if the Collector fails, the request goes on and telemetry may be lost.

The otlp_logs and otlp_traces boot flags enable the two exporters independently. With a flag enabled, its destination is selected once at startup, in this order: nonempty signal-specific environment override, explicit YAML value, default. An empty environment override falls back to YAML/default. The defaults are http://127.0.0.1:4318/v1/logs and http://127.0.0.1:4318/v1/traces:

telemetry:
otlp:
logs_endpoint: http://collector:4318/v1/logs
traces_endpoint: http://collector:4318/v1/traces
Key Default What it does
telemetry.otlp.logs_endpoint http://127.0.0.1:4318/v1/logs OTLP/HTTP address the logs exporter sends to, with the signal path
telemetry.otlp.traces_endpoint http://127.0.0.1:4318/v1/traces OTLP/HTTP address the traces exporter sends to, with the signal path

The shipped base YAML and its Helm copy explicitly contain the loopback URLs, so their source is yaml; only an omitted/empty YAML endpoint without an override reports default.

telemetry.otlp.protocol selects the encoding for both signals: http/protobuf (the default, application/x-protobuf) or http/json (application/json). Every OTLP receiver must accept protobuf; some accept nothing else (Vector’s opentelemetry source, measured on 0.61). The standard OTEL_EXPORTER_OTLP_PROTOCOL variable overrides the YAML when an exporter is enabled. Any other value, gRPC included, stops the boot with the setting named.

The overrides are OTEL_EXPORTER_OTLP_LOGS_ENDPOINT and OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. Each URL is used as supplied: include the signal path yourself. Use an absolute http or https URL with a hostname and a valid port if supplied, up to 2,048 bytes; user info, query and fragment are rejected. YAML destinations are validated even when their flag is off; environment overrides for disabled exporters are ignored. No general OTEL_EXPORTER_OTLP_ENDPOINT, gRPC or OTLP authentication/header configuration is provided by this setting. Metrics have their own exporter, below.

Every exported log, span and metric carries the same resource attributes, so a backend joins the three signals of one deployment and tells deployments apart:

Attribute Value Set by
service.name ai-gateway Fixed
service.version The gateway’s version (gateway version prints it) telemetry.otlp.service_version, or service.version in OTEL_RESOURCE_ATTRIBUTES
deployment.environment.name and deployment.environment Your environment, such as production or staging; left out when not set telemetry.otlp.deployment_environment, or deployment.environment.name (or deployment.environment) in OTEL_RESOURCE_ATTRIBUTES
telemetry:
otlp:
deployment_environment: production
# service_version: 2026.11.2 # only to name a build differently from its version

Set deployment_environment on every installation you export from: it is what most backends use to split production from staging, and the gateway cannot guess it. The older name deployment.environment is written next to deployment.environment.name because several backends still read only the older one. The values are read once at startup, take 1 to 128 printable characters, and come from the standard OTEL_RESOURCE_ATTRIBUTES variable first, then the YAML, then the binary’s version (for the version only); an override value that is not valid is ignored. Other keys of OTEL_RESOURCE_ATTRIBUTES are not exported. The same attributes go on log destinations that speak OTLP, and Settings → Infrastructure shows the values in effect with their source. They are not metric labels on /metrics.

With telemetry.otlp.console_url set to the console’s address, every exported span carries gateway.console.url, the span in the console’s trace view (<console_url>/#/traces/<trace_id>?span=<span_id>): from a trace in your APM backend, one click opens the same trace in the gateway with its routing, attempts, cost and evaluations. Unset (the default), no link is exported.

telemetry:
otlp:
console_url: https://gateway.example.com/ui # absolute http(s), no query or fragment

The address is read once at startup and shown in Settings → Infrastructure (Resource line). It is an attribute of the span, not of the resource, and names no team or key: whoever follows it still signs in and sees only what their role allows. To link the other way, from the console to your APM, use spans.apm_link_template.

A reachable Collector is needed to receive telemetry, not to boot or serve inference. Without one, export may fail or drop records from the bounded queues; the gateway continues serving requests. In a container, loopback refers to that container: use the Collector service address when it is a separate service. Disabling both flags keeps structured JSON stdout logs.

A Collector is optional. Any OTLP receiver can take the gateway’s logs and traces directly, for example Vector writing them to an S3 bucket. Measured on 2026-11-07 with the Quickstart stack, Vector 0.61 and MinIO standing in for S3:

vector.yaml
sources:
otlp:
type: opentelemetry
grpc: {address: 0.0.0.0:4317}
http: {address: 0.0.0.0:4318} # OTLP/HTTP: protobuf only, the gateway's default
sinks:
s3_logs:
type: aws_s3
inputs: [otlp.logs]
bucket: otel
key_prefix: "logs/%Y-%m-%d/"
region: us-east-1
endpoint: http://minio:9000 # omit for AWS S3
force_path_style: true # MinIO and other S3-compatible stores
encoding: {codec: json}
framing: {method: newline_delimited}
s3_traces:
type: aws_s3
inputs: [otlp.traces]
bucket: otel
key_prefix: "traces/%Y-%m-%d/"
region: us-east-1
endpoint: http://minio:9000
force_path_style: true
encoding: {codec: json}
framing: {method: newline_delimited}
  • Credentials: give Vector its S3 credentials through AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, or an IAM role. On 0.61, a ${VAR} placeholder inside the sink’s auth block was sent literally.
  • Gateway: point it at Vector with OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://vector:4318/v1/logs and OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://vector:4318/v1/traces. With Compose, put both in an override file next to compose.yaml; the bundled Collector service can stay stopped.
  • Decoding: without a decoding option, Vector writes one JSON line per record, with hex trace_id/span_id and the gateway’s attributes as fields. decoding: {codec: otlp} keeps the raw OTLP structure, but Vector’s JSON encoder then prints the binary IDs as unreadable text.
  • Correlation: a request’s log record and its server and provider spans share the request’s trace_id, and carry request_id/request.id. Prompts and answers are never exported.
  • When the receiver is down or stalled: requests are unaffected. Measured, the latency stayed under 1 ms on average with Vector stopped and with it paused. Records that could not be sent are dropped from the bounded queue and counted in gateway_otel_dropped_total{signal}; alert on its rate.

The same pattern on GKE, with the logs written to a Cloud Storage bucket. The kit of the multi-region validation ships it as a manifest (deploy/validation/gke-multiregion/manifests/vector.yaml): a ServiceAccount, the configuration below, a one-replica Deployment, a Service on 4318/4317 and a NetworkPolicy that admits only the gateway Pods.

# vector.yaml (Vector 0.61, distroless-libc image pinned by digest)
data_dir: /var/lib/vector
sources:
otlp:
type: opentelemetry
http: {address: "0.0.0.0:4318"} # protobuf, the gateway's default protocol
grpc: {address: "0.0.0.0:4317"}
sinks:
bucket:
type: gcp_cloud_storage
inputs: [otlp.logs]
bucket: my-gateway-logs
key_prefix: "logs/us-central1/%Y-%m-%d/"
filename_extension: ndjson
compression: none
encoding: {codec: json}
framing: {method: newline_delimited}
batch: {timeout_secs: 10} # one object about every 10 s while logs flow
healthcheck: {enabled: false} # it reads bucket metadata, which object creation alone does not grant
  • Identity, without a key: with Workload Identity Federation for GKE, grant roles/storage.objectCreator on the bucket to the Kubernetes ServiceAccount itself, principal://iam.googleapis.com/projects/<number>/locations/global/workloadIdentityPools/<project>.svc.id.goog/subject/ns/<namespace>/sa/vector. Vector takes its token from the GKE metadata server. Create-only is enough: every object name carries a UUID, so nothing is overwritten.
  • Gateway, with Helm: set gateway.otlpLogsEndpoint: http://vector:4318/v1/logs as well as telemetry.otlp.logs_endpoint in the YAML. The chart sets OTEL_EXPORTER_OTLP_LOGS_ENDPOINT whenever its Collector is on, and that environment override wins over the YAML. With networkPolicy.egress.enabled, add an extraRules entry to the Vector Pods on 4318.
  • What lands: one JSON line per record, with the gateway’s attributes (request_id, trace_id, route, status, duration) as fields. Prompts, answers, keys and tokens are never in the records.
  • Losing the receiver: the gateway’s log queue holds 1,024 records and a batch that fails to send is not retried, so records produced while Vector is away are dropped (counted in gateway_otel_dropped_total{signal="logs"}); inference is unaffected. Run Vector with a persistent buffer, or more than one replica behind the Service, when the logs must survive its restarts.

Measured on GKE (2026-11-21), with this configuration and identity: turning the logs on was a helm upgrade under load with no failed request of 1,782; the request IDs of 40 requests were all in the bucket within about 27 s; no secret value or secret-shaped string (provider keys, gateway tokens, bearer values) appeared in any of the 13 objects; and deleting the Vector Pod under traffic affected no request (none of its records were lost in that short outage, which the bounded queue does not guarantee). The rest of the production setup around it is in run on Kubernetes in production.

Settings & sources → Infrastructure and the existing administrative configuration summary show only each signal’s enabled state, whether an active validated destination was captured at boot, its source (default, yaml or environment) and its restart requirement. They never return the destination URL, host or environment-variable name. Configured is not a health check or proof of delivery. A disabled signal shows configured false and source null, without erasing latent YAML; unavailable metadata is not presented as a configured destination. Endpoints and these flags require a restart/rollout, and subsequent runtime configuration refreshes retain that applied boot snapshot.

Request and attempt records use typed attributes; context enrichment preserves an explicit or logger-bound request/trace/span ID instead of adding it twice. This changes internal encoding, not the log contract or telemetry controls. The request and attempt field names, order, types and levels remain compatible.

What to look for when a request fails:

  • request_failed (Error for a 5xx): the gateway could not serve the request; code is the error code the client received and error the cause. Some failures keep an older, specific name (key_lookup_failed, analytics_query_failed, …).
  • upstream transport failure (Warn, one per attempt) and upstream_transport_failure (Error): the provider could not be reached; provider names the connection and error the cause, with the URL’s query and credentials removed.
  • stream_copy_failed: an answer was cut after it started; side identifies the provider (Warn), client (Info), or administrative gateway stop (gateway, Info). bytes_sent records how much was written. An administrative stop uses the bounded gateway_panic result where an attempt result is recorded; it is not a provider-health observation.
  • client_closed_request (Info): the client went away before the answer. It is recorded with status 499, in the request log, the metrics and the usage events, and is not counted as a provider failure nor by the circuit breaker.
  • Administrative emergency stop: a request interrupted before its headers gets 503 gateway_panic, rather than the client-disconnection status 499. If an unfinished answer already started, the connection is interrupted without replay or a new HTTP status. The first cancellation cause wins: a client departure or deadline that happened first retains its own classification. IDs still identify the affected journey; the stop must not count as a provider-health failure. See operations.
  • panic in request and background_panic (Error): a defect, with its stack. When the answer had already started, the connection is aborted so the client does not take a truncated answer as complete.

MCP tool executions also produce a log and a span, with the tool and the result, without arguments or responses.

Exported spans follow the OpenTelemetry GenAI semantic conventions (development status) for every model call, so a tracing backend that understands gen_ai.* shows the operation, provider, models, finish reasons and token usage without gateway-specific parsing. They ride on the existing exporters: otlp_traces for spans and logging.request_events: stdout for the request event’s gen_ai member. No new flag; the attributes appear as soon as those are on.

Two spans describe each model call:

  • Provider attempt (span kind CLIENT, one per send, retries and fallbacks included): what was sent where. Its name is {gen_ai.operation.name} {gen_ai.request.model}, such as chat gpt-4o-mini, for chat, text_completion, embeddings and generate_content; other operations keep POST provider.<operation>, passthrough keeps <METHOD> provider.passthrough. The span still ends when the response headers arrive.
  • Request (span kind SERVER, the gateway’s root span): what the client asked for and received, ended when the answer is complete. Operations that are not model calls (vector stores, containers, conversations, fine-tuning, token counting, stored-response reads, deletes and cancels) carry no gen_ai.*. Token usage is on this span only, so a backend that sums gen_ai.usage.* over a trace counts each request once, however many attempts it made.
Attribute Type Attempt span Request span Value
gen_ai.operation.name string ✓ ✓ chat (Chat Completions, Messages, Responses), text_completion, embeddings, generate_content; other operations use the gateway’s name (images, audio_speech, rerank, moderations, passthrough, …), as the convention allows.
gen_ai.provider.name string ✓ ✓ (not on a cache hit) Well-known product of the connection: from its preset, then its protocol and endpoint: openai, azure.ai.openai, azure.ai.inference, anthropic, aws.bedrock, gcp.gemini, gcp.vertex_ai, cohere, ollama; another protocol keeps its own name. An OpenAI-compatible endpoint reports openai, as the convention prescribes for clients that cannot tell.
gen_ai.request.model string ✓ upstream model (targets[].model) ✓ model the client sent
gen_ai.request.stream boolean ✓ ✓ Present (true) only when the client asked for a stream.
gen_ai.response.model, gen_ai.response.id string ✓ Only what the answer relayed without translation reported. Absent for a translated answer (another protocol, the Responses API behind Chat Completions, Messages/Responses/generateContent ingress), whose body names the alias, and for a cache hit. With responses_lifecycle on (OpenAI Responses), the ID is the gateway-issued response ID the client received.
gen_ai.response.finish_reasons string[] ✓ One per generation in provider order, at most 16 (stop, length, tool_calls, end_turn, MAX_TOKENS, …). A Responses answer maps completed to stop, incomplete to its reason and failed to error. Translated answers carry the canonical reason. Streams are read only with stream_usage. Absent on a cache hit.
gen_ai.response.time_to_first_chunk double (s) ✓ Successful streams only (not an error answer or a semantic fallback): time to the first byte written to the client.
gen_ai.usage.input_tokens, gen_ai.usage.output_tokens int ✓ Provider-reported counters; absent when not reported, never zero by default.
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens, gen_ai.usage.reasoning.output_tokens int ✓ Same sources as the request event’s tokens.cache_read, cache_write and reasoning.
gen_ai.conversation.id string ✓ ✓ X-Gateway-Session-Id, under session_tracking; caller-declared. With agent_recognition, a recognized coding-agent run that declared no session carries its run ID here (the client’s own, or a derived one). Otherwise no fallback ID is invented.
gen_ai.agent.name string ✓ Under agent_recognition: the recognized client (the name of the rule that matched, such as claude-code).
gateway.agent_run.class, gateway.agent_run.basis, gateway.agent_run.turn, gateway.agent_run.compacted, gateway.agent_run.tool_steps string, string, int, boolean, int ✓ Under agent_recognition: the request class (main, subagent, compaction, auxiliary), how the run ID was known (client, declared, derived), the number of typed messages in the context window, true when that window starts from a compaction summary, and the tool steps this request reported. Labels and counts, never text.
gateway.agent.id, gateway.turn.id, gateway.conversation.parent_id string ✓ The asserted agent labels, under agent_sessions.
server.address, server.port string, int ✓ Host and port of the connection’s base URL (default 443/80); never the path, query or user information.
error.type string ✓ ✓ Attempt: the provider’s HTTP status (429, 500, …), or timeout, cancelled, transport_error before any answer; the span status is then error. Request: the status the client received, when 400 or more, or stream_interrupted when the provider cut an answer that had already started (the status is then the 200 already sent; the span status is error and gateway.stream_cut says provider).
gateway.provider.id, gateway.model.alias string ✓ gateway.provider.id The configured connection ID and the alias the request resolved.

MCP tool calls are execute_tool spans named execute_tool <tool> with gen_ai.tool.name (the configured tool grant name), gen_ai.tool.type: extension, gen_ai.conversation.id and error.type; a tool listing keeps the MCP operation span. With agent_recognition, each tool a coding agent ran itself and reported in its next request is also an execute_tool <tool> span, a child of that request’s span: gen_ai.tool.name, gen_ai.tool.type: function, gen_ai.tool.call.id, gen_ai.conversation.id, gateway.tool.reported_by: client and, when the client reported a failure, gateway.tool.reported_error: true. The gateway did not see that tool run, so the span has no duration, and it never carries arguments or results. The span the gateway stores for it is named client tool and keeps the tool’s name in an attribute shown only with content_structure:read; the exported span keeps the convention’s name. The X-Request-Id and a child traceparent already reach the MCP server.

Content is never exported. The conventions’ opt-in content attributes (gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions, gen_ai.tool.definitions) are not emitted at all; request and response bodies are retained only by encrypted content capture, under its own policy. Every string is checked before export: identifiers (models, response IDs, provider names, tools) must be 1–256 characters of letters, digits and _ . : / @ + = -, finish reasons 1–64 of letters, digits and _ . -; anything else is left out rather than sent. No request or response ID enters a metric label.

Upgrade note. Before this release, attempt and other provider spans used gen_ai.provider.name for the connection ID and gen_ai.request.model for the alias. They now carry the convention’s values; the connection ID moved to gateway.provider.id and the alias to gateway.model.alias. Spans that are not model calls (provider health checks, video task polls, containers, conversations, skipped attempts) keep their names and now name their connection gateway.provider.id and their model gateway.model, and no longer use gen_ai.*. Attempt span names changed from POST provider.chat / POST provider.<operation> to chat <model> (and the other well-known operations) as above. Update trace queries and dashboards that filter on the old names. The Langfuse destination format is unchanged.

logging.level selects the minimum severity of the shipped JSON logging pipeline. The default is info; the other accepted values are warn and error. The existing OTLP log wrapper delegates its enabled check to the same handler, so this selection also filters that pipeline’s exported records. JSON is the fixed shipped stdout format, not another configurable format field. Log content still excludes request payloads and credentials at every supported level.

With boot_settings_view and the existing global configuration-read permissions, GET /api/v1/admin/config adds optional infrastructure.logging_settings: one read-only logging.level row with its captured value, default info, source and rollout requirement. Settings & sources → Infrastructure → Structured logs shows the same information inline, alongside the unchanged per-signal OTLP status. This remains the startup inspector; the optional runtime editor below is separate.

Omitted, null or empty YAML level uses Default; an explicit valid value, including info, retains YAML provenance. There is no log-level environment override. Capture follows successful construction/installation of the owned logger; an uncaptured or arbitrary injected logger is Unavailable, and the view does not infer its filter from configuration. The existing normalized summary remains compatible when the visibility flag is off. Configuration refresh preserves the startup capture; changing YAML requires a rollout.

The threshold continues to filter existing Info events, including config_applied, at warn or error. The view does not force an announcement through the chosen filter, prove Collector delivery or report every producer’s custom logger. Persisted Request logs and usage analytics have their own recording flags and permissions; this stdout/OTLP threshold does not disable that database history. When an existing refresh observes lost view/access, the page clears the captured data; a later authorized refresh can reload it. The startup inspector adds no polling or writer. Optional runtime management below retains this immutable capture.

Change the minimum severity without restarting

Section titled “Change the minimum severity without restarting”

Enable features.logging_management (default false) with ui and PostgreSQL configured. The YAML logging.level remains the baseline (info by default; warn and error are also accepted). In Settings & sources → Runtime logging, a global admin can save an override or revert it to YAML; a global viewer can inspect current state. logging:read and logging:manage are separate permissions. Inference keys, operators and team-scoped roles cannot use this control. The flag grants no permission and does not depend on the startup-view flag.

The canonical API is GET, PUT and DELETE /api/v1/admin/logging. GET supplies the current global configuration version, saved override, effective policy/source and separately observed applied level/source. PUT accepts exactly {"version":4,"level":"warn"} using the version just read; DELETE accepts only that current version. Mutation requires the authenticated same-origin session and CSRF token. The API reference includes runnable session-based examples. Unknown members, duplicate/case-fold names, nulls, noncanonical levels and trailing payloads are rejected. There is no debug/payload logging switch.

Changes are persisted with the shared optimistic configuration version and actor/request-ID audit in one PostgreSQL transaction. Each current replica validates the complete snapshot before applying its owned logging controller. Synchronization uses the existing refresh loop; it is not instantaneous cluster-wide application. JSON, bound/context/stdlog handlers and the OTLP log wrapper share the current minimum. An in-flight request uses the threshold in effect for each log record; its authorization, response and billing are unchanged. Filtering occurs at the handler enabled check; already accepted or queued records can arrive after a change, without retroactive deletion. Info records, including request/startup announcements, can be suppressed; persisted Request logs, audit history, metrics and trace export retain their own controls.

The startup logging_settings row, YAML source and V1–V11 parameter metadata remain immutable and require rollout for changes to their baseline. They do not pretend a runtime edit happened at boot. The new view distinguishes effective policy from an unavailable custom logger: unknown applied values/sources are paired null, and a process without an owned controller refuses mutations with 503 logging_controller_unavailable. Main installs its owned controller before the first refresh. A successful refresh reasserts the accepted minimum even when the stored version has not changed.

Turning logging_management off restores that replica’s YAML/default minimum and retains the dormant saved override. Re-enabling applies it again after refresh. Revert deletes an existing override; a missing override returns 404. Invalid/corrupted configuration or database failure leaves the last valid local threshold and snapshot in service. If persistence succeeds but local refresh fails, the mutation reports configuration_sync_pending: reload before retrying, since the write may already be committed.

A conflict preserves the authorized console draft and its original version. Reloading shows the latest state without silently rebasing the draft; the admin explicitly adopts that version after review. Losing access or disabling the feature removes the draft and ignores late replies. After a known denial, the console refreshes parent authorization; a successful viewer read of logging alone cannot restore a management form. The console never echoes untrusted diagnostic bodies.

Back up the database and preserve external secrets, then deploy a binary supporting additive migration97 and the new flag to every replica before enabling runtime control. Already-running older binaries do not implement the controller; do not advertise them as synchronized. Their newer-schema guard also prevents restarting against schema97. There is no automatic schema downgrade: remove/revert the override with a supporting binary, and follow the explicit backup/restore rollback procedure if reverting the binary version. Migration history must not be edited to bypass the guard.

After rollout, read /api/v1/admin/logging on the actual replicas and compare applied/source with effective policy. Test a bounded local request and correlate its request ID with the mutation audit and the records permitted by the chosen severity. A missing Info log after selecting warn is not proof of missing request execution. Restore the baseline with the versioned revert action rather than changing the controller outside configuration ownership.

logging:
write_mode: async # default; or sync

logging.write_mode (default async, read at startup; change it with a rollout) selects where the JSON log records are encoded and written to stdout:

  • async: one worker goroutine encodes and writes the records, taken from a bounded queue of 1,024 records, and writes whole lines in batches of up to 32 KiB (a batch is flushed as soon as the queue is empty). The request goroutine only hands its request line over.
    • Order: records reach stdout in the order they were logged, one queue and one worker; the lines of one request stay in order.
    • Backpressure, no loss: when the queue is full the caller waits for room; no record is dropped. Waits are counted in gateway_log_queue_waits_total.
    • Records written before the caller goes on: a record at Error level or above, and any record carrying a value other than a string, number, boolean, duration or time (an error, a map, a structure, a group), waits until everything queued before it is on stdout and is then written by the caller itself before the log call returns. So error lines are never left in the queue, and no value the caller may change later is read by another goroutine.
    • Shutdown: a graceful shutdown or a startup failure writes every queued record before the process exits (bounded by a 2-second window; if stdout is stuck past it, the count left is written to stderr). A record logged after that is written directly.
    • Limit: a crash that skips shutdown (an unrecovered panic, SIGKILL, an out-of-memory kill) loses the Info and Warn records still queued, at most 1,024 records. Choose sync when every line must be on stdout before the next line of code runs.
  • sync: every record is encoded and written on the goroutine that logs it, as before this setting existed.

Both modes write the same records with the same fields; the level filter (logging.level and the runtime override), the request, trace and span IDs and the OTLP log export are applied before the queue and do not change. With logging.request_events: stdout the log and the events still share stdout through one serialized writer, and no record is ever split between two writes. On the rig in how performance is measured, async measured higher throughput and a lower median latency than sync, with CPU per request within the noise of it; that measurement is why it is the default.

With boot_settings_view, GET /api/v1/admin/config returns infrastructure.logging.write_mode (mode, source default or yaml, default, restart_required, active: whether this process writes through the queue, queue_capacity), and Settings & sources → Infrastructure → Log writes shows it, read-only. This is an operator control, not a feature flag.

With logging.request_events: stdout (default off, read at startup), every finished inference request also writes one JSON line {"event":"gateway.request","schema_version":1,...} to stdout, next to the log: a stable, versioned record for an audit or billing pipeline, with IDs, timings, routing, attempts, tokens, cost, key, team, organization, end user, tags, guardrail outcomes and parameter policy names, never content or credentials. A collector tells events from log records by the event member. The queue is bounded and never delays a request; losses are counted in gateway_request_events_dropped_total. Schema, Vector example and limits: request audit events.

With log_destinations, each request becomes a metadata record (the request log row’s fields, including feedback_key when the request carried X-Gateway-Feedback-Key) delivered in batches to:

  • S3, GCS or Azure Blob, as JSON Lines;
  • Langfuse, as a generation span over OTLP (v3 and v4);
  • Datadog;
  • an HTTP endpoint.
features:
log_destinations: true
log_destinations:
- id: archive
type: s3 # s3, gcs, azure_blob, langfuse, datadog or http
bucket: gateway-logs
region: us-east-1
prefix: requests/
- id: dd
type: datadog
api_key_env: DD_API_KEY

At most 10 destinations; the block is YAML only (restart to change).

Key Types Default What it does
log_destinations[].id all required Unique lower-case identifier, shown in Settings & sources and the status API
log_destinations[].type all required s3, gcs, azure_blob, langfuse, datadog or http
log_destinations[].bucket s3, gcs required Bucket the JSON Lines files are written to
log_destinations[].region s3 required AWS region of the bucket
log_destinations[].prefix object stores empty Relative path of the objects inside the bucket or container (letters, digits, ., -, _, /)
log_destinations[].credential s3, azure_blob auto Where the cloud credential comes from: for S3 env, web_identity, container or cli; for Azure client_secret, workload_identity or managed_identity
log_destinations[].profile s3 empty AWS profile name of the shared configuration, for cli or auto
log_destinations[].account_url azure_blob required https://<account>.blob.core.windows.net
log_destinations[].container azure_blob required Blob container the files go to
log_destinations[].endpoint langfuse, http required HTTPS address of the Langfuse instance or the HTTP receiver
log_destinations[].public_key_env langfuse required Variable holding the Langfuse public key
log_destinations[].secret_key_env langfuse required Variable holding the Langfuse secret key
log_destinations[].api_key_env datadog required Variable holding the Datadog API key
log_destinations[].site datadog datadoghq.com Datadog site, such as datadoghq.eu or us5.datadoghq.com
log_destinations[].service datadog ai-gateway service attribute of each log
log_destinations[].auth_header_env http empty Variable holding the whole Authorization header value sent to the receiver
log_destinations[].flush_seconds all 10 How often a batch is sent, 1–300 seconds
log_destinations[].max_batch all 500 Records per batch, 1–5000
log_destinations[].allow_insecure_http all false Allows http:// to a loopback address, for local testing only

Each destination has its own bounded in-memory queue. Full intake drops records instead of delaying inference. Ordinary delivery failures can drop a batch after bounded retries; a missing cloud credential retains a bounded batch with backoff until recovery or retirement. Retries may duplicate delivery. Settings & sources shows current worker-generation status and can send a correlated synthetic test record. This is best-effort export, not durable or exactly-once delivery.

The feature flag metrics_endpoint turns on GET /metrics, in the Prometheus text format. It is an operator control: set it in the features block of the gateway YAML (metrics_endpoint: true, as the bundled configuration does) or toggle it at runtime from Settings → Features or PUT /api/admin/features/metrics_endpoint; with it off, /metrics answers 404 feature_disabled. It is named by what it serves, not by the format; until 0.0.1-rc.2 it was prometheus_metrics, which is now refused naming metrics_endpoint, and a stored override under the old id is renamed by migration 195 (upgrading from 0.0.1-rc.2). Do not confuse it with telemetry.otlp.metrics_endpoint, the OTLP receiver address of the otlp_metrics push below.

With metrics_endpoint, /metrics exposes:

  • requests by route and status, with a duration histogram;
  • attempts by provider, model and outcome;
  • gateway_provider_errors_total{provider,model,class}: failed provider attempts, class one of transport (connection error or timeout), invalid_response, status_5xx, status_429, stream_interrupted (the provider cut an answer that had already started: a stream after its first byte, or a body on the buffered relay; that attempt is also in gateway_upstream_attempts_total as result="response", because its headers arrived). Client cancellations and administrator stops are not provider errors;
  • gateway_usage_write_failures_total: usage records the gateway could not persist (the request was served; its usage row is missing);
  • with a database, gateway_database_up and gateway_database_ping_seconds (see high availability); with secret_manager, gateway_secret_manager_secrets and gateway_secret_manager_failing_secrets;
  • in-flight requests, heap, goroutines and dropped OTLP records;
  • gateway_request_events_written_total and gateway_request_events_dropped_total{reason} (queue_full, write_error), with request audit events on;
  • gateway_log_queue_waits_total (log records whose caller waited because the queue was full) and gateway_log_queue_failed_total (queued records whose handler failed while being written), with asynchronous log writes (logging.write_mode: async, the default);
  • With inference_request_metrics (operator flag, off by default): gateway_inference_requests_total{provider,model,streaming,outcome} and the gateway_inference_request_duration_seconds histogram with the same labels, one count per finished inference request (below);
  • With pricing_coverage (operator flag, off by default; requires usage_valuation): gateway_pricing_coverage_total{provider,model,status}, every answered model call by whether its cost could be computed (below);
  • With rate_limit_observe_mode: gateway_rate_limit_would_limit_total{policy}, the requests an observe-only rate policy admitted past its limit;
  • With evaluation_metrics: gateway_evaluations_total, gateway_evaluation_score, gateway_evaluation_runs_total, gateway_evaluation_judge_cost_usd_total, gateway_evaluation_pending and gateway_evaluation_label_overflow_total, with bounded evaluation, value and team labels. With evaluation_monitors: gateway_evaluation_monitor_evaluations_total{type,outcome} and gateway_evaluation_monitor_transitions_total{type,kind}.
  • gateway_topics_units_total{facet,topic,origin} and gateway_topics_fits_total{kind,status} (Topics): units assigned by a fit (initial) or as they arrive (online), and fits by kind and status. topic is assigned or outlier; with topics.metric_topic_labels: N it names the N largest topics of each facet and folds the rest into other.
  • gateway_guardrail_findings_total{guardrail,outcome} (masked, blocked, and would_block/would_mask for monitor guardrails; misconfigured counts the checks of a judge guardrail that cannot decide for a reason of configuration), gateway_alert_deliveries_total{channel,outcome}, gateway_alert_rule_alerts_total{transition,severity,scope,source} and gateway_alert_rule_scans_total{outcome} (the alert rules), gateway_mcp_health_checks_total{server,outcome} and gateway_admin_bearer_failures_total{reason} (rejected admin API Bearer calls with the shared token: invalid, too_short, rate_limited; see the console), gateway_console_login_rejections_total{reason} (refused console token sign-ins: invalid, locked_out) and gateway_console_login_lockouts_total (client addresses locked out; see lockout after failed sign-ins);
  • gateway_caller_concurrency_in_flight{subject} (key, team) and gateway_caller_concurrency_admission_total{result} (admitted, refused), with concurrency caps per key and team on;
  • per-target capacity and semantic cache, described in the routing and cache guides;
  • the exact cache series: lookups, stores, shared-backend calls and the cache in use;
  • with span_store, the span writer’s series: gateway_span_store_spans_total{kind,result}, gateway_span_store_queued_requests_total, gateway_span_store_queue_depth, gateway_span_store_batches_total{result}, gateway_span_store_ledger_reads_total and the gateway_span_store_write_seconds histogram (span store metrics);
  • the inference series below: tokens, cost, time to first token, provider latency, circuit state, fallbacks and remaining budget.

Labels come only from configuration (route, status, provider, model, guardrail or channel IDs); never a request ID, user or content. Protect /metrics with a network or ingress policy.

Series Type Labels Measured
gateway_tokens_total counter provider, model, type (input, output, cached, cache_write, reasoning) Tokens the provider reported for a finished request, the same values the usage ledger records. A count the provider did not report is not added (unknown is not zero). Streams count only when their usage is known (usage in streams). With OpenAI-style usage, cached is part of input (the prompt tokens read from the provider’s cache), so do not add the two. cache_write is what the provider wrote to its prompt cache (Anthropic’s cache creation tokens) and reasoning the output spent reasoning, which providers count within output.
gateway_cost_usd_total counter provider, model, and price_source with cost_price_source_label The request cost in USD when its valuation is known (usage_valuation, a price, proven usage, a successful answer); the value is the one sent in the cost header. An unknown cost is never counted. Prometheus stores a float: the ledger stays the exact record. With the operator flag cost_price_source_label (off by default) each series also says where the price came from: catalog (an automatic price catalog), price_book (an operator’s price book entry where no automatic price existed) or price_book_override (a price book entry that replaced an available automatic price). Turning the flag on starts new series with the label beside the old unlabelled ones, which stop growing; sum by provider, model to read both.
gateway_inference_requests_total counter provider, model, streaming (true, false), outcome (ok, error, canceled) With inference_request_metrics: every finished inference request once, by the configured provider and model that served it. canceled is a client that went away (499, or a stream it stopped reading) and is not an error; error is any other failure, an error status or an answer the provider or the gateway cut short. A retry or fallback inside the request is one request here (attempts are in gateway_upstream_attempts_total).
gateway_pricing_coverage_total counter provider, model, status (complete, partial, inconsistent, unavailable) With pricing_coverage: every answered call (a 2xx answer) once, by whether its cost could be computed from the same valuation the ledger records. complete: a known cost, a valid zero included (an exact-cache hit). partial: the final usage did not arrive whole, or a cached-token category has no published price (partial_counters, usage_unreported, cache_usage_unreported, cache_price_unavailable, image_output_split_unreported, service_tier_unreported), or the durable outcome of the call is not settled yet. inconsistent: the reported counters are negative or do not add up (cached tokens above the input), or a known amount does not equal its parts. unavailable: no price applies (no rate, an unsupported rate, a model the rate does not name). The status never changes the cost: it describes it. A failed call is not counted. The same status of each stored call is the pricing_status dimension of /analytics/query. Coverage of a window is sum by (status) (increase(gateway_pricing_coverage_total[1h])); a window without samples is unknown coverage, not full coverage.
gateway_inference_request_duration_seconds histogram as above With inference_request_metrics: the end-to-end duration of the same requests, so a streamed answer’s latency is read apart from a buffered one’s.
gateway_time_to_first_token_seconds histogram provider, model Streamed answers with status below 400: from the request start to the first body byte the client received.
gateway_provider_latency_seconds histogram provider, model, result Each provider attempt, like the attempt span: from the attempt start (destination admission included) until the response headers or a transport failure. result is the attempt outcome of gateway_upstream_attempts_total.
gateway_circuit_breaker_state gauge provider, model (upstream model), state (closed, open, half_open) Number of circuit-breaker destinations of this replica in each state, read at collection. Present with circuit_breaker; destinations appear after their first attempt and reset when the configuration changes.
gateway_fallbacks_total counter model, kind (target, context_window, content_policy) target: each move to another target of the same model during a request. context_window/content_policy: each time a semantic fallback is dispatched.
gateway_budget_remaining_usd gauge policy Remaining USD of each configured budget policy (budget_usd) in its current period, with budget_limits and a database. Per-end-user policies are not exported. Read from the shared ledger once per collection, bounded by storage.database.acquire_timeout; a failed read emits no series. Every replica reports the same value: aggregate with max, not sum.

Cardinality bound. provider and model are configured IDs: the provider ID and the model ID that served the request (the canonical model, not a client-sent alias). Any other value, such as a name that is not in the current configuration, is recorded as other. type, result, state and kind are fixed words, policy a configured policy ID. gateway_tokens_total, gateway_cost_usd_total, gateway_time_to_first_token_seconds, gateway_provider_latency_seconds, gateway_provider_errors_total and gateway_fallbacks_total also hold at most 2,048 label sets each per process (the breaker gauge is bounded by the breaker’s own 4,096 destinations, the budget gauge by the configured policies); past that, new label sets are recorded with provider and model set to other, so a configuration that changes many times cannot grow a family without bound. A series for a provider or model you remove stays until the process restarts, like the other Prometheus counters. No key ID, user, team, request ID, end user, tag or other client-controlled value is a label.

Examples:

# Output tokens per second by model, the autoscaling signal
sum by (model) (rate(gateway_tokens_total{type="output"}[2m]))
# p95 time to first token
histogram_quantile(0.95, sum by (le, model) (rate(gateway_time_to_first_token_seconds_bucket[5m])))
# Spend per hour by provider
sum by (provider) (increase(gateway_cost_usd_total[1h]))
# Share of spend valued at a price book entry (cost_price_source_label)
sum(increase(gateway_cost_usd_total{price_source=~"price_book.*"}[1h])) / sum(increase(gateway_cost_usd_total{price_source!=""}[1h]))
# Error rate without the clients that gave up (inference_request_metrics)
sum(rate(gateway_inference_requests_total{outcome="error"}[5m])) / sum(rate(gateway_inference_requests_total{outcome!="canceled"}[5m]))
# p95 of streamed requests
histogram_quantile(0.95, sum by (le) (rate(gateway_inference_request_duration_seconds_bucket{streaming="true"}[5m])))
# Open circuits
sum by (provider, model) (gateway_circuit_breaker_state{state="open"}) > 0
# Remaining budget (same value on every replica)
max by (policy) (gateway_budget_remaining_usd)

The exact cache of embeddings and moderations (T057). Each family appears once the first matching event happens, except the gauge, which is always there. No alias, key, team or backend address is a label: every label value is one of the fixed words below.

Series Type Labels Measured
gateway_exact_cache_lookups_total counter result (hit, miss, bypass), reason Each embeddings or moderations request, once. hit and miss carry reason="none"; a bypass (the cache was not consulted, no X-Gateway-Cache header on the answer) carries why, below. Other operations are not counted.
gateway_exact_cache_stores_total counter result (stored, skipped, failed), reason What became of each miss’s answer: kept (stored, reason="none"), not kept by rule (skipped, with the reason) or refused by the shared backend (failed, reason="backend_error"). A miss whose provider call failed before any answer adds nothing.
gateway_cache_backend_operation_duration_seconds histogram operation (validate, generation, purge, get, set), result (ok, error) Each call to the shared cache backend (Redis or Memcached, distributed_exact_cache): the boot and console checks (validate), reading or moving the shared generation marker (generation, purge), the lookup (get) and the write (set). Buckets from 0.5 ms to 2.5 s; _count is the number of calls.
gateway_cache_backend_errors_total counter operation The calls above that failed (timeout, refused connection, TLS, protocol). A failed lookup is a bypass with reason="backend_error": the request goes to the provider, never fails because of the cache.
gateway_exact_cache_backend gauge backend (memory, distributed) 1 for the cache that serves: memory (per replica) or distributed (the shared backend). Both 0 when exact_cache is off, the backend configuration is invalid, or a shared backend is configured while distributed_exact_cache is off, which bypasses every lookup.

Bypass reasons (gateway_exact_cache_lookups_total{result="bypass"}):

reason Meaning
feature_disabled exact_cache is off.
distributed_disabled A shared backend is configured and distributed_exact_cache is off: the gateway does not fall back to memory, so nothing is cached. The boot log warns with exact_cache_bypassed (reason: distributed_disabled).
backend_unavailable The cache backend configuration is invalid (the boot check refused it).
provider_network The alias’s provider network policy is not ready (provider_network).
alias_disabled The alias has no cache policy, or cache.enabled: false.
not_requested The request did not send exactly one X-Gateway-Cache: allow.
client_directive The request sent Cache-Control, Pragma, Cookie or Range.
uncacheable_request The alias has more than one target, the body is not a JSON object, asks for a stream, or (moderations) names a remote image.
no_key No authenticated key (the cache key needs one).
canceled The client left before the lookup finished.
config_changed A new configuration was published during the lookup.
backend_error A shared-backend call failed; see gateway_cache_backend_errors_total.
invalid_entry The shared backend returned an entry the gateway does not trust (another provider, an invalid body): it is not served.

Skipped-store reasons (gateway_exact_cache_stores_total{result="skipped"}): response_status (not a 200), too_large (over cache_backend.max_response_bytes, or the entry over the byte budget), response_vary (Vary: * or a Vary naming a header the key does not cover; see what is stored), response_headers (Cache-Control, Pragma, an authentication challenge, Authorization, Cookie, Set-Cookie2, Content-Encoding, Content-Range or trailers), content_type (not JSON), incomplete (cut short, a length mismatch, the client left), invalid_body (no data or results, or an error field) and config_changed.

# Hit ratio of the exact cache over the fleet
sum(rate(gateway_exact_cache_lookups_total{result="hit"}[15m]))
/ sum(rate(gateway_exact_cache_lookups_total{result=~"hit|miss"}[15m]))
# Why answers are not kept
sum by (reason) (increase(gateway_exact_cache_stores_total{result="skipped"}[1h]))
# p99 of the shared backend's lookups
histogram_quantile(0.99, sum by (le) (rate(gateway_cache_backend_operation_duration_seconds_bucket{operation="get"}[5m])))

A cache whose answers are all miss while stores_total{result="skipped"} grows is refusing what the provider returns; the GatewayExactCacheNotStoring alert fires on it.

With control_snapshot_metrics (off by default), each replica also exports how current its control configuration is (T168):

Series Type Meaning
gateway_control_version gauge The control configuration version this replica applies
gateway_control_refresh_age_seconds gauge Seconds since its last successful refresh; absent until the first one
gateway_control_refresh_failures_total counter Refreshes that failed; the replica keeps serving its last valid snapshot. A refresh cut short by its own request’s cancellation or deadline is not counted

Replicas normally converge within one refresh interval. Useful queries: max(gateway_control_version) - min(gateway_control_version) (divergence across replicas), max(gateway_control_refresh_age_seconds) (the most stale replica) and increase(gateway_control_refresh_failures_total[10m]). The values describe what this replica applied, not what others did; no label carries request or tenant data.

A self-hosted model server knows things the gateway cannot see from outside: how many requests wait in its queue, how full its cache is, how long its own first token takes. vLLM and llama.cpp publish them as Prometheus metrics. With provider_metrics_scrape on, the gateway reads them from each connection you opt in and shows them in /metrics, and through it in OTLP metrics, next to its own series for the same connection.

The replicas of a local inference pool need no setting here: llama.cpp and vLLM replicas declare /metrics themselves, and the pool screen reads their running and waiting requests from the scrape.

Turn it on in this order:

  1. Give each model server its own connection (providers[]). Two replicas of one model are two connections, and the connection ID is how you tell their series apart.
  2. Set metrics_path on each one, in the YAML or in the console’s provider form (Model server metrics path). For vLLM and llama.cpp it is /metrics.
  3. Turn the flag on. It is an operator flag, off by default, and applies without a restart.
features:
provider_metrics_scrape: true
providers:
- {id: vr1, protocol: openai, base_url: http://10.0.0.5:8001/v1, api_key_env: LOCAL_PROVIDER_KEY, metrics_path: /metrics}
- {id: vr2, protocol: openai, base_url: http://10.0.0.5:8002/v1, api_key_env: LOCAL_PROVIDER_KEY, metrics_path: /metrics}
provider_metrics: # every field optional; read on each cycle, no restart
interval: 15s
timeout: 2s
max_series: 500
allow: ["vllm:", "llamacpp:"]

What you get in /metrics, with the server’s own names and the connection as the provider label:

# TYPE vllm:num_requests_running gauge
vllm:num_requests_running{provider="vr1",model_name="qwen05"} 3
vllm:num_requests_running{provider="vr2",model_name="qwen05"} 5
gateway_provider_metrics_up{provider="vr1"} 1
gateway_provider_metrics_series{provider="vr1"} 349
Setting Default Bounds What it does
providers[].metrics_path empty (not scraped) an absolute path of at most 256 letters, digits and ._~/-; no . or .. segment, no // The path of the server’s metrics. It is read on the host of base_url (scheme, host and port; the /v1 of base_url is left out) and never on another host. At most 64 connections may set it
providers[].metrics_credential false needs metrics_path, bearer authentication with one static secret and no credential pool Sends the connection’s bearer secret with the scrape. Use it only for a server that protects its metrics with its key (llama.cpp started with an API key does; vLLM does not)
provider_metrics.interval 15s 5s to 5m How often each connection is scraped
provider_metrics.timeout 2s 100ms to 30s, at most interval The bound of one scrape
provider_metrics.max_series 500 50 to 5,000 The most series kept from one connection. A family that does not fit is dropped whole, so a histogram never loses some of its buckets
provider_metrics.allow ["vllm:", "llamacpp:"] 1 to 16 prefixes of 1 to 64 metric name characters; a prefix of gateway_ is refused Only families whose name starts with one of these are kept; the rest of what the server publishes (runtime and process metrics) is ignored

The gateway’s own series about the scrape, one per connection:

Series Type Meaning
gateway_provider_metrics_up{provider} gauge 1 while the last scrape succeeded, 0 after a failed one
gateway_provider_metrics_series{provider} gauge Series kept from the last scrape
gateway_provider_metrics_scrapes_total{provider,result} counter Scrapes by result: ok or failed
gateway_provider_metrics_dropped_series_total{provider} counter Series left out for a bound: the series limit, more than 16 labels, an invalid label name, a label value over 128 bytes or with a control character, a repeated series or a value that is not a number

How it behaves:

  • A failed scrape drops that connection’s series. A queue length from a minute ago is worse than none: alert on gateway_provider_metrics_up == 0 instead. The gateway logs provider_metrics_scrape_failed once when a connection starts failing, with a fixed reason (transport, timeout, status, too_large, redirect, credential, invalid_answer or empty_answer), and the provider card in the console shows the same state.
  • empty_answer means the path answered but nothing matched allow: most often the wrong path or a server with another metric prefix. Add the prefix to allow.
  • Only counters, gauges and histograms are kept. A label called provider on the server’s side becomes exported_provider. A series with a label value over 128 bytes or with a control character, and a series the server repeats, is dropped and counted, never altered. The answer is read up to 1 MiB; a larger one fails the scrape.
  • The scrape sends nothing of a client’s request, follows no redirect and goes through the connection’s network profile (proxy, CA, mutual TLS). The scraped values are never logged and are not used for routing, health checks, usage or cost.
  • Each gateway replica scrapes on its own. With three replicas, Prometheus sees each model server series three times, told apart by the gateway instance; aggregate with max by (provider) for gauges. Scale the extra series as connections × max_series × replicas.
  • Where to see the settings: the provider card shows the last scrape (Metrics /metrics · 349 series), the Providers page shows the effective provider_metrics values, and GET /api/v1/admin/config returns them as provider_metrics and, per connection, metrics_path, metrics_credential and metrics_scrape. The settings are changed in the YAML; the path and the credential choice also in the console.

Useful queries: sum by (provider) (vllm:num_requests_waiting) (the queue behind each replica), vllm:kv_cache_usage_perc (how full each replica’s cache is) and, for tokens per second while generating, rate(vllm:generation_tokens_total[2m]) / rate(vllm:request_decode_time_seconds_sum[2m]).

deploy/observability/alert-rules.yml holds Prometheus alert rules for the operational failures the gateway can see. The bundled Prometheus (kubectl apply -k deploy/observability) loads them. With the Prometheus Operator, the Helm chart ships the same file as a PrometheusRule when you set serviceMonitor.enabled and serviceMonitor.alertRules (both off by default):

serviceMonitor:
enabled: true
alertRules: true
labels: {release: prometheus} # must match your Prometheus's serviceMonitorSelector and ruleSelector

Every threshold and for below is a default to tune to your traffic, not a measured recommendation. Edit the file (and the chart copy deploy/helm/gateway/files/alert-rules.yml, which the chart check compares byte for byte), then validate it:

Terminal window
docker run --rm --entrypoint promtool -v "$PWD/deploy/observability:/rules:ro" -w /rules \
prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 \
check rules alert-rules.yml
docker run --rm --entrypoint promtool -v "$PWD/deploy/observability:/rules:ro" -w /rules \
prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 \
test rules alert-rules-test.yml

alert-rules-test.yml checks that each rule fires after its for and not on a short blip or at low traffic.

Alert Expression (summary) for Severity
GatewayCircuitOpen gateway_circuit_breaker_state{state="open"} above 0 by provider and model 1m critical
GatewayProviderErrorRateHigh provider errors / attempts (without client cancellations) above 0.2 over 5m, with at least 20 attempts in the window 10m critical
GatewayProviderSlow p95 of gateway_provider_latency_seconds{result="response"} above 30 s over 10m, with at least 20 answers 15m warning
GatewayDatabaseDown gateway_database_up == 0 on a replica 2m critical
GatewayUsageWriteFailures any gateway_usage_write_failures_total increase in 10m 0m critical
GatewaySecretManagerFailing gateway_secret_manager_failing_secrets > 0 15m warning
GatewayTelemetryDropping gateway_otel_dropped_total rising in every 5m window, by signal 15m warning
GatewayExactCacheNotStoring at least 20 answers of a miss skipped or failed to store over 30m (provider errors left out), and none stored 15m warning

Notes on reading them:

  • Circuit open sums the replicas that report the destination open. A provider that keeps failing passes through half_open, which resets for; the error-rate alert covers that case.
  • Provider slow measures until the response headers. A non-streaming answer arrives whole, so long generations raise it: raise the threshold for reasoning models or watch time to first token instead.
  • Usage write failures fire on a single failure: the request was served and its usage row (spend, quota, analytics) is missing.
  • Secret manager: a failing secret keeps serving its last good value, so requests show nothing until the credential rotates.
  • Exact cache not storing means every lookup is a miss: the answers come back but a rule refuses them. The reason of gateway_exact_cache_stores_total names the rule. Distinct inputs do not fire it (their answers are still stored), and neither does a provider outage (response_status is left out).

deploy/observability/slo-rules.yml (T168) adds an availability objective and alerts on how fast its error budget burns. It is optional and off by default: with the Helm chart set serviceMonitor.sloRules: true (next to serviceMonitor.enabled) for a second PrometheusRule; with the bundled Prometheus, uncomment /etc/prometheus/slo-rules.yml in deploy/observability/prometheus.yml (the file is already in its ConfigMap).

serviceMonitor:
enabled: true
sloRules: true
labels: {release: prometheus}
  • SLI: the share of inference requests answered without a 5xx, from gateway_http_requests_total summed over every replica. Inference routes are Chat and text completions, Responses, Messages, embeddings, moderations, rerank, images, audio, video generations, OCR, Decisions, System One and Gemini /v1beta/models/.... Catalogs, files, batches, vector stores, MCP and administrative routes are left out, so cheap reads cannot dilute the ratio. A 429 or another 4xx counts as a request, not an error: it is the gateway applying a limit, not failing.
  • Objective: 99.5% (error budget 0.005). To change it, replace 0.005 in the two alerts; the recording rules do not depend on it.
  • Recording rules: gateway:inference_requests:rate<w>, gateway:inference_errors:rate<w> and gateway:inference_error_ratio:rate<w> for the windows 5m, 30m, 1h and 6h. With no traffic in a window the ratio has no value, so an idle gateway neither fires nor counts as healthy.
Alert Fires when for Severity
GatewayInferenceErrorBudgetFastBurn the 5m and the 1h error ratios are both above 14.4 × 0.005 (7.2%): a 30-day budget gone in about two days 2m critical
GatewayInferenceErrorBudgetSlowBurn the 30m and the 6h error ratios are both above 6 × 0.005 (3%): the budget gone in five days 15m warning

The long window proves the burn is sustained; the short one clears the alert soon after recovery, and its ratio is the value the alert reports. Both alerts carry slo: inference_availability. Validate after editing, the same way as the alert rules (check rules slo-rules.yml, test rules slo-rules-test.yml); the chart copy deploy/helm/gateway/files/slo-rules.yml is compared byte for byte. These rules measure what the gateway answered; they do not certify an objective for a deployment, which stays the operator’s to set and review.

With features.operational_alerts (off by default; requires alert_channels), each replica also sends the same conditions to the alert channels that subscribe to them, on state transitions only. See operational events.

The otlp_metrics boot flag (off by default, operator control, restart required) pushes the same series /metrics serves to an OTLP/HTTP receiver, such as an OpenTelemetry Collector. It does not need metrics_endpoint, and it changes nothing in /metrics.

features:
otlp_metrics: true
telemetry:
otlp:
protocol: http/protobuf # shared with logs and traces
metrics_endpoint: http://collector:4318/v1/metrics
metrics_interval: 60s
metrics_timeout: 10s
Field Default Bounds Environment override
telemetry.otlp.metrics_endpoint http://127.0.0.1:4318/v1/metrics Same rules as the other endpoints: absolute http/https, valid host and port, no user info, query or fragment, up to 2,048 bytes OTEL_EXPORTER_OTLP_METRICS_ENDPOINT
telemetry.otlp.metrics_interval 60s 1s to 1h OTEL_METRIC_EXPORT_INTERVAL (milliseconds)
telemetry.otlp.metrics_timeout 10s, or the interval when that is shorter 100ms to 1m; an explicit value must not exceed the interval OTEL_METRIC_EXPORT_TIMEOUT (milliseconds)
telemetry.otlp.protocol http/protobuf http/protobuf or http/json OTEL_EXPORTER_OTLP_PROTOCOL

The values are captured once at startup; the source of the endpoint (default, yaml, environment) appears in the telemetry_boot log and in the infrastructure view of the console, never the URL. YAML values are validated even with the flag off; an invalid value with the flag on stops the boot with the setting named.

What the receiver gets: one ExportMetricsServiceRequest per interval with resource service.name=ai-gateway and scope ai-gateway. Each Prometheus family keeps its name and labels (as attributes): counters become cumulative monotonic sums, gauges stay gauges and histograms become cumulative explicit-bucket histograms with the same bounds. Units come from the name (s, By, {token}, USD). Start time is the process start.

Behavior and failure:

  • One background worker collects a snapshot and sends it; nothing waits on it in the request path. There is no queue: every value is cumulative, so a send still running when the next interval comes skips that interval, and a failed send loses only that snapshot (the next carries the totals).
  • A Collector that is down, slow or rejecting costs only telemetry: the send is abandoned after metrics_timeout, its data points are added to gateway_otel_dropped_total{signal="metrics"}, and one otlp_metrics_export_failed warning (with a fixed reason: unreachable, timeout, status_<code>, never the endpoint) is logged per failure streak, then otlp_metrics_export_recovered when sends succeed again.
  • On shutdown the exporter abandons a send in progress (the final snapshot carries its totals) and sends one last snapshot, bounded by metrics_timeout and at most 2 seconds, before the database closes. The shipped grace (180s) and the Helm cleanup allowance already include those 2 seconds; add them to a shutdown grace period you size yourself.
  • Collection takes the same locks as a /metrics scrape and, like a scrape, pings the database and, with budget_limits, reads budget remainders in one short transaction, each bounded by storage.database.acquire_timeout. Both hold a pool connection while they run, so a very frequent scrape or interval competes with requests for the pool.

The example Collector configuration (deploy/base/collector.yaml and the Helm copy) has a metrics pipeline to the debug exporter. Helm sets OTEL_EXPORTER_OTLP_METRICS_ENDPOINT to its Collector (or gateway.otlpMetricsEndpoint); it is used only when features.otlp_metrics is on in the gateway YAML. Do not scrape /metrics and receive OTLP metrics into the same backend for the same replicas, or every series is counted twice.

On Kubernetes with the Prometheus Operator, the Helm chart can render a ServiceMonitor for /metrics (serviceMonitor.enabled), and its optional NetworkPolicy limits who reaches the port that serves it (networkPolicy.ingressFrom); see operations.

The repository ships a provisioned Grafana dashboard (deploy/observability/gateway.json), a Prometheus that scrapes /metrics every 15 s and a Kustomize overlay to install them. The dashboard follows an SRE investigation: volume → success and p95 → slow route → attempts per provider → heap and goroutines → telemetry losses. You can also point your own Prometheus and Grafana at it.

In the overlay, Prometheus and Grafana use emptyDir: the data is lost when the pod is recreated. The example Collector uses the debug exporter; connect a real backend for historical search.

  • No payload capture: a call cannot be reproduced exactly.
  • The duration in stream metrics is measured at the end of the request; for attempts, up to the provider’s headers.
  • PostgreSQL backup and retention are an operations responsibility; see metadata retention.
  • Queue, circuit, cache, caller concurrency and the inference counters are per replica; sum them across replicas, except gateway_budget_remaining_usd (shared, use max).

Every route below needs a console session or an admin Bearer token, the role’s permission and, for writes, the X-CSRF-Token header; the full contract is in the API reference.

Route What it does
GET /api/v1/admin/agent-runs Lists the coding-agent runs recognized in a time range, most recent first; agent_recognition, logs:read (agent runs)
GET /api/v1/admin/agent-runs/{id} One run as a thread: its model calls, reported tool steps, subagent branches and compaction dividers
GET /api/v1/admin/agent-runs/settings The effective agent_recognition block and the client rules in the order they are tried; config:read
POST /api/v1/admin/log-destinations/{id}/test Queues one synthetic record and flushes the destination now, to see the object written or the failure

Inspect external integration boot policies

Section titled “Inspect external integration boot policies”

The read-only Settings & sources → Inspect session, vector and integration policies section and GET /api/v1/admin/config expose infrastructure.integration_settings to authorized global readers when boot_settings_view is enabled. Existing secret_manager and log_destinations flags still control operational behavior. The summary does not fetch a secret, contact a destination, activate an integration or replace the privileged status/test interfaces.

For the secret manager, the view reports whether a manager was declared, an allowlisted manager kind and the existing secret_manager.refresh_seconds policy (default 300, valid 10–86,400 seconds). It never reports credential names, addresses, namespace/path prefixes, authentication references, or fetched values. “Declared” does not mean authenticated, resolved or healthy.

For log destinations, it reports the declaration count (at most ten) and declaration-ordered entries containing only a known destination type and two existing policies:

YAML parameter per destination Default Existing bound
flush_seconds 10 1–300 seconds
max_batch 500 1–5,000 records

Destination numbers are positions in the loaded list, not IDs or delivery-worker identities. No bucket, endpoint, host, path, credential/environment reference, object name or delivery-health data enters this safe projection. Use the existing authorized destination status for actual delivery counters.

Every scalar includes its default, decoded default/yaml source and rollout requirement. Explicit default or zero values retain YAML origin while zero selects the existing fallback. Programmatic factories without decoded provenance report nullable declaration/value/source fields; they do not invent a configuration source. This metadata inspection preserves existing adapters and network behavior; it is not a new external-service or managed-cloud compatibility certification.

The existing minimum-severity enum, integration refresh and destination batching limits use shared parameter definitions with their actual Go and console consumers. The JSON/OTLP filtering and captured startup sources retain their existing behavior. Per-signal OTLP destinations, secret references and provider-specific connection schemas stay private; a definition or configured summary does not prove delivery. Boot changes require rollout, and the existing view and authorization controls still apply.

Enable features.log_destination_management (default false) with log_destinations, ui and PostgreSQL. Settings & sources → Destination configuration and GET, PUT, DELETE /api/v1/admin/log-destination-policy share a versioned full-list policy and actor/request-ID audit. destinations:read belongs to global admin/viewer; destinations:manage belongs only to global admin. Neither flag nor template grants permission. Existing status and synthetic-test permissions remain separate.

Connection trust belongs to the operator’s YAML declarations. A template binds type, target, bucket/account, cloud identity/profile and credential environment references. Runtime requests cannot select another endpoint, reference a new environment variable, or rebind infrastructure identity. The API returns only template ID, one of the six existing types and a sanitized target label; credential references, query strings and secret values remain private. Declare new connection trust in YAML and roll out the gateway before it can be selected in this editor. This restart boundary is explicit; the editor does not provision infrastructure or offer arbitrary secret/endpoint CRUD.

For example, declare an approved connection:

features:
ui: true
log_destinations: true
log_destination_management: true
log_destinations:
- id: approved_http
type: http
endpoint: https://logs.example/ingest
auth_header_env: LOG_DESTINATION_AUTH
flush_seconds: 10
max_batch: 500

The operator supplies LOG_DESTINATION_AUTH through the deployment’s Secret/environment. The web interface never receives its value or variable name. S3, GCS, Azure Blob, Langfuse and Datadog use their existing YAML connection contracts in the same way. An instance can select any approved template, including a second instance of one template; doing so intentionally exports an additional copy.

PUT replaces the whole list, with exactly six fields per row:

{"version":4,"destinations":[{"id":"audit_copy","template_id":"approved_http","flush_seconds":10,"max_batch":500,"prefix":"runtime/","service":"ai-gateway"}]}

Use the current version and an ID from GET’s template list. Up to ten distinct destination IDs are allowed. Batching zero chooses compiled defaults (10 seconds and 500 records), not a template’s custom batching. Prefix and service are exact replacements, including empty strings. Prefix follows the existing relative-path contract (up to 200 allowed characters, no leading slash or ..); managed service labels are at most 256 UTF-8 bytes. Legacy longer YAML labels remain readable and unchanged, but must be shortened before a managed save. Unknown fields—including endpoint, type, profile, credential and *_env—are refused. Duplicate fields, nulls, aliases and invalid types are also refused.

[] is an explicit policy disabling every destination. DELETE accepts only {"version":4} and restores the YAML list; a missing override returns 404. GET separates raw override from normalized effective rows, source, applies_to:"new_completions", restart_required:false and trust_requires_restart:true. The startup inspector remains immutable and count/type/tuning-only. A 409 preserves the draft; reload, review and explicitly adopt the current version before saving. A known access denial cannot be undone by a viewer-only reload. Database/corrupt-snapshot failures retain the previous valid policy; 503 configuration_sync_pending requires reading current state before retrying a possibly committed write.

Each replica reconciles after validating/publishing its snapshot. The global configuration lock is released before any worker cancellation/reap wait. A management refresh can wait for bounded cancellation of an older retired generation while holding only the generation mutex; request intake does not wait for that mutex or network delivery. New completions use the newest available generation, including requests that started before delivery was enabled. A batch accepted by an older worker drains to its old target/credential; removing an instance cannot recall accepted work. Unchanged declarations keep their workers/counters. Replicas converge asynchronously.

While log_destination_management is enabled, at most the current and one retired generation are retained (at most twenty workers for ten destinations). If another replacement overtakes draining workers, older retired work can be cancelled and lost. In this managed mode, intake never waits for replacement or delivery during a handoff and may drop metadata; the status API’s dropped_during_reconfiguration counter and console report that process-local loss. Queue limits count records, not a guaranteed memory/RSS ceiling. Each generation has its own counters; replacing one does not produce a durable lifetime total. Missing credentials hold a bounded batch with backoff; shutdown/retirement still has a finite owner and can lose pending work.

Disabling management restores the YAML list and historical lock/drain behavior, without the opt-in handoff-drop/obsolete-cancellation policy, but retains the dormant override for re-enable. Disabling delivery retires workers; re-enable creates the current effective generation. Restart reuses the persisted policy and starts new workers; memory queues are not recovered. A failed or slow destination does not delay inference or another destination.

Per-record request/trace IDs remain intact. Synthetic tests use the triggering action’s IDs. Batch calls propagate a derived request ID and W3C context anchored to the first available request span in the batch, before cloud signing; other records keep their own IDs in the batch. Unknown parentage is not fabricated. No prompt, response or credential is exported by this metadata path.

Migration99 stores only nonsecret template IDs and tuning. Back up and roll out all replicas before enabling management. Old binaries refuse the newer schema on startup, and schema downgrade is unsupported. A saved policy referring to a template removed in a later YAML rollout is invalid: update/revert that policy before removing its template. Upgrade and recovery.

client_ip_logging defaults off and requires the boot source_ip_controls profile. It adds only a verified canonical client_ip to structured stdout request records and client.address to OTLP; raw forwarding chains and IP metric labels are excluded. Private source remains available for authorization after collection opt-out, while a fresh request/internal boundary does not inherit old recording consent. Existing peer diagnostics and configured CIDRs are distinct. This does not add an IP field/filter to SQL log history, UsageEvent, receipts or the financial ledger; external collectors own retention. Persisted addresses with their own retention are the separate client_source_metadata profile (T033.003). See configuration and privacy.

Qualified weighted Chat dispatch may report finite configured provider/credential IDs with the existing request/trace context for selection and cooldown transitions. Do not record values, refs, ciphertext, fingerprints or provider payloads. Cooldown signals come only from qualified weighted dispatch response headers; primary/native/catalog calls are outside that monitor. An exhausted pool is not-sent availability, not a provider breaker failure or a paid attempt. The configured console policy is distinct from local observation and fleet health; scope and recovery describe cold restarts and generation fencing.

m7gtw[email protected]