Search code examples
prometheusgrafanapromql

Calculate percentage of multiple prometheus metrics and display in Grafana


I have the following metrics:

total_number_of_visitors which is a gauge that increases when a visitor enters the website and decreases when they leave

paid_visitors which is a counter that is incremented when a paid visitor enters the website and stays for at least 5 minutes.

Each one of these metrics has two common labels device [mobile, desktop, other] and browser [ Chrome, Safari, Firefox, Edge, other]

I want to calculate a percentage of the a paid visitors using PromQL and filter by any of these two labels to display in a graph in Grafana. How do I go about that?


Solution

  • The following query would return the average percentage of paid visitors on the site during the last 5 minutes:

    100 * rate(paid_visitors[5m]) / avg_over_time(total_number_of_visitors[5m])
    

    Filtering by device and browser labels can be performed in the following way:

    100 * rate(paid_visitors{device="$device",browser="$browser"}[5m]) / avg_over_time(total_number_of_visitors{device="$device",browser="$browser"}[5m])
    

    Just substitute $device and $browser with the desired values.

    Grouping be device and browser labels can be performed in the following way:

    100 * sum(rate(paid_visitors[5m])) by (device, browser) / sum(avg_over_time(total_number_of_visitors[5m])) by (device, browser)