Sobes.tech
Senior

How to measure the execution time of an HTTP request using only counters (without histogram)?

sobes.tech AI

Answer from AI

If histograms cannot be used and only counters are available, you can approximately estimate the execution time of an HTTP handler using two counters:

  1. A counter for the total number of handler calls (e.g., requests_total).
  2. A counter for the total time spent on all calls (e.g., requests_duration_seconds_total).

In each HTTP handler:

  • Record the start and end time of the request processing.
  • Increment the call counter by 1.
  • Add the duration (time difference) to the total time counter.

The average execution time can be obtained as the ratio of total time to the number of calls:

var (
    requestsTotal = prometheus.NewCounter(prometheus.CounterOpts{Name: "requests_total"})
    requestsDuration = prometheus.NewCounter(prometheus.CounterOpts{Name: "requests_duration_seconds_total"})
)

func handler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()
    // process request
    // ...
    duration := time.Since(start).Seconds()

    requestsTotal.Inc()
    requestsDuration.Add(duration)
}

Thus, although we do not get a distribution of times, we can calculate the average execution time as requests_duration_seconds_total / requests_total. This is a simple and effective method under constraints on histogram usage.

How to measure the execution time of an HTTP request… - sobes.tech