Prometheus Query to Count Unique Label Values

Better Stack Team
Updated on December 2, 2024

To count unique label values in Prometheus, you can use the count function along with the by clause to aggregate metrics based on a specific label. This is useful when you want to find out how many unique values a particular label has within a given metric.

Example Scenario

Let’s say you have a metric called http_requests_total that includes a label named instance. You want to count how many unique instances are being tracked.

PromQL Query

Here’s how you can construct your query:

 
count(http_requests_total) by (instance)

Breakdown of the Query

  • count(http_requests_total): This part of the query counts the number of occurrences of the http_requests_total metric across all instances.
  • by (instance): This clause specifies that the counting should be grouped by the instance label. As a result, you will get a count of http_requests_total for each unique instance.

Getting Distinct Unique Values

If you want to get the distinct unique values of a label (rather than just counting how many times each unique value appears), you can use the count function on the label_replace function. Here’s an example:

 
count(count(http_requests_total) by (instance))

Additional Example: Counting Unique Values of a Different Label

Suppose you want to count unique values of another label, such as status, from the same metric:

 
count(http_requests_total) by (status)

This will give you the count of requests grouped by the status code.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github