opentelemetry-rust icon indicating copy to clipboard operation
opentelemetry-rust copied to clipboard

Guidance on Reusing Metric Counters Globally

Open michaeljtang opened this issue 10 months ago • 1 comments

From reading the docs, I am having trouble understanding the best practices guidance for reusing of Counters in opentelemetry::metrics when using a global meter provider. I am specifically using the regular counters, and not the observable ones.

My scenario is as follows: I am using a global meter provider via global::meter(). Having global access to metrics is ideal for me as I am using the actor framework and this makes it easier for me to push the metrics across different actors. However, there is no equivalent function for creating a global counter, so it seems to me that the options are to either:

  1. Recreate and drop each counter using the global meter provider every time I use it.
  2. Create on startup and then manually pass these counters throughout my application.
  3. Store my counters as global variables and access these when I want to push a metric.

Option 2 seems to defeat the purpose of using a global meter provider, and Option 3 is not ideal as I don't want to myself maintain global variables in my application. In regards to Option 1, the docs state:

If a [Counter] needs to be shared, users are recommended to clone the [Counter] instead of creating duplicate [Counter]s for the same metric. Creating duplicate [Counter]s for the same metric could lower SDK performance.

However, pushing to duplicate counters is a slightly different scenario from dropping/re-creating the same counters, as in general duplicate counters will not exist at the same time. So I am not sure if this guidance is concerned specifically with pushing to duplicate counters from different threads, and if the overhead of recreating the counter each time is enough to be a performance concern.

My question is, what is the best practice in this scenario, where I want to be able to globally access my different Counters?

michaeljtang avatar Apr 21 '25 19:04 michaeljtang

I am also having the same question after searching for a while and ending up with no result. However, the source code of the Counter shows that it is a wrapper of an Arc which means it should be safe to make multiple clone of it and share/move them even across multiple threads. So I guess the recommended approach would be somewhat similar to your option 2 and option 3 where we store it either as a global variable or as a state variable in the application. Not sure if this is correct as I am also trying to figure this out. It would be great if any member or maintainer could show up and clarify this.

ChaserZ98 avatar May 28 '25 08:05 ChaserZ98