How to Expose Prometheus Metrics
In this guide, we add Prometheus metrics to a ZIO HTTP server with the zio-http-metrics module. By the end, the server counts every request, measures how long each one takes, tracks how many are in flight, and serves all of it at GET /metrics in the text format that Prometheus scrapes.
We start from a small orders API, instrument it with one call to MetricsEndpoint.withMetrics, read the output, and then change the path, the labels, and the polling interval. The last section shows how to instrument only some routes.
The Problem
A Prometheus scraper needs an HTTP endpoint that returns the current metric values as text. ZIO HTTP's Middleware.metrics records the request metrics, but it does not serve them: without the zio-http-metrics module, you write the /metrics route yourself, add the ZIO Metrics Connectors libraries to the build, and provide three layers whose names do not say what each one does.
For example, a server that wires the Prometheus connector by hand looks like this:
import zio._
import zio.metrics.connectors.prometheus.PrometheusPublisher
import zio.metrics.connectors.{MetricsConfig, prometheus}
import zio.http._
object HandWiredMetrics extends ZIOAppDefault {
val api: Routes[Any, Response] =
Routes(
Method.GET / "orders" -> handler(Response.text("order-1, order-2")),
) @@ Middleware.metrics()
val metrics: Routes[PrometheusPublisher, Response] =
Routes(
Method.GET / "metrics" -> handler(ZIO.serviceWithZIO[PrometheusPublisher](_.get.map(Response.text))),
)
val run =
Server
.serve(api ++ metrics)
.provide(
Server.default,
prometheus.prometheusLayer,
prometheus.publisherLayer,
ZLayer.succeed(MetricsConfig(1.second)),
)
}
Each of the three layers has a job: publisherLayer holds the latest Prometheus text, prometheusLayer polls the ZIO metrics and writes them into the publisher, and MetricsConfig sets how often it polls. Leaving out prometheus.prometheusLayer is an easy mistake: the program still compiles, the compiler only warns that the MetricsConfig layer is unused, and /metrics answers every request with an empty body.
The zio-http-metrics module packages the middleware, the route, and the layers into the MetricsEndpoint object, so the same server takes two calls.
Prerequisites
Add ZIO HTTP and the metrics module to your build.sbt:
// ZIO HTTP server and client
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
// Prometheus metrics endpoint for ZIO HTTP (brings in the ZIO Metrics Connectors Prometheus connector)
libraryDependencies += "dev.zio" %% "zio-http-metrics" % "3.12.0"
The examples in this guide use these imports:
import zio._
import zio.http._
import zio.http.metrics.MetricsEndpoint
This guide assumes you know how to define routes and start a server. The recorded metrics are the ones described in the metrics middleware reference.
The Routes to Instrument
The examples instrument a small orders API with two routes. The second route has a path parameter and returns 404 Not Found for any order except order 1, so the output shows how parameters and status codes appear in the metric labels:
object OrderRoutes {
val routes: Routes[Any, Response] =
Routes(
Method.GET / "orders" -> handler(Response.text("order-1, order-2")),
Method.GET / "orders" / int("orderId") -> handler { (orderId: Int, _: Request) =>
if (orderId == 1) Response.text("order-1") else Response.notFound
},
)
}
Instrumenting Routes and Serving /metrics
MetricsEndpoint.withMetrics applies Middleware.metrics() to the routes and appends a GET /metrics route that returns the Prometheus text. The result needs a PrometheusPublisher from the environment, which MetricsEndpoint.layers() provides together with the polling that fills it:
object Step4ServeMetricsExample extends ZIOAppDefault {
val run =
Server
.serve(MetricsEndpoint.withMetrics(OrderRoutes.routes))
.provide(Server.default, MetricsEndpoint.layers())
}
Server.default listens on port 8080. MetricsEndpoint.withMetrics appends the /metrics route after it applies the middleware, so the HTTP metrics do not count scrapes of /metrics.
Reading the Prometheus Output
With the server running, we send a few requests to the orders API and then read the metrics:
curl localhost:8080/orders
curl localhost:8080/orders
curl localhost:8080/orders/1
curl localhost:8080/orders/7
sleep 2
curl localhost:8080/metrics
The response groups the values by metric. This excerpt shows the request counter and the in-flight gauge; the last number on each line is the timestamp of the poll in milliseconds:
# TYPE http_concurrent_requests_total gauge
# HELP http_concurrent_requests_total
http_concurrent_requests_total{method="GET",path="/orders"} 0.0 1796060874490
http_concurrent_requests_total{method="GET",path="/orders/{orderId}"} 0.0 1796060874490
# TYPE http_requests_total counter
# HELP http_requests_total
http_requests_total{method="GET",path="/orders/{orderId}",status="404"} 1.0 1796060874490
http_requests_total{method="GET",path="/orders/{orderId}",status="200"} 1.0 1796060874490
http_requests_total{method="GET",path="/orders",status="200"} 2.0 1796060874490
The path label holds the route pattern, /orders/{orderId}, not the requested path, so requests for different orders add to the same series. The status label separates the successful lookup from the 404. The http_request_duration_seconds histogram follows the same labels and adds _bucket, _count, _sum, _min, and _max lines:
http_request_duration_seconds_bucket{method="GET",path="/orders/{orderId}",status="404",le="0.005"} 1.0 1796060874490
http_request_duration_seconds_count{method="GET",path="/orders/{orderId}",status="404"} 1.0 1796060874490
http_request_duration_seconds_sum{method="GET",path="/orders/{orderId}",status="404"} 0.004432455 1796060874490
/metrics returns the snapshot taken by the last poll, not the live values. A request made just before a scrape appears after the next poll, which is up to one polling interval (one second by default) later. That is why the commands above wait two seconds before reading the metrics.
To collect these values, add the server as a target to the scrape_configs section of your Prometheus configuration:
scrape_configs:
- job_name: "orders"
static_configs:
- targets: ["localhost:8080"]
Prometheus requests /metrics by default, which is the path MetricsEndpoint.withMetrics serves.
Changing the Path, Labels, and Polling Interval
MetricsEndpoint.withMetrics takes named parameters with defaults, so you can override only the ones you need. Here we serve the metrics at /prometheus, add a service="orders" label to every HTTP metric, and poll every five seconds instead of every second:
import zio.metrics.MetricLabel
object Step6CustomizedMetricsExample extends ZIOAppDefault {
val app =
MetricsEndpoint.withMetrics(
OrderRoutes.routes,
metricsPath = "prometheus",
extraLabels = Set(MetricLabel("service", "orders")),
)
val run =
Server
.serve(app)
.provide(Server.default, MetricsEndpoint.layers(pollingInterval = 5.seconds))
}
With this server, GET /metrics returns 404 Not Found and GET /prometheus returns lines such as:
http_requests_total{method="GET",path="/orders/{orderId}",service="orders",status="200"} 1.0 1796060890575
MetricsEndpoint.withMetrics also accepts concurrentRequestsName, totalRequestsName, requestDurationName, and requestDurationBoundaries to rename the three metrics or change the histogram buckets. When you change metricsPath, set metrics_path in the Prometheus scrape configuration to match.
Instrumenting Only Some Routes
MetricsEndpoint.withMetrics instruments every route you pass to it. To leave some routes out, such as a health check that a load balancer calls every few seconds, apply Middleware.metrics() yourself to the routes you want measured and append the metrics route with MetricsEndpoint.endpointRoute:
object Step7SeparateMiddlewareExample extends ZIOAppDefault {
val health: Routes[Any, Response] =
Routes(Method.GET / "health" -> handler(Response.ok))
val app =
(OrderRoutes.routes @@ Middleware.metrics()) ++ health ++ MetricsEndpoint.endpointRoute()
val run =
Server
.serve(app)
.provide(Server.default, MetricsEndpoint.layers())
}
Requests to /health succeed but add no lines to /metrics; requests to /orders are counted as before. MetricsEndpoint.endpointRoute takes the path as its only parameter, with "metrics" as the default.
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/prometheusmetrics/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.prometheusmetrics.<ObjectName>".
Going Further
- The metrics middleware reference shows how to record a custom metric inside a handler with
ZIO#@@; the Prometheus endpoint serves custom metrics alongside the HTTP ones. - The
Middleware.metricsoverload that takesresponseLabelsandpathLabelMapperderives extra labels from each response and rewrites thepathlabel; combine it withMetricsEndpoint.endpointRouteas in the last section. - To send metrics to a backend other than Prometheus, see the ZIO Metrics Connectors documentation.