prometheusgrafanapromql

PromQL Condition within query


Good day, i have an existing PromQL query which is working ok within Grafana, the query is supposed to show the success rate in percent for a custom http metric.

1 - 
sum by(api_name)
(
    increase(demo_http_requests_seconds_count{error="true", api_name="Demo_API", consumer="Demo_Consumer"}[$__range])
)
/ 
sum by(api_name)
(
    increase(demo_http_requests_seconds_count{api_name="Demo_API", consumer="Demo_Consumer"}[$__range])
)

My problem is that the failed http metric (indicated with error="true") returns sometimes no result and in turn the result does not show anything in Grafana.

Is it possible, for example to create a condition around the query to say that if no errors returned that the success rate will be 1 (100%) ?


Solution

  • Try the following PromQL query:

    sum by(api_name)
    (
      increase(demo_http_requests_seconds_count{
        error!="true", api_name="Demo_API", consumer="Demo_Consumer"
      }[$__range])
    )
    /
    sum by(api_name)
    (
      increase(demo_http_requests_seconds_count{
        api_name="Demo_API", consumer="Demo_Consumer"
      }[$__range])
    )
    or
    sum by(api_name) (
      demo_http_requests_seconds_count{
        api_name="Demo_API", consumer="Demo_Consumer"
      }
    ) * 0
    

    The query contains or ... part, which adds 0 value to the initial query results if they do not contain some api_name label value.

    P.S. Note that increase() function in Prometheus may return unexpected results for slow-changing counters. See this issue and this question for details.