Prometheus metrics
Prometheus metrics let the dashboards and alerts you already run for other services cover model traffic too. The gateway publishes counters, gauges and histograms in the Prometheus text format on /metrics, so you can graph requests, tokens, spend, latency and failures per team, key and model, and alert on them. Prometheus metrics are free on every Spanway gateway.
A real-world scenario
An operations team already watches every service in Grafana. They add the gateway as a scrape target and build a panel of spend per team and a panel of failed provider calls per model. When a provider starts failing at 2 a.m., the existing on-call alert fires on spanway_llm_api_failed_requests_metric the same way it does for any other service, and the team sees which model and which provider is affected before users notice.
Turn it on
Add the prometheus callback in the config file and restart. The route is mounted at startup, which is why it cannot be switched on from the Admin UI. The Logging & Alerts page shows it as a config file destination with an On or Off badge.
-
Add the callback to the config file and restart the gateway:
spanway_settings:callbacks: ["prometheus"] -
Create a key for the scraper, for example in the Admin UI under Virtual Keys with + Create New Key, or reuse the master key for a first test.
-
Read the metrics once by hand:
curl http://localhost:4000/metrics \-H "Authorization: Bearer $SPANWAY_API_KEY"Expected result: a text document that starts with
# HELPand# TYPElines and contains metric names starting withspanway_, for examplespanway_proxy_total_requests_metric. Send one chat request and read it again, and the counter for that key and model goes up by one./metricsis a Prometheus scrape endpoint in the text format, so it is not part of the published OpenAPI reference. -
Point your Prometheus server at the route:
scrape_configs:- job_name: spanwaymetrics_path: /metricsauthorization:credentials: sk-metrics-readerstatic_configs:- targets: ["spanway:4000"] -
In the Admin UI, open Settings, then Logging & Alerts, and check that Prometheus metrics under Set in the config file shows On.
/metrics needs a key by default. Any valid virtual key or the master key works, sent the same way as for any other route, and a request without one gets 401. To let a scraper read it without a key, set require_auth_for_metrics_endpoint: false under spanway_settings, and only do that when the route is not reachable from outside your network.
With the Docker Compose file
The example docker-compose.yml starts Prometheus next to the gateway, and its prometheus.yml sends a key with every scrape, read from a file named prometheus_scrape_key next to the compose file. Before docker compose up
- add
callbacks: ["prometheus"]underspanway_settingsin the gateway's config file and mount it as the compose file's comments show, because the compose gateway has no/metricsroute without it, - create a virtual key for the scraper and save only the key in
prometheus_scrape_key, for exampleprintf '%s' "$SCRAPER_KEY" > prometheus_scrape_key.
Without the file every scrape gets 401, and Prometheus shows the target as down on its Status, Targets page.
A separate metrics port
With more than one worker the gateway keeps metrics in a shared directory, PROMETHEUS_MULTIPROC_DIR, created under the temp directory and emptied at startup. --prometheus_metrics_port 4001 (or PROMETHEUS_METRICS_PORT) also serves those metrics from a small separate process on that port, which must differ from --port. That port has no key check, so keep it off public ingress. The same server can run as a sidecar that shares the directory, with spanway-container metrics-server --host 0.0.0.0 --port 4001, and it answers /health too.
What is measured
Every metric name starts with spanway_. Most request metrics carry end_user, hashed_api_key, api_key_alias, team, team_alias, user, requested_model, model_id and api_provider, plus org_id and org_alias.
| Family | Metrics |
|---|---|
| Requests | spanway_proxy_total_requests_metric, spanway_proxy_failed_requests_metric, spanway_requests_metric, spanway_llm_api_failed_requests_metric, spanway_callback_logging_failures_metric |
| Tokens | spanway_total_tokens_metric, spanway_input_tokens_metric, spanway_output_tokens_metric, cached, cache creation, reasoning and audio token counters |
| Spend | spanway_spend_metric, spanway_zero_cost_requests_total, spanway_spend_capture_rate, spanway_provider_remaining_budget_metric |
| Latency | spanway_request_total_latency_metric, spanway_llm_api_latency_metric, spanway_llm_api_time_to_first_token_metric, spanway_overhead_latency_metric, spanway_request_queue_time_seconds |
| Budgets | spanway_budget_tier_shifts_total for budget tier shifts, and remaining budget, max budget and hours left for teams, organizations, keys, users and end users. They are updated when a request is made with that key, team or user. With prometheus_initialize_budget_metrics: true they are also refreshed for every key and team every 5 minutes (PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES) |
| Rate limits | Remaining requests and tokens per key and model and per deployment, and allowed and used limits per key, team and project |
| Deployments | spanway_deployment_state, spanway_deployment_cooled_down, spanway_deployment_rate_limited_responses (HTTP 429 answers a provider returned, per deployment), success and failure responses, and successful and failed fallbacks. Latency and time to first token per deployment come from spanway_llm_api_latency_metric and spanway_llm_api_time_to_first_token_metric by model_id, see deployment speed |
| Guardrails | spanway_guardrail_latency_seconds, spanway_guardrail_requests_total, spanway_guardrail_errors_total by guardrail and hook |
| Cache and MCP | Cache hits, misses and cached tokens, spanway_mcp_tool_calls_total with its spend, and spanway_agent_credential_uses_total for agents' stored credentials |
| Logging pipeline | spanway_logging_queue_depth, spanway_logging_queue_capacity, spanway_logging_degraded, spanway_logging_records_dropped_total, spanway_logging_records_sampled_out_total, spanway_logging_degraded_episodes_total, refreshed every 10 seconds, see logging under load |
| Data policies | spanway_code_traffic_requests_total by signal_kind (client, route, header, tag, content) and outcome (routed or rejected), see code traffic |
The full metric list below names every metric with its type.
Admission control
These come from admission control and stay at 0 while it is off. When PROMETHEUS_MULTIPROC_DIR is set they are summed across the worker processes of an instance.
| Metric | Type | Labels | Meaning |
|---|---|---|---|
spanway_admission_admitted_requests | gauge | none | Requests holding a worker slot now. |
spanway_admission_queued_requests | gauge | none | Requests waiting for a slot now. |
spanway_admission_rejected_requests_total | counter | reason (queue_full or queue_timeout) | Requests refused with 503 since start. |
Public feed rate limit
This comes from the public feed rate limit.
| Metric | Type | Labels | Meaning |
|---|---|---|---|
spanway_public_route_throttled_requests_total | counter | none | Requests to the public feeds answered 429 since start because one address went over the per-minute limit. |
Retention cleanup
These come from the retention cleanup job. The table label is the cleaned table, such as Spanway_SpendLogs.
| Metric | Type | Labels | Meaning |
|---|---|---|---|
spanway_spend_log_cleanup_runs_total | counter | outcome (completed, budget_exhausted, batch_cap_reached, aborted, skipped_disabled, skipped_locked) | Cleanup runs and why each ended. |
spanway_spend_log_cleanup_rows_deleted_total | counter | table | Rows deleted. |
spanway_spend_log_cleanup_rows_remaining | gauge | table | Expired rows still waiting, counted only up to a cap, so the cap value means at least that many. |
spanway_spend_log_cleanup_batch_failures_total | counter | table | Delete batches that failed. |
spanway_spend_log_cleanup_batch_duration_seconds | histogram | table | How long each delete batch took. |
Spanway Cloud billing safety
These come from Cloud billing safety and stay at 0 while Cloud billing works. Any increase means tenants are being refused or overage is being held back, so alert on it.
| Metric | Type | Labels | Meaning |
|---|---|---|---|
spanway_cloud_billing_refusals_total | counter | reason (invalid_config) | Cloud tenant requests refused with 503 cloud_billing_unavailable because the cloud block is invalid. |
spanway_cloud_settlement_failures_total | counter | reason (invalid_config) | Daily credit settlements that did not run. |
spanway_cloud_overage_metering_blocked_total | counter | reason (not_configured, wrong_price, stripe_unavailable) | Stripe overage price checks that held overage back. |
Budget gauges for idle keys and teams
prometheus_initialize_budget_metrics under spanway_settings decides whether budget gauges also cover keys and teams that sent no traffic since the gateway started. It is off by default. Off, a key's or team's remaining budget appears in /metrics after its first request and is updated on each request after that, so a budget alert only covers keys that are in use. On, the gateway reads every key and team from the database every 5 minutes and sets their gauges, so a dashboard shows every budget from startup. The cost is one database read of all keys and teams per interval on one replica, which is noticeable with many thousands of keys. Platform admins who build budget dashboards turn it on. Change the interval with the PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES environment variable.
spanway_settings:
callbacks: ["prometheus"]
prometheus_initialize_budget_metrics: true
Keeping the number of series down
A busy gateway can create many label combinations. These settings under spanway_settings keep that in check.
| Setting | Effect |
|---|---|
prometheus_metrics_config | A list of {group, metrics, include_labels}. Only the metrics listed are recorded, each with only the labels listed. Unknown names stop startup with an error. |
prometheus_exclude_metrics, prometheus_exclude_labels | Drop metrics or labels everywhere. Unknown names stop startup with an error too. |
prometheus_metrics_cleanup_interval_seconds | How often expired series are removed, 60 seconds by default. |
prometheus_end_user_metrics_ttl_seconds, prometheus_end_user_metrics_cleanup_interval_seconds | How long an end_user series lives without updates (3,600 seconds) and how often they are checked (60 seconds). |
prometheus_latency_buckets | A list of bucket bounds in seconds for the latency histograms, replacing the built-in buckets. More buckets mean more series. |
prometheus_metrics_max_series_per_metric | A cap per metric. Past it, counters and histograms add to one series whose labels are all other, so totals stay right, and gauges skip the new label set. |
prometheus_metrics_ttl_seconds | Forget series not updated for that long. It is ignored with more than one worker, where only the cap applies. |
prometheus_end_user_metrics_max_series_per_metric | A separate cap of 10,000 series for metrics with end_user, forgotten after an hour without updates. |
A requested_model the router does not know is recorded as other, so callers cannot add series by inventing model names.
Privacy
Optional labels
These settings under spanway_settings add labels. Each one is off by default, because each one adds series and some add personal data.
| Setting | Default | What turning it on does |
|---|---|---|
prometheus_emit_stream_label | false | Adds stream (True or False) to spanway_proxy_total_requests_metric, so you can tell streaming traffic apart. |
prometheus_emit_input_sequence_length_label | false | Adds a bucketed prompt length label to the request metrics, to see whether long prompts are slower. |
prometheus_emit_rate_limit_labels | false | Adds rate_limit_category and rate_limit_type to spanway_proxy_failed_requests_metric, so a 429 says whether a provider or the gateway limited it. Existing dashboards keep working while it is off. |
prometheus_deployment_and_latency_caller_identity | api_key_alias | Which caller label the deployment and latency metrics carry: api_key_alias, user_email or both. user_email and both put email addresses in your metrics store. An unknown value stops startup. |
prometheus_user_budget_label_include_email_alias | false | Adds user_email and user_alias to the user budget gauges, so a dashboard can name the person. This is personal data. |
custom_prometheus_metadata_labels | [] | Turns the listed request metadata fields into labels, for example metadata.project. Only list fields that never hold personal data or free text. |
custom_prometheus_tags | [] | Turns each listed request tag into a tag_<name> label with true or false. |
enable_end_user_cost_tracking_prometheus_only | unset | Fills the end_user label from the request's user field. |
disable_end_user_cost_tracking_prometheus_only | unset | Leaves end_user empty in metrics even when end user cost tracking is on elsewhere. |
When PROMETHEUS_URL points at your Prometheus server, the gateway also posts a daily fallback summary to its alert channels at 9 a.m. Pacific time. PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS changes the hour.
Labels never hold prompts or responses. They do hold identifiers, which can be personal data: user, user_email, client_ip, user_agent, key aliases and the sha256 hash of a key, never the key itself. prometheus_user_budget_label_include_email_alias, prometheus_deployment_and_latency_caller_identity and custom_prometheus_metadata_labels can add more, see Optional labels. end_user is empty unless enable_end_user_cost_tracking_prometheus_only: true is set. Request tags become labels only for the tags you list in custom_prometheus_tags, with the value true or false. Drop any label you do not want with prometheus_exclude_labels. Your Prometheus server keeps the series under its own retention, and a data subject erasure in Spanway does not reach it.
Errors
| Status | Where | Meaning | Fix |
|---|---|---|---|
401 Unauthorized access to metrics endpoint: ... | GET /metrics | No valid key was sent. The message ends by naming spanway_settings.require_auth_for_metrics_endpoint: false as the way to allow unauthenticated reads. | Give the scraper a virtual key, or set that setting only on a private network. |
| 404 | GET /metrics | The prometheus callback is not in the config file, so the route was never mounted. | Add it to spanway_settings.callbacks and restart. |
Startup stops with Configuration validation failed: and the unknown names | Gateway start | prometheus_metrics_config lists a metric or label the gateway does not have. A table of the valid names is printed above the error. | Fix the name. The full metric list has every valid metric. |
Startup stops with Prometheus exclude configuration validation failed: followed by Invalid metric name in prometheus_exclude_metrics: <name> or Invalid label name in prometheus_exclude_labels: <name> | Gateway start | An exclude list names a metric or label that does not exist. | Fix or remove the name. |
Startup stops with Invalid prometheus_deployment_and_latency_caller_identity=<value>. Accepted values: ... | Gateway start | The caller identity setting has an unknown value. | Use api_key_alias, user_email or both. |
Error: --prometheus_metrics_port must differ from --port | spanway command line | The separate metrics port is the same as the API port. | Pick another port, such as 4001. |
Prometheus metrics server exited with code <n> before serving <host>:<port>; is the port already in use? | spanway command line | The separate metrics process stopped at once, usually because another program uses the port. | Free the port or pick another one. |
Prometheus metrics server did not answer <url> within 30s | spanway command line | The separate metrics process started but never answered. | Check that the host and port are reachable inside the container and that PROMETHEUS_MULTIPROC_DIR is writable. |
| Scrape shows stale or missing series | Prometheus | With several workers, prometheus_metrics_ttl_seconds is ignored and only the series cap applies, or the shared directory was not writable. | Use the separate metrics port or sidecar, and check that PROMETHEUS_MULTIPROC_DIR is writable. |
The same errors are in the error reference.
Logs
| Level | Line | Meaning | Action needed |
|---|---|---|---|
| DEBUG | mounting metrics endpoint | The prometheus callback loaded and /metrics is being mounted at startup. | None. |
| DEBUG | Starting Prometheus Metrics on /metrics (a virtual key or the master key is needed) | The route is mounted and needs a key. It reads (no key needed, require_auth_for_metrics_endpoint is false) when that setting is off. | None. |
| ERROR | One line per unknown metric or label from prometheus_metrics_config | Only logged when the rich package is missing. Otherwise a table of the valid names is printed to the console. Either way startup then stops with Configuration validation failed:. | Fix the name. |
| WARNING | prometheus_metrics_ttl_seconds is ignored while PROMETHEUS_MULTIPROC_DIR is set: ... | With several workers series cannot be forgotten, so only prometheus_metrics_max_series_per_metric limits them. | Set a series cap if you rely on the ttl. |
| WARNING | Error recording ... metric: ... | One metric update failed and was skipped. | None if rare, otherwise check the shared metrics directory. |
The same lines are in the log reference.
Full metric list
Use these names in prometheus_metrics_config and prometheus_exclude_metrics. Counters gain a _total suffix in the scrape output, and histograms gain _bucket, _sum and _count.
| Metric | Type | What it counts |
|---|---|---|
spanway_proxy_total_requests_metric | counter | Requests the gateway answered, by key, team, user and model. |
spanway_proxy_failed_requests_metric | counter | Requests the gateway answered with an error. |
spanway_requests_metric | counter | Requests sent to providers, by deployment. |
spanway_llm_api_failed_requests_metric | counter | Provider calls that failed. |
spanway_callback_logging_failures_metric | counter | Logging destination writes that failed. |
spanway_in_flight_requests | gauge | Requests being handled right now on this worker. |
spanway_total_tokens_metric | counter | Input plus output tokens. |
spanway_input_tokens_metric | counter | Input tokens. |
spanway_output_tokens_metric | counter | Output tokens. |
spanway_input_cached_tokens_metric | counter | Input tokens the provider read from its prompt cache. |
spanway_input_cache_creation_tokens_metric | counter | Input tokens written to the provider's prompt cache. |
spanway_input_audio_tokens_metric | counter | Audio input tokens. |
spanway_output_reasoning_tokens_metric | counter | Reasoning tokens. |
spanway_output_audio_tokens_metric | counter | Audio output tokens. |
spanway_provider_cache_read_input_tokens_metric | counter | Prompt cache reads reported by the provider. |
spanway_provider_cache_creation_input_tokens_metric | counter | Prompt cache writes reported by the provider. |
spanway_images_generated_metric | counter | Images generated. |
spanway_video_duration_seconds_metric | counter | Seconds of video generated. |
spanway_spend_metric | counter | Spend in US dollars. |
spanway_zero_cost_requests_total | counter | Successful requests recorded at zero cost, often a missing price. |
spanway_spend_capture_rate | gauge | Share of requests whose cost was recorded. |
spanway_request_increase_hints_total | counter | Budget and rate limit refusals that carried the request_increase hint, by request_type and target. |
spanway_access_request_expiry_total | counter | Temporary access request raises the expiry job settled, by outcome (restored, kept, failed). |
spanway_skill_scans_total | counter | Skill and plugin uploads skill scanning checked, by subject_type, status and mode. |
spanway_skill_scan_files_total | counter | Files of scanned skills and plugins, by verdict. |
spanway_skill_scan_duration_seconds | histogram | Seconds one skill or plugin scan took, by subject_type. |
spanway_mcp_skill_requests_total | counter | Skills over MCP requests, by method and outcome. |
spanway_mcp_skill_request_duration_seconds | histogram | Seconds a skills over MCP request took, by method. |
spanway_mcp_skill_store_errors_total | counter | Times the skills table could not be read for skills over MCP. |
spanway_workflow_trigger_fires_total | counter | Workflow trigger fires, by kind and status, including fires refused at the inbound route because the sender is not in the access mapping. |
spanway_workflow_trigger_webhook_rejected_total | counter | Inbound trigger deliveries refused before a fire was written, by reason: signature, timestamp, missing_headers, unreadable, rate_limited, too_large or not_json. |
spanway_agent_credential_uses_total | counter | Times the gateway used or refused an agent's stored credential, by kind and outcome. |
spanway_budget_tier_shifts_total | counter | Times a team or organization moved to another budget tier, by scope_type and to_tier. |
spanway_mcp_tool_calls_total | counter | MCP tool calls. |
spanway_mcp_tool_call_spend_metric | counter | Spend on MCP tool calls. |
spanway_request_total_latency_metric | histogram | Seconds from request to full answer. |
spanway_llm_api_latency_metric | histogram | Seconds the provider took. |
spanway_llm_api_time_to_first_token_metric | histogram | Seconds to the first streamed token. |
spanway_overhead_latency_metric | histogram | Seconds the gateway added. |
spanway_overhead_with_guardrails_latency_metric | histogram | Seconds the gateway added including guardrails. |
spanway_deployment_latency_per_output_token | histogram | Seconds per output token, by deployment. |
spanway_request_queue_time_seconds | histogram | Seconds a request waited in the gateway queue. |
spanway_remaining_team_budget_metric | gauge | Team budget left. |
spanway_team_max_budget_metric | gauge | Team budget. |
spanway_team_budget_remaining_hours_metric | gauge | Hours until the team budget resets. |
spanway_team_members_metric | gauge | Members per team. |
spanway_remaining_org_budget_metric | gauge | Organization budget left. |
spanway_org_max_budget_metric | gauge | Organization budget. |
spanway_org_budget_remaining_hours_metric | gauge | Hours until the organization budget resets. |
spanway_remaining_api_key_budget_metric | gauge | Key budget left. |
spanway_api_key_max_budget_metric | gauge | Key budget. |
spanway_api_key_budget_remaining_hours_metric | gauge | Hours until the key budget resets. |
spanway_remaining_user_budget_metric | gauge | User budget left. |
spanway_user_max_budget_metric | gauge | User budget. |
spanway_user_budget_remaining_hours_metric | gauge | Hours until the user budget resets. |
spanway_remaining_customer_budget_metric | gauge | End user budget left. |
spanway_customer_max_budget_metric | gauge | End user budget. |
spanway_customer_budget_remaining_hours_metric | gauge | Hours until the end user budget resets. |
spanway_remaining_requests_metric | gauge | Requests left in the provider's rate limit window, by deployment. |
spanway_remaining_tokens_metric | gauge | Tokens left in the provider's rate limit window, by deployment. |
spanway_remaining_api_key_requests_for_model | gauge | Requests per minute left for a key on a model. |
spanway_remaining_api_key_tokens_for_model | gauge | Tokens per minute left for a key on a model. |
spanway_api_key_rate_limit_allowed_metric | gauge | A key's rate limit. |
spanway_api_key_rate_limit_used_metric | gauge | How much of a key's rate limit is used. |
spanway_team_rate_limit_allowed_metric | gauge | A team's rate limit. |
spanway_team_rate_limit_used_metric | gauge | How much of a team's rate limit is used. |
spanway_project_model_rate_limit_allowed_metric | gauge | A project's rate limit on a model. |
spanway_project_model_rate_limit_used_metric | gauge | How much of a project's rate limit on a model is used. |
spanway_deployment_tpm_limit | gauge | A deployment's tokens per minute limit. |
spanway_deployment_rpm_limit | gauge | A deployment's requests per minute limit. |
spanway_deployment_state | gauge | 0 healthy, 1 partial outage, 2 complete outage. |
spanway_deployment_total_requests | counter | Requests per deployment. |
spanway_deployment_success_responses | counter | Successful answers per deployment. |
spanway_deployment_failure_responses | counter | Failed answers per deployment. |
spanway_deployment_cooled_down | counter | Times a deployment was put in cooldown. |
spanway_deployment_successful_fallbacks | counter | Fallbacks that worked. |
spanway_deployment_failed_fallbacks | counter | Fallbacks that also failed. |
spanway_guardrail_latency_seconds | histogram | Seconds a guardrail took. |
spanway_guardrail_requests_total | counter | Guardrail checks. |
spanway_guardrail_errors_total | counter | Guardrail checks that raised, by guardrail and hook. A guardrail that blocks by raising, such as a 403 from write action alignment, is counted here too. |
spanway_mcp_write_alignment_checks_total | counter | MCP writes the write action alignment guardrail checked, by guardrail, outcome and category. |
spanway_cache_hits_metric | counter | Response cache hits. |
spanway_cache_misses_metric | counter | Response cache misses. |
spanway_cached_tokens_metric | counter | Tokens served from the response cache. |
spanway_code_traffic_requests_total | counter | Code traffic routed or refused by a data policy. |
spanway_managed_file_created_total | counter | Files uploaded through the gateway. |
spanway_managed_file_deleted_total | counter | Files deleted through the gateway. |
spanway_managed_file_size_bytes | gauge | Size of uploaded files. |
spanway_managed_batch_created_total | counter | Batches created through the gateway. |
spanway_managed_batch_duration_seconds | histogram | Seconds a batch took. |
spanway_check_batch_cost_jobs_polled | gauge | Batches the cost job checked in its last run. |
spanway_check_batch_cost_jobs_processed_total | counter | Batches the cost job finished. |
spanway_check_batch_cost_errors_total | counter | Errors in the batch cost job. |
spanway_check_batch_cost_last_run_timestamp | gauge | When the batch cost job last ran. |
spanway_in_memory_spend_update_queue_size | gauge | Spend updates waiting in memory to be written. |
spanway_redis_spend_update_queue_size | gauge | Spend updates waiting in Redis. |
spanway_in_memory_daily_spend_update_queue_size | gauge | Daily spend updates waiting in memory. |
spanway_redis_daily_spend_update_queue_size | gauge | Daily spend updates waiting in Redis. |
spanway_pod_lock_manager_size | gauge | Background job locks this replica holds. |
Request metrics also carry project_id, project_alias, user_alias, status_code, route, model_group and service_tier where they apply, and stream and input_sequence_length when those labels are turned on.
Related
- Logging for the other destinations.
- Alerting for alerts the gateway sends itself.
- Logging under load for the logging pipeline metrics.
- Spend capture rate for the
spanway_spend_capture_rategauge. - Production settings for running several workers.
- Error reference and log reference.