# Metrics API

Scrape your team's transaction and Shredstream metrics into Prometheus or Grafana, or read historical metric series as JSON

Source: https://zerocopy.sh/docs/account/metrics-api

Use the Metrics API to monitor your team's SWQoS traffic and Shredstream receivers
in Grafana. Partners also receive metrics for their customer keys.

[`GET /api/v1/metrics`](/docs/reference/management-api/retrieve-prometheus-metrics)
returns Prometheus text exposition. For historical queries, use
[`GET /api/v1/metrics/series`](/docs/reference/management-api/retrieve-metric-history).
Both endpoints require a [management key](/docs/api-keys#management-keys) with `usage:read`.

## Create a management key [#management-key]

On your team's **API keys** page, create a management key and select `usage:read`.
Only a team admin can create it, after identity verification. Save the `zc_mgmt_`
secret when it appears; the console shows it once.

Choose a lifetime of 30, 90 or 365 days. If you set an IP restriction, allow the
addresses your scraper uses. Create a replacement and update the scraper before
the key expires, then revoke the old key. An SWQoS API key cannot authenticate
metrics requests.

## Scrape with Prometheus [#prometheus]

Add this job to your [Prometheus configuration](https://prometheus.io/docs/prometheus/latest/configuration/configuration/).
Replace `YOUR_MANAGEMENT_KEY` with the management key's secret. Restrict access to
the configuration file.

```yaml title="prometheus.yml"
scrape_configs:
  - job_name: zerocopy
    scheme: https
    metrics_path: /api/v1/metrics
    scrape_interval: 60s
    honor_timestamps: true
    track_timestamps_staleness: true
    authorization:
      type: Bearer
      credentials: YOUR_MANAGEMENT_KEY
    static_configs:
      - targets: [console.zerocopy.sh]
```

Each SWQoS sample covers one complete UTC minute, assigned by the transaction's
first receipt time. Data is 3 minutes behind. Samples carry the minute's end as
an explicit millisecond timestamp. Keep `honor_timestamps` enabled so Prometheus
stores that timestamp. End Grafana graphs at `now-3m` to account for the lag.

Every metric is a gauge. Counts and SOL amounts are totals for that minute; use
the values directly, or `sum_over_time()` to total stored minutes. `rate()` and
`increase()` apply to counters and give incorrect results for these gauges.
The endpoint emits only series observed in the minute, except
`zerocopy_key_info`, which includes every non-deleted key. A missing series does
not assert a zero. `track_timestamps_staleness` stops a missing timestamped series
from staying visible through Prometheus's normal lookback window.

Scraping more often repeats the same minute. Scraping less often, or missing a
scrape, can leave gaps: this endpoint does not replay missed minutes. Use the
JSON history endpoint when you need historical buckets. Transaction records are
best effort and are not a billing ledger.

Records that arrive after a minute was scraped are absent from its stored
samples. JSON history reads current records and buckets them by resolution
time, so its figures can differ from the scraped receipt-time buckets.

## Grafana Cloud [#grafana-cloud]

The [Metrics Endpoint integration](https://grafana.com/docs/grafana-cloud/observe-and-act/monitor-infrastructure/integrations/integration-reference/integration-metrics-endpoint/)
can scrape the endpoint without a Prometheus server:

1. In Grafana Cloud, open **Connections** and select **Metrics Endpoint**.
2. Create a scrape job named `zerocopy` with the URL
   `https://console.zerocopy.sh/api/v1/metrics` and a one-minute scrape interval.
3. Choose **Bearer** authentication. Paste the management key without the
   `Bearer ` prefix.
4. Test the connection, then save the job.

If the key has IP restrictions, allow the scraper addresses for your stack's
region. Grafana documents them through its
[Allowlist API](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/allow-list/#allowlist-api).
The Metrics Endpoint integration uses the `grafana` service's addresses.

## Import the dashboard [#dashboard]

<a href="/docs/examples/zerocopy-metrics-dashboard.json" download="zerocopy-metrics-dashboard.json">Download the Grafana dashboard JSON</a>.
In Grafana, open **Dashboards**, choose **New > Import**, then upload the file.
Select the Prometheus datasource that stores your ZeroCopy metrics. The
dashboard's time range ends three minutes before now.

The **Customer** and **Key** selectors use `zerocopy_key_info`. **All** customers
includes your own keys, whose `customer` label is empty. SWQoS panels follow both
selectors. Shredstream panels show the team's receivers independently of key
selection.

Quantile panels show each key separately, with metro where present. Quantiles
from different keys or minutes cannot be combined into a team quantile. Panels
show **No data** when their selected series are absent, including a receiver
panel for a team without Shredstream receivers.

## Metric reference [#metrics]

SWQoS metrics have `key_id`. Where present, `metro` is a public
[metro identifier](/docs/swqos/endpoints#regions). `quantile` is `0.5`, `0.9` or `0.99`.
Key names and customer references appear only on `zerocopy_key_info`.

| Metric | Labels | Value |
| --- | --- | --- |
| `zerocopy_key_info` | `key_id`, `name`, `customer`, `state` | `1` for each non-deleted key. `state` is `active`, `expired` or `revoked`; `customer` is empty for own keys |
| `zerocopy_swqos_transactions` | `key_id`, `metro`, `outcome` | Transactions in the minute; `outcome` is `landed`, `failed` or `expired` |
| `zerocopy_swqos_slots_to_land` | `key_id`, `metro`, `quantile` | Slots to land for landed transactions |
| `zerocopy_swqos_edge_time_seconds` | `key_id`, `metro`, `quantile` | Time from receipt to forwarding, in seconds |
| `zerocopy_swqos_tips_sol` | `key_id`, `metro` | Tips in SOL for landed transactions; token tips count at their SOL value when sent |
| `zerocopy_swqos_priority_fees_sol` | `key_id`, `metro` | Priority fees in SOL for landed and failed transactions |
| `zerocopy_swqos_failed_transactions` | `key_id`, `error` | Failed transactions by normalized error; the team's top 20 errors in the minute, with the rest under `other`. `unknown` means the error is empty or unparseable |
| `zerocopy_swqos_compute_unit_price_microlamports` | `key_id`, `quantile` | Compute unit price in microlamports per compute unit, for legacy and v0 transactions only; v1 sets a total priority fee |
| `zerocopy_swqos_compute_unit_limit` | `key_id`, `quantile` | Requested compute unit limit |
| `zerocopy_swqos_landed_index` | `key_id`, `quantile` | Zero-based position in the block for landed transactions |
| `zerocopy_swqos_block_engine_submissions` | `key_id`, `engine`, `result` | Submission attempts by result; `engine` is `jito` for Jito (BAM), `dbi` for Jito (DBI), `harmonic`, `everstake` or `gbx` |
| `zerocopy_shredstream_packets_per_second` | `receiver_id`, `receiver`, `metro` | Packets delivered per second over the preceding two minutes |
| `zerocopy_shredstream_bytes_per_second` | `receiver_id`, `receiver`, `metro` | Bytes delivered per second over the preceding two minutes |
| `zerocopy_shredstream_errors_per_second` | `receiver_id`, `receiver`, `metro` | Delivery errors per second over the preceding two minutes |

Error labels contain at most 120 characters. Normalization removes varying
transaction details such as amounts, addresses and instruction indexes.

### Block engine submissions [#block-engine-submissions]

Each attempt counts once, including attempts for bundles with several
transactions. For Jito (BAM), the latest status replaces the initial submission answer.

| Result | Meaning |
| --- | --- |
| `accepted` | The engine acknowledged receipt; this does not establish landing |
| `processed`, `finalized` | The latest Jito (BAM) status |
| `rejected`, `dropped`, `error`, `timeout`, `rate_limited`, `unavailable` | The engine's corresponding answer |
| `dbi_written` | Sent through Jito (DBI) |
| `no_result` | Harmonic, Everstake or GBX acknowledged receipt and has no later status |
| `other` | An unrecognized answer |

Empty or skipped submissions are omitted.

### Show key names and customers [#key-names]

Join transaction values to the info metric with `on (key_id) group_left`:

```text title="Transactions with key names and customers"
zerocopy_swqos_transactions
  * on (key_id) group_left (name, customer)
    (topk by (key_id) (1, timestamp(zerocopy_key_info)) > bool 0)
```

The result retains `metro` and `outcome` and adds `name` and `customer`. To group
by customer, apply `sum by (customer, outcome)` to the joined expression. Keys
without a customer reference have `customer=""`.

`topk` selects the newest info sample for each key, then `> bool 0` turns its
timestamp into `1`. This avoids duplicate matches while Prometheus still has an
older name or customer reference in its lookback window.

## JSON history [#json-history]

[`GET /api/v1/metrics/series`](/docs/reference/management-api/retrieve-metric-history) returns the same historical metric buckets as the
console's Metrics page. Set `MANAGEMENT_API_KEY` to your management key. Rust and
Go use the [example project](/docs/reference/json-rpc#example-project).

```rust title="src/bin/metric_series.rs" tab="Rust" tab-group="language"
use serde_json::Value;
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .get("https://console.zerocopy.sh/api/v1/metrics/series?metric=transactions&range=24h&group_by=outcome")
        .bearer_auth(required("MANAGEMENT_API_KEY")?)
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="metric-series/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("MANAGEMENT_API_KEY")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodGet,
		"https://console.zerocopy.sh/api/v1/metrics/series?metric=transactions&range=24h&group_by=outcome", nil)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="metric-series.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.MANAGEMENT_API_KEY
if (!apiKey) throw new Error('set MANAGEMENT_API_KEY')

const query = new URLSearchParams({
  metric: 'transactions',
  range: '24h',
  group_by: 'outcome',
})
const response = await fetch(
  `https://console.zerocopy.sh/api/v1/metrics/series?${query}`,
  { headers: { authorization: `Bearer ${apiKey}` } },
)
const body = await response.text()
let reply: unknown
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="Read metric history" tab="cURL" tab-group="language"
curl --fail-with-body -sS --get 'https://console.zerocopy.sh/api/v1/metrics/series' \
  -H "Authorization: Bearer $MANAGEMENT_API_KEY" \
  --data-urlencode 'metric=transactions' \
  --data-urlencode 'range=24h' \
  --data-urlencode 'group_by=outcome'
```

Choose `metric` from `transactions`, `landed_rate`, `failed_rate`, `expired_rate`,
`slots_to_land`, `edge_time`, `tips` or `priority_fees`. For `slots_to_land` and
`edge_time`, use `quantile=0.5`, `0.9` or `0.99`. Group by `key`, `metro`, `outcome`,
`path`, `source` or `kind`. Path groups can overlap because a transaction can use
several paths.

Use `range=1h`, `24h` (the default), `7d` or `30d`, or supply RFC 3339 `from` and
`to` times within the last 90 days. Filter with `key_id`, `metro` and `outcome`;
repeat a parameter to select several values. A partner can select a customer
key with `key_id`.

The response includes `metric`, `unit`, optional `quantile`, `step_seconds`,
`from`, `to` and `series`. Each series has `labels` and `points` pairs of
`[unix_ms, value]`; a null value means the bucket has no value. Consult the
[metric history reference](/docs/reference/management-api/retrieve-metric-history) for query formats and units.

JSON rates use percent from 0 to 100. JSON `edge_time` uses microseconds, and
`tips` and `priority_fees` use lamports. `tips` includes token tips at their SOL value
when sent. The corresponding Prometheus metrics use seconds and SOL.

## Rate limits [#rate-limits]

Each management key can make 600 GET requests per minute across the Management
API. Responses include `RateLimit-Limit`, `RateLimit-Remaining` and
`RateLimit-Reset`. Exceeding the limit returns `429 rate_limited` and a
`Retry-After` header. IP restrictions apply to both metrics endpoints.

A team can run two analytics requests at once. Prometheus requests count toward
this limit only when a cached response is unavailable; JSON history requests
always count. Excess concurrent requests return `429 analytics_busy` with `Retry-After: 1`.
Use one scrape job per team and let Grafana query Prometheus for its panels.
