Home > Blockchain >  spring boot metrics and are they thread safe
spring boot metrics and are they thread safe

Time:12-21

I have the following counter i use in my spring boot class, i am counting the number of requests for certain resource

@Bean
public Counter myCounter(MeterRegistry meterRegistry) {
    return Counter.builder("mycounter")
            .register(meterRegistry);
}

What i wanted to know would this cause any issues in terms of threading when i inject this counter into my class and call increment. I read it uses atomic data structure under the hood?

How about across multiple services? Prometheous should be sync the counters i think.

CodePudding user response:

Micrometer documentation doesn't say anything about the thread safety. Therefore I would assume, that it depends on the meter registry. At least Prometheus Counters are thread safe (checked in the code). PrometheusCounter is using DoubleAdder for counting:

One or more variables that together maintain an initially zero double sum. When updates (method add) are contended across threads, the set of variables may grow dynamically to reduce contention. Method sum (or, equivalently doubleValue) returns the current total combined across the variables maintaining the sum. The order of accumulation within or across threads is not guaranteed. Thus, this class may not be applicable if numerical stability is required, especially when combining values of substantially different orders of magnitude. This class is usually preferable to alternatives when multiple threads update a common value that is used for purposes such as summary statistics that are frequently updated but less frequently read. This class extends Number, but does not define methods such as equals, hashCode and compareTo because instances are expected to be mutated, and so are not useful as collection keys.

Regarding the metrics across multiple services, the Metric collection in Prometheus is safe to be used by multiple services. However I would suggest using different Tag values to identify each service (i.e. service=service1, service=service2 ...).

  • Related