prometheuspromql

PromQL "topk" function is not working as expected


I am trying to display the top 10-services which have high memory usage.

For that I have written the following promql:

sort_desc(topk(5, max by (container)(max_over_time(container_memory_usage_bytes{namespace=~"(ns1|ns2|ns3)", container!=""}[$__interval]))) by (container))

I'm using Bar Gauge visualization and in metric Options -> Type = Instant.

This is still returning all the values and not just top 10.

I tried to follow the recommendations that were made in the similar post on this platform for gauge but couldn't resolve it so looking for other suggestions.


Solution

  • Remove the by (container) grouping from the topk aggregator- you're grouping by your container tag which would mean you're getting the top 5 values per container, so you're getting values for all containers.

    Your query should become something like this:

    sort_desc(
      topk (
        5,
        max by (container) (
          max_over_time(container_memory_usage_bytes{container!="",namespace=~"(ns1|ns2|ns3)"}[$__interval])
        )
      )
    )