Client side Prometheus implementation

(Jari (LotU)) #1

Swift Prometheus: Client-side Prometheus implementation in Swift

This module, Prometheus, would include Prometheus metric types for developers to create and use, to serve prometheus formatted metrics any way they want.

A low level Client-Side Prometheus implementation.

A lot of companies and employers don't want their serverside applications running without any sort of insight whatsoever. Prometheus is a Monitoring system used by many big names out there to keep track of what their applications are doing.

This package is a Client-Side implementation of Prometheus, allowing you to serve up Prometheus formatted data that a Server-Side Prometheus application can read out, and store.

There currently are some swift solutions out there that provide Prometheus monitoring, for example SwiftMetrics, but none of them are framework independent, and none of them expose the ability for the end user to add metrics of their own without editing package source.

API Design
Note: All of this is still in early stages, and might very well change based on community input

The Swift Prometheus API is designed to be simple. It has no dependencies, only uses Swift builtin types, and requires no setup.

Using prometheus in your project is as simple as this:

import Prometheus

let counter = Prometheus.shared.createCounter(forType: Int.self, named: "my_counter") // Increment value by 1
// OR use to increment the counter by a given value

// To get a hold of your metrics


In this case, only incrementing the counter once, with a value of 1, this will give the follwing output:

# TYPE my_counter counter
my_counter 1

Also supported are help texts, that can be used to clarify what metric holds what:

import Prometheus

let counter = Prometheus.shared.createCounter(forType: Int.self, named: "my_counter", helpText: "Counts up")


which will result in:

# HELP my_counter Counts up
# TYPE my_counter counter
my_counter 1

An example of how this could end up looking in an application (using Vapor syntax here, but framework should not matter)

import Prometheus

router.get("/status") { req -> String in
    return Prometheus.shared.getMetrics()

Metrics currently supported are:

  • Counter
  • Gauge
  • Histogram
  • Summary
  • Info

To check out the implementations, and full overview of the module, it's on GitHub here

Into the future
Right now, the API I created has some quirks and code I'm not fully happy with. I'll work on cleaning these flaws up, but wanted to share this here already, since the API is functional. Next to that, the code is only partially documented, and has no tests yet. I'll also provide those over the coming week(s)

Next to changes to this module I'll preform, I think it'd be a nice to have, to have default implementations on a per framework basis, covering metrics that most anyone would want, like response times, system information, and other defaults.

Thanks for reading :smile:

(Tanner) #2

Thanks for submitting this pitch @MrLotU. I think a Prometheus client built on Swift NIO would be a great fit in the SSWG project list.

One concern I have with the code example is the use of Prometheus.shared. Does this use locking to achieve thread-safety or will it potentially crash if used cross-thread? I think removing that in favor of initializing instances of Prometheus would be a better approach. I might also call it PrometheusClient to avoid using the same name as the module, since that can cause issues in Swift.

Overall though, I think this is a great proposal and I would love to see it move forward. cc @server-work-group.

(Jari (LotU)) #3

Right now, no. I am investigating this, I’m also not sure if manual initializations will fix this if you use one instance and talk to it from more than one eventloop for example. But the initializer to the class is public, so you can most definitely create your own instances.

For the naming, I agree, so I’ll updat that!

Thanks for your input!

(Tanner) #4

Ah perfect. I would just remove the .shared then. For Vapor, at least, you will want to initialize at least one client per event loop. Probably one client per controller. For other frameworks, you might just initialize a single instance for your whole app. But I would let the user decide how that is done.

(Jari (LotU)) #5

I don’t think you do, since it will not post back metrics from all eventloop instances if you request the prometheus string so to say, which is the reason I went for 1 shared instance

(Tanner) #6

@MrLotU oh I see now. Would there be any reason that you would want to cache the prometheus data anywhere other than application memory? For example, in Redis or memcached or something? Or is the idea with prometheus that you store the results local to the instance, and just gather them from all instances?

If you want to keep the door open to swapping out how the data is stored, you could have two layers like:

  • PrometheusService
  • PrometheusStorage

Where PrometheusStorage is a protocol that can be implemented however the user likes. By default an InMemoryPrometheusStorage is used that takes advantage of locking for thread-safety.

Then PrometheusService accepts a generic PrometheusStorage and provides a nice API for getting / setting data.

Otherwise, if there's no reason for giving the user the option for modifying how Prometheus stores its data, then just one PrometheusService type that is thread-safe would make sense to me. However, I would still avoid using .shared since being static makes dependency trees less clear, and opt for having the user pass around a single instance of PrometheusService.

(Jari (LotU)) #7

@tanner0101 The way prometheus works, you don't want to do persistance on the client side (website/app/service) but on the server side (Prometheus server). See this example:

In this chart, my library would be the green Exporter part, exposing data on a HTTP endpoint that can be scraped by the Prometheus server instance. This server instance will take care of the storage, and will feed into alerting and things like Grafana for visualisation. So there is no need to persist anything on the client side (in my Library).

This is also the reason I went with the .shared approach, since you only want one single truth about your metrics, Prometheus server usually scrapes just one endpoint (in most cases /metrics) so you want ALL your info there. From my perspective, it'd be better to have 1 "shared" but thread safe PrometheusClient class instance, than to have one per .

(Tobias Haeberle) #8

The Prometheus server will scrape a special endpoint on the webserver (E.G. /metrics) in a defined interval (E.G. every 2s) and collect the metrics. Thus it is enough if the application keeps an in memory representation of the last x measurements. But it has to do so for all requests. So you will want to have a single store per server which collects metrics across all event loops. No way around locking here I guess. But I would also remove the shared instance approach. Also it might be nice to actually spawn a separate server on a different port exclusively for metrics. This port could then be exposed only to an internal network and not to the public.