Skip to main content

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.

  1. Add the callback to the config file and restart the gateway:

    spanway_settings:
    callbacks: ["prometheus"]
  2. 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.

  3. 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 # HELP and # TYPE lines and contains metric names starting with spanway_, for example spanway_proxy_total_requests_metric. Send one chat request and read it again, and the counter for that key and model goes up by one. /metrics is a Prometheus scrape endpoint in the text format, so it is not part of the published OpenAPI reference.

  4. Point your Prometheus server at the route:

    scrape_configs:
    - job_name: spanway
    metrics_path: /metrics
    authorization:
    credentials: sk-metrics-reader
    static_configs:
    - targets: ["spanway:4000"]
  5. 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

  1. add callbacks: ["prometheus"] under spanway_settings in the gateway's config file and mount it as the compose file's comments show, because the compose gateway has no /metrics route without it,
  2. create a virtual key for the scraper and save only the key in prometheus_scrape_key, for example printf '%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.

FamilyMetrics
Requestsspanway_proxy_total_requests_metric, spanway_proxy_failed_requests_metric, spanway_requests_metric, spanway_llm_api_failed_requests_metric, spanway_callback_logging_failures_metric
Tokensspanway_total_tokens_metric, spanway_input_tokens_metric, spanway_output_tokens_metric, cached, cache creation, reasoning and audio token counters
Spendspanway_spend_metric, spanway_zero_cost_requests_total, spanway_spend_capture_rate, spanway_provider_remaining_budget_metric
Latencyspanway_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
Budgetsspanway_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 limitsRemaining requests and tokens per key and model and per deployment, and allowed and used limits per key, team and project
Deploymentsspanway_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
Guardrailsspanway_guardrail_latency_seconds, spanway_guardrail_requests_total, spanway_guardrail_errors_total by guardrail and hook
Cache and MCPCache hits, misses and cached tokens, spanway_mcp_tool_calls_total with its spend, and spanway_agent_credential_uses_total for agents' stored credentials
Logging pipelinespanway_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 policiesspanway_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.

MetricTypeLabelsMeaning
spanway_admission_admitted_requestsgaugenoneRequests holding a worker slot now.
spanway_admission_queued_requestsgaugenoneRequests waiting for a slot now.
spanway_admission_rejected_requests_totalcounterreason (queue_full or queue_timeout)Requests refused with 503 since start.

Public feed rate limit​

This comes from the public feed rate limit.

MetricTypeLabelsMeaning
spanway_public_route_throttled_requests_totalcounternoneRequests 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.

MetricTypeLabelsMeaning
spanway_spend_log_cleanup_runs_totalcounteroutcome (completed, budget_exhausted, batch_cap_reached, aborted, skipped_disabled, skipped_locked)Cleanup runs and why each ended.
spanway_spend_log_cleanup_rows_deleted_totalcountertableRows deleted.
spanway_spend_log_cleanup_rows_remaininggaugetableExpired rows still waiting, counted only up to a cap, so the cap value means at least that many.
spanway_spend_log_cleanup_batch_failures_totalcountertableDelete batches that failed.
spanway_spend_log_cleanup_batch_duration_secondshistogramtableHow 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.

MetricTypeLabelsMeaning
spanway_cloud_billing_refusals_totalcounterreason (invalid_config)Cloud tenant requests refused with 503 cloud_billing_unavailable because the cloud block is invalid.
spanway_cloud_settlement_failures_totalcounterreason (invalid_config)Daily credit settlements that did not run.
spanway_cloud_overage_metering_blocked_totalcounterreason (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.

SettingEffect
prometheus_metrics_configA 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_labelsDrop metrics or labels everywhere. Unknown names stop startup with an error too.
prometheus_metrics_cleanup_interval_secondsHow often expired series are removed, 60 seconds by default.
prometheus_end_user_metrics_ttl_seconds, prometheus_end_user_metrics_cleanup_interval_secondsHow long an end_user series lives without updates (3,600 seconds) and how often they are checked (60 seconds).
prometheus_latency_bucketsA 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_metricA 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_secondsForget 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_metricA 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.

SettingDefaultWhat turning it on does
prometheus_emit_stream_labelfalseAdds stream (True or False) to spanway_proxy_total_requests_metric, so you can tell streaming traffic apart.
prometheus_emit_input_sequence_length_labelfalseAdds a bucketed prompt length label to the request metrics, to see whether long prompts are slower.
prometheus_emit_rate_limit_labelsfalseAdds 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_identityapi_key_aliasWhich 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_aliasfalseAdds 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_onlyunsetFills the end_user label from the request's user field.
disable_end_user_cost_tracking_prometheus_onlyunsetLeaves 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​

StatusWhereMeaningFix
401 Unauthorized access to metrics endpoint: ...GET /metricsNo 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.
404GET /metricsThe 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 namesGateway startprometheus_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 startAn 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 startThe caller identity setting has an unknown value.Use api_key_alias, user_email or both.
Error: --prometheus_metrics_port must differ from --portspanway command lineThe 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 lineThe 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 30sspanway command lineThe 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 seriesPrometheusWith 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​

LevelLineMeaningAction needed
DEBUGmounting metrics endpointThe prometheus callback loaded and /metrics is being mounted at startup.None.
DEBUGStarting 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.
ERROROne line per unknown metric or label from prometheus_metrics_configOnly 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.
WARNINGprometheus_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.
WARNINGError 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.

MetricTypeWhat it counts
spanway_proxy_total_requests_metriccounterRequests the gateway answered, by key, team, user and model.
spanway_proxy_failed_requests_metriccounterRequests the gateway answered with an error.
spanway_requests_metriccounterRequests sent to providers, by deployment.
spanway_llm_api_failed_requests_metriccounterProvider calls that failed.
spanway_callback_logging_failures_metriccounterLogging destination writes that failed.
spanway_in_flight_requestsgaugeRequests being handled right now on this worker.
spanway_total_tokens_metriccounterInput plus output tokens.
spanway_input_tokens_metriccounterInput tokens.
spanway_output_tokens_metriccounterOutput tokens.
spanway_input_cached_tokens_metriccounterInput tokens the provider read from its prompt cache.
spanway_input_cache_creation_tokens_metriccounterInput tokens written to the provider's prompt cache.
spanway_input_audio_tokens_metriccounterAudio input tokens.
spanway_output_reasoning_tokens_metriccounterReasoning tokens.
spanway_output_audio_tokens_metriccounterAudio output tokens.
spanway_provider_cache_read_input_tokens_metriccounterPrompt cache reads reported by the provider.
spanway_provider_cache_creation_input_tokens_metriccounterPrompt cache writes reported by the provider.
spanway_images_generated_metriccounterImages generated.
spanway_video_duration_seconds_metriccounterSeconds of video generated.
spanway_spend_metriccounterSpend in US dollars.
spanway_zero_cost_requests_totalcounterSuccessful requests recorded at zero cost, often a missing price.
spanway_spend_capture_rategaugeShare of requests whose cost was recorded.
spanway_request_increase_hints_totalcounterBudget and rate limit refusals that carried the request_increase hint, by request_type and target.
spanway_access_request_expiry_totalcounterTemporary access request raises the expiry job settled, by outcome (restored, kept, failed).
spanway_skill_scans_totalcounterSkill and plugin uploads skill scanning checked, by subject_type, status and mode.
spanway_skill_scan_files_totalcounterFiles of scanned skills and plugins, by verdict.
spanway_skill_scan_duration_secondshistogramSeconds one skill or plugin scan took, by subject_type.
spanway_mcp_skill_requests_totalcounterSkills over MCP requests, by method and outcome.
spanway_mcp_skill_request_duration_secondshistogramSeconds a skills over MCP request took, by method.
spanway_mcp_skill_store_errors_totalcounterTimes the skills table could not be read for skills over MCP.
spanway_workflow_trigger_fires_totalcounterWorkflow 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_totalcounterInbound 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_totalcounterTimes the gateway used or refused an agent's stored credential, by kind and outcome.
spanway_budget_tier_shifts_totalcounterTimes a team or organization moved to another budget tier, by scope_type and to_tier.
spanway_mcp_tool_calls_totalcounterMCP tool calls.
spanway_mcp_tool_call_spend_metriccounterSpend on MCP tool calls.
spanway_request_total_latency_metrichistogramSeconds from request to full answer.
spanway_llm_api_latency_metrichistogramSeconds the provider took.
spanway_llm_api_time_to_first_token_metrichistogramSeconds to the first streamed token.
spanway_overhead_latency_metrichistogramSeconds the gateway added.
spanway_overhead_with_guardrails_latency_metrichistogramSeconds the gateway added including guardrails.
spanway_deployment_latency_per_output_tokenhistogramSeconds per output token, by deployment.
spanway_request_queue_time_secondshistogramSeconds a request waited in the gateway queue.
spanway_remaining_team_budget_metricgaugeTeam budget left.
spanway_team_max_budget_metricgaugeTeam budget.
spanway_team_budget_remaining_hours_metricgaugeHours until the team budget resets.
spanway_team_members_metricgaugeMembers per team.
spanway_remaining_org_budget_metricgaugeOrganization budget left.
spanway_org_max_budget_metricgaugeOrganization budget.
spanway_org_budget_remaining_hours_metricgaugeHours until the organization budget resets.
spanway_remaining_api_key_budget_metricgaugeKey budget left.
spanway_api_key_max_budget_metricgaugeKey budget.
spanway_api_key_budget_remaining_hours_metricgaugeHours until the key budget resets.
spanway_remaining_user_budget_metricgaugeUser budget left.
spanway_user_max_budget_metricgaugeUser budget.
spanway_user_budget_remaining_hours_metricgaugeHours until the user budget resets.
spanway_remaining_customer_budget_metricgaugeEnd user budget left.
spanway_customer_max_budget_metricgaugeEnd user budget.
spanway_customer_budget_remaining_hours_metricgaugeHours until the end user budget resets.
spanway_remaining_requests_metricgaugeRequests left in the provider's rate limit window, by deployment.
spanway_remaining_tokens_metricgaugeTokens left in the provider's rate limit window, by deployment.
spanway_remaining_api_key_requests_for_modelgaugeRequests per minute left for a key on a model.
spanway_remaining_api_key_tokens_for_modelgaugeTokens per minute left for a key on a model.
spanway_api_key_rate_limit_allowed_metricgaugeA key's rate limit.
spanway_api_key_rate_limit_used_metricgaugeHow much of a key's rate limit is used.
spanway_team_rate_limit_allowed_metricgaugeA team's rate limit.
spanway_team_rate_limit_used_metricgaugeHow much of a team's rate limit is used.
spanway_project_model_rate_limit_allowed_metricgaugeA project's rate limit on a model.
spanway_project_model_rate_limit_used_metricgaugeHow much of a project's rate limit on a model is used.
spanway_deployment_tpm_limitgaugeA deployment's tokens per minute limit.
spanway_deployment_rpm_limitgaugeA deployment's requests per minute limit.
spanway_deployment_stategauge0 healthy, 1 partial outage, 2 complete outage.
spanway_deployment_total_requestscounterRequests per deployment.
spanway_deployment_success_responsescounterSuccessful answers per deployment.
spanway_deployment_failure_responsescounterFailed answers per deployment.
spanway_deployment_cooled_downcounterTimes a deployment was put in cooldown.
spanway_deployment_successful_fallbackscounterFallbacks that worked.
spanway_deployment_failed_fallbackscounterFallbacks that also failed.
spanway_guardrail_latency_secondshistogramSeconds a guardrail took.
spanway_guardrail_requests_totalcounterGuardrail checks.
spanway_guardrail_errors_totalcounterGuardrail 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_totalcounterMCP writes the write action alignment guardrail checked, by guardrail, outcome and category.
spanway_cache_hits_metriccounterResponse cache hits.
spanway_cache_misses_metriccounterResponse cache misses.
spanway_cached_tokens_metriccounterTokens served from the response cache.
spanway_code_traffic_requests_totalcounterCode traffic routed or refused by a data policy.
spanway_managed_file_created_totalcounterFiles uploaded through the gateway.
spanway_managed_file_deleted_totalcounterFiles deleted through the gateway.
spanway_managed_file_size_bytesgaugeSize of uploaded files.
spanway_managed_batch_created_totalcounterBatches created through the gateway.
spanway_managed_batch_duration_secondshistogramSeconds a batch took.
spanway_check_batch_cost_jobs_polledgaugeBatches the cost job checked in its last run.
spanway_check_batch_cost_jobs_processed_totalcounterBatches the cost job finished.
spanway_check_batch_cost_errors_totalcounterErrors in the batch cost job.
spanway_check_batch_cost_last_run_timestampgaugeWhen the batch cost job last ran.
spanway_in_memory_spend_update_queue_sizegaugeSpend updates waiting in memory to be written.
spanway_redis_spend_update_queue_sizegaugeSpend updates waiting in Redis.
spanway_in_memory_daily_spend_update_queue_sizegaugeDaily spend updates waiting in memory.
spanway_redis_daily_spend_update_queue_sizegaugeDaily spend updates waiting in Redis.
spanway_pod_lock_manager_sizegaugeBackground 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.