Define custom metric instruments in Tyk Gateway with your own dimensions sourced from request headers, JWT claims, session data, endpoint paths, and more.
By default, Tyk Gateway exports standard RED metrics with a fixed set of dimensions. Custom metrics let you define additional instruments with dimensions drawn from request headers, session data, JWT claims, and other context, enabling use cases such as:
Multi-tenant billing: Count requests per customer ID from a header or JWT claim
Tier-based SLOs: Track latency separately for premium vs. standard API tiers
Business KPIs: Measure domain-specific signals (e.g., successful transactions per payment provider)
API-level metrics are disabled entirely; no request metrics are exported.
Populated array
Only the instruments you define are exported. Default RED metrics are not exported unless you explicitly define them.
Preserving default RED metricsWhen you populate api_metrics, the built-in RED instruments are no longer exported automatically. Use the block below as a starting point, it re-creates all four default instruments, then append your custom instruments after them.
Dimensions let you slice your metrics by any signal available at request time. Tyk can source dimension values from six places; the sections below describe common use cases and which source and key to use for each.
Two metadata keys capture response status, and they answer different questions:
Key
Source
What it captures
response_code
metadata
The numeric HTTP status code returned to the client (200, 429, 502, etc.). Always populated. Bounded cardinality (~100 values).
response_flag
metadata
A 3-letter error classification code set by the gateway, e.g. URS (upstream returned 5XX), AKI (API key invalid), CBO (circuit breaker open). Falls back to the HTTP status code string (e.g. "200") when no error classification applies. See the full list of response flags.
Use response_code to break down traffic by HTTP status. Use response_flag to understand Gateway-level error causes.The status_codes filter in the filters block decides whether a request is recorded at all. The response_code dimension attaches the actual code as a label on the recorded data points. A common pattern is to combine both: filter to error responses, then break them down by exact code:
Four options are available, at different cardinality levels:
Source
Key
Cardinality
Notes
API listen path
metadata
listen_path
Bounded (one value per API)
The configured listen path (e.g. /api/v1/). Safe to use in any metric.
Endpoint template
metadata
endpoint
Bounded (one per track endpoint)
The matched path template (e.g. /user/{id}). Requires track_endpoints configured on the API. Empty string for unmatched requests.
Raw request path
context
path
⚠️ Potentially unbounded
The URL path as requested by the client (e.g. /api/v1/users/12345). Avoid unless paths have known low cardinality.
Path segments
context
path_parts
⚠️ Potentially unbounded
The path split by / into a list of segments (e.g. /api/v1/users/123 → ["api", "v1", "users", "123"]). Access a specific segment with {{ index ._tyk_context.path_parts N }}. Carries the same cardinality risk as path if any segment varies per request.
Prefer listen_path or endpoint (with track_endpoints) over raw path or path_parts in most cases.
Several sources expose client identity, with different cardinality trade-offs:
Session fields (session source): alias (the human-readable key alias), portal_app (Developer Portal app ID), and portal_org (Developer Portal org ID) are typically bounded and safe to use. api_key and oauth_id are ⚠️ high cardinality (one value per key/client); only use these with cardinality control enabled.
JWT claims (context source): any claim is available as jwt_claims_<name> (e.g. jwt_claims_tier, jwt_claims_tenant_id). See Request context variables for setup requirements and cardinality notes.
Request headers (header source): use when client identity is passed as a header (e.g. X-Tenant-ID). Cardinality depends on what the header contains.
If you want to attach static, API-level metadata (such as team ownership, service tier, cost centre, or criticality) to your metrics without touching request headers or tokens, use the config_data source.The config_data field in the API definition is a free-form key-value map you can populate per API:
A dimension like {"source": "config_data", "key": "team"} will carry team="platform" on every metric recorded for that API; no request modification required.Fallback behaviour: If config_data_disabled is true on the API, or the key is absent, the dimension falls back to the default value on the dimension definition. If no default is set, an empty string is used. All values are treated as strings.
The context source reads from Tyk’s request context variables, a set of values extracted from the incoming request and enriched during middleware processing. The context source covers two kinds of variables: those populated automatically by Tyk, and those written by custom plugins.
Context variables must be enabled on the API definition (enable_context_vars: true) for the context source to work. Without this setting, all context dimensions will be empty.
The request path split by / into a list of segments. E.g. /api/v1/users/123 → ["api", "v1", "users", "123"]. Access individual segments with {{ index ._tyk_context.path_parts N }}.
⚠️ Potentially unbounded.
remote_addr
The connecting client IP address.
⚠️ High cardinality.
jwt_claims_<name>
Individual JWT claims, e.g. jwt_claims_tier, jwt_claims_tenant_id. Available when JWT auth is in use.
Bounded if the claim takes a fixed set of values (e.g. subscription tier). Safe to use.
cookies_<name>
Cookie values by name (hyphens replaced with underscores).
Depends on cookie values.
headers_<name>
Request header values by name (capitalised, hyphens replaced with underscores, e.g. headers_User_Agent).
Depends on header values.
token
The raw inbound bearer token.
⚠️ Extremely high cardinality. Do not use as a dimension.
Usually the most useful defaults for metrics are JWT claims: they let you segment traffic by tenant, subscription tier, or any other bounded claim without requiring a plugin:
Go plugins and JQ request transforms can write arbitrary variables into the request context, which are then accessible as context source dimensions. This is useful for computed signals, such as enriched tenant IDs, feature flags, routing decisions, or values decoded from opaque tokens.Go plugin:
import "github.com/TykTechnologies/tyk/ctx"func MyPlugin(w http.ResponseWriter, r *http.Request) { if ctxData, ok := r.Context().Value(ctx.ContextData).(map[string]interface{}); ok { ctxData["my_custom_var"] = "value" }}
JQ transform: return a tyk_context object alongside the transformed body:
Python, gRPC (coprocess), and JavaScript (JSVM) plugins cannot write to request context variables. To pass data from these plugins into metrics dimensions, use session metadata (session source, via session.meta_data) or inject a custom HTTP request header (header source) instead.
When a request is handled by an MCP API, Tyk populates four additional metadata keys derived from the JSON-RPC payload. These are available as dimensions in any custom metric instrument.
JSON-RPC error code on failure; empty string on success
-32001, -32002, “
Bounded
These keys are only populated for MCP APIs. For non-MCP requests all four keys resolve to an empty string; use the default field on the dimension definition to set a fallback value. There is no performance overhead on non-MCP metric configurations.
Each instrument can restrict which requests it records using the filters block. All filter conditions use AND logic (a request must match all specified filters):
Filter Field
Type
Description
api_ids
string array
Only record requests to these API IDs.
methods
string array
Only record requests with these HTTP methods (e.g., ["GET", "POST"]).
status_codes
string array
Only record responses with these status codes. Supports exact values ("200") and class patterns ("2xx", "4xx", "5xx").
Custom dimensions can significantly increase cardinality. Before adding a dimension, estimate the number of unique values it can take:
api_id: bounded (tens or hundreds of APIs)
method: bounded (fewer than 10 values)
customer_id from a header: potentially unbounded if unique per user
The cardinality_limit setting (default: 2,000 unique combinations per instrument) protects against unbounded cardinality. When the limit is reached, new combinations are tracked in an overflow bucket. See Cardinality Control for details.
On Tyk Cloud, custom metric configuration is not currently self-service. Contact Tyk support to request custom dimensions for your Cloud deployment.