Measure request duration with prometheus and golang

Robert Scherbarth
2 min readMay 1, 2020

--

This article shows an example on how to measure request durations in microservices.

Here I want to show a little example how to measure the duration on any request via a middleware. I longer use prometheus/grafana to evaluate the status of my services. So I want to show an example on how to measure your requests. This Article shows this with an golang example implementation.

Prometheus is an open-source system. That provides monitoring and alerting toolkits. For this article only the main component is relevant. This is the Prometheus-server which scrapes and stores time series data. To provide this data this article uses prometheus/client_golang which is a official supported by the prometheus community.

The following code shows the example code for the middleware:

measureResponseDuration is a factory function which returns a http.Handler. It enrich the returned function with a prometheus histogram. This is used to get the information of the incoming request. The essential part is to call the responseTimeHistogram. ... .Observe(...) after next.ServeHTTP(...) with this we make sure that all other handler-functions are called.

To get the status code we have to implement the http.responseWriter interface. The implementation shows that I created a statusRecorder struct for this purpose. It is responsible to store the status code after the request is finished. It is set to a default value because Calling WriteHeader inside of a handler is optional and with this it is ensured that the prometheus label is set to a value.

The defined routes can be added via labels as well. But use it with caution. Because if you have too many routes in your service. The queries become very slow if the cardinality is too high. You can get the route pattern from the context as shown in the getRoutePattern function.

In this example I used prometheus buckets the metric that will be exposed are looking like this:

sample output with 2 routes

And maybe you want to build some grafana dashboard this could look like this:

grafana example

--

--

Responses (2)