Skip to content

Allow /metrics handler output filtering via name[] query param - #1925

Merged
aknuds1 merged 5 commits into
prometheus:mainfrom
colega:feature/promhttp-metric-filtering
Dec 8, 2025
Merged

aknuds1 merged 5 commits into
prometheus:mainfrom
colega:feature/promhttp-metric-filtering

Conversation

@colega

@colega colega commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

Context

We have a huge application with thousands of metrics per pod, and we have a Prometheus instance that need to scrape a small subset of those metrics (5 to 10 metrics)

I've set up some relabeling rules, and it works great, but profiles say that this instance spends more than 50% of its CPU time just parsing openmetrics responses and dropping the metrics.

We could save some trees if there was a way to signal Prometheus that we just want a subset of them. I considered running a dumb nginx proxy that would strip out the unneeded metrics, but with native histograms being exposed in proto that won't be possible anymore, plus we'd still be spending precious CPU cycles encoding that response.

I have considered exposing those metrics on a different registry/handler, but:

  • It adds complexity to the application, those metrics are deep in the business logic
  • It would leak the details of how I operate the application to the application itself: the app shouldn't know whether I'm scraping with one Prometheus, two, or N.

What this PR does

This PR adds support for filtering metrics by name using the name[] query parameter in HandlerForTransactional (and hence in HandlerFor and promhttp.DefaultHandler). The default behavior is unchanged.

Related issue

I see this has been discussed already in #135
I don't see much consensus there, however I found out that this is something already implemented in client_python ref and client_java ref through the name[] query param, so I hope there isn't much discussion about whether this is a good fit here.

Example

# Get all metrics (existing behavior)
curl http://localhost:8080/metrics

# Get specific metrics
curl 'http://localhost:8080/metrics?name[]=http_requests_total&name[]=process_cpu_seconds_total'

@colega
colega force-pushed the feature/promhttp-metric-filtering branch from da23a04 to 9bcabdc Compare December 2, 2025 18:04
@colega colega changed the title Add metric filtering support to promhttp.HandlerForTransactional Add metric filtering support to promhttp.Handler Dec 2, 2025
@colega
colega force-pushed the feature/promhttp-metric-filtering branch from 9bcabdc to 80d1536 Compare December 2, 2025 18:08
@colega
colega marked this pull request as ready for review December 3, 2025 09:24
@colega
colega force-pushed the feature/promhttp-metric-filtering branch 3 times, most recently from 1c76a92 to ba1b97a Compare December 3, 2025 11:26
@colega colega changed the title Add metric filtering support to promhttp.Handler Allow /metrics filtering via name[]= query param Dec 3, 2025
@colega colega changed the title Allow /metrics filtering via name[]= query param Allow /metrics handler output filtering via name[] query param Dec 3, 2025
colega added a commit to grafana/dskit that referenced this pull request Dec 4, 2025
This forks the promhttp.Handler's code to serer/promhttpfork, and applies prometheus/client_golang#1925 on top of it. I'll remove the fork when it's merged and we can go back upstream.

Signed-off-by: Oleg Zaytsev <[email protected]>
This commit adds support for filtering metrics by name using the
name[] query parameter in HandlerForTransactional. Multiple metric
names can be specified by providing the parameter multiple times.

Example usage:
  /metrics?name[]=http_requests_total&name[]=process_cpu_seconds_total

Implementation details:
- Query parameters are parsed and converted to a map for O(1) lookup
- Filtering happens inline during the encoding loop to avoid allocating
  a new slice
- When no name[] parameters are provided, all metrics are returned
  (backward compatible)
- When name[] parameters don't match any metrics, an empty response
  is returned with HTTP 200

Tests include:
- Single and multiple metric filtering
- Backward compatibility (no filter returns all)
- Non-matching filters
- Empty and duplicate values
- Verification that transactional gather lifecycle is maintained

Signed-off-by: Oleg Zaytsev <[email protected]>

@aknuds1 aknuds1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I lack experience with the code in question, but the new functionality looks sensible to me. Leaving some suggestions. Also, shouldn't there be a changelog entry?

Comment thread prometheus/promhttp/http.go Resolved
Comment thread prometheus/promhttp/http_test.go Resolved
Comment thread prometheus/promhttp/http_test.go Resolved
Signed-off-by: Oleg Zaytsev <[email protected]>
Signed-off-by: Oleg Zaytsev <[email protected]>

@aknuds1 aknuds1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, except I wonder if there shouldn't be a changelog entry. Thanks for applying my feedback :)

colega added a commit to grafana/mimir that referenced this pull request Dec 5, 2025
…s` endpoint filtering by `name[]` (#13746)

<!--  Thanks for sending a pull request!  Before submitting:

1. Read our CONTRIBUTING.md guide
2. Rebase your PR if it gets out of sync with main
-->

#### What this PR does

Switches to a fork of `client_golang` that contains the PR
prometheus/client_golang#1925 which supports
`/metrics` endpoint handler filtering through the use of `name[]` query
param. I added a test to make sure this functionality doesn't disappear
in a possible future removal of this replace directive.

Also updates the costattribution package as this version now has changes
introduced by @duricanikolic in
prometheus/client_golang#1902

#### Which issue(s) this PR fixes or relates to

Fixes an internal issue

#### Checklist

- [x] Tests updated.
- [ ] Documentation added.
- [x] `CHANGELOG.md` updated - the order of entries should be
`[CHANGE]`, `[FEATURE]`, `[ENHANCEMENT]`, `[BUGFIX]`. If changelog entry
is not needed, please add the `changelog-not-needed` label to the PR.
- [ ]
[`about-versioning.md`](https://github.com/grafana/mimir/blob/main/docs/sources/mimir/configure/about-versioning.md)
updated with experimental features.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Switch to a forked `client_golang` to add `/metrics` filtering via
`name[]`, update cost-attribution validation and tests, adapt API usage,
and bump `compress`.
> 
> - **Server/HTTP metrics**:
> - Enable metric filtering on `/metrics` via `name[]` query param
(promhttp handler change). Added test
`TestMetricsEndpointSupportsMetricFiltering`.
> - **Dependencies**:
> - Replace `github.com/prometheus/client_golang` with fork
`github.com/colega/prometheus-client_golang` (pulls in filtering
support) and vendor updates.
> - Bump `github.com/klauspost/compress` to `v1.18.2` and vendor
changes.
> - **Cost attribution**:
> - Simplify metric descriptor validation using `prometheus.Desc.Err()`;
adjust error expectations in tests.
> - **Integration tests client**:
> - Adapt `LabelNames` to new `model.LabelNames` return type and convert
to `[]string`.
> - **Changelog**:
>   - Document `/metrics` filtering enhancement.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
94aa553. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: Oleg Zaytsev <[email protected]>
Signed-off-by: Oleg Zaytsev <[email protected]>
@colega

colega commented Dec 5, 2025

Copy link
Copy Markdown
Contributor Author

Oh, right, sorry, I forgot about the CHANGELOG.md, updated now.

@aknuds1
aknuds1 merged commit 572ca3a into prometheus:main Dec 8, 2025
@kakkoyun

kakkoyun commented Dec 8, 2025

Copy link
Copy Markdown
Member

@roidelapluie @aknuds1 for taking care of it. I guess we (client_golang maintainers) were not fast enough.

@bwplotka

bwplotka commented Dec 8, 2025

Copy link
Copy Markdown
Member

Thanks for this!

Please avoid merging PRs on a hot path without maintainers acknowledgement. Especially as it looks like it was only done/reviewed by a single company (plus one community member), when this library is used by thousands. If you want to maintain this project, respond on issues, fix bugs, do releases we would welcome new active members (:

Nevertheless, I reviewed and change is great, LGTM. If it was not, I hope you wouldn't mind if we would revert to iterate.

Re []name: This has been discussed a lot in the past. Users definitely need it, and the only controversy is that there is no STANDARD that would define clean API. E.g. users want to match on regexes, labels etc. This is important as once adopted, scrapers will need to adjust etc. I wished it was defined on OpenMetrics side etc (cc @dashpole @krajorama @ywwg should we?).

@dashpole

dashpole commented Dec 8, 2025

Copy link
Copy Markdown
Contributor

I'm not sure it belongs in the protocol specification. We do have a section on protocol negotiation that covers TLS and version negotiation, but I would prefer to keep the spec as limited to the text format as possible.

@bwplotka

Copy link
Copy Markdown
Member

Then what else we can do to ensure all SDKs have standard API for matching/URL of /metrics and avoid issue of scrape having to have custom flow (likely manually configurable) per specific application? cc @dashpole

@dashpole

dashpole commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

I would probably write a simple proposal, and then document it here https://prometheus.io/docs/instrumenting/writing_clientlibs/? Or maybe it can be its own page, similar to how UTF-8 is documented. I would hope we can apply this to more than just OpenMetrics 2.0

aknuds1 added a commit to grafana/mimir that referenced this pull request Dec 22, 2025
Use upstream prometheus/client_golang once more, as
prometheus/client_golang#1925 has been merged.

Signed-off-by: Arve Knudsen <[email protected]>
aknuds1 added a commit to grafana/mimir that referenced this pull request Dec 22, 2025
<!--  Thanks for sending a pull request!  Before submitting:

1. Read our CONTRIBUTING.md guide
2. Rebase your PR if it gets out of sync with main
-->

#### What this PR does

Use upstream
[prometheus/client_golang](https://github.com/prometheus/client_golang)
once more, as prometheus/client_golang#1925 has
been merged. There are no effective changes with this PR, only some code
comments are added to the vendored code.

#### Which issue(s) this PR fixes or relates to

Fixes #<issue number>

#### Checklist

- [ ] Tests updated.
- [ ] Documentation added.
- [ ] `CHANGELOG.md` updated - the order of entries should be
`[CHANGE]`, `[FEATURE]`, `[ENHANCEMENT]`, `[BUGFIX]`. If changelog entry
is not needed, please add the `changelog-not-needed` label to the PR.
- [ ]
[`about-versioning.md`](https://github.com/grafana/mimir/blob/main/docs/sources/mimir/configure/about-versioning.md)
updated with experimental features.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Replaces forked `prometheus/client_golang` with upstream
pseudo-version and updates vendored promhttp docs, modules, and sums.
> 
> - **Dependencies**:
> - Switch to upstream
`github.com/prometheus/[email protected]`;
remove `replace` to fork.
> - **Vendored code**:
> - Update comments in `prometheus/promhttp/http.go` to document
`name[]` metric filtering for `Handler` and `HandlerFor`.
>   - Refresh `vendor/modules.txt` entries for `client_golang`.
> - **Housekeeping**:
>   - Update `go.sum` accordingly.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
0e053b2. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Signed-off-by: Arve Knudsen <[email protected]>
@juliusv

juliusv commented Apr 10, 2026

Copy link
Copy Markdown
Member

Re []name: This has been discussed a lot in the past. Users definitely need it, and the only controversy is that there is no STANDARD that would define clean API. E.g. users want to match on regexes, labels etc.

Besides the call for a standard, I also think that being able to filter by regexes is something I would expect from this kind of filtering functionality. If I wanted all container_.* metrics, I would have to list a lot of name[] params, and I might not always even know all the metric names that exist with a given prefix (if I want to just get them all).

@colega
colega deleted the feature/promhttp-metric-filtering branch April 10, 2026 15:55
@colega

colega commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

I think that would require a better feature definition, and also what's the use case for that? Our use case for this was to bring only the minimum required metrics to evaluate some recording rules, I think that bringing arbitrary series matching a regexp defies that purpose.

I'm not against it, I just think that we shouldn't try to build it if there's no real use case.

@juliusv

juliusv commented Apr 10, 2026

Copy link
Copy Markdown
Member

The main use case I can think of would be what people are already doing with metric relabeling in the Prometheus server to only scrape a subset of metrics from a target (for example, because they care about one topic area of metrics that all start with a given prefix), but doing so more efficiently because the filtering happens earlier on in the chain. So a metric relabeling rule like:

metric_relabel_configs:
  - action: keep
    source_labels: [__name__]
    regex: '(api_|http_|container_).*'

Relabeling is powerful because it also allows matching on other labels, rewriting them, extracting parts of one label into another, and so on. That's probably more than we want here, but some form of pattern-based matching would still be nice for this use case.

@roidelapluie

Copy link
Copy Markdown
Member

?keep[]=(api_|http_|container_).*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants