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.