Video in progress

A gauge was registered in Micrometer, but after a while Prometheus started showing NaN. What could be the cause?

A Micrometer gauge holds only a weak reference to the observed object. If no other strong reference to that object remains, the GC collects it and the gauge returns NaN.

📖 Answer

The classic mistake:

public void registerMetrics(MeterRegistry registry) {
    AtomicInteger active = new AtomicInteger(); // local variable
    registry.gauge("sessions.active", active);
    // the method ended: nobody references active anymore
}

For a few minutes everything works, then after the first GC sessions_active turns into NaN. Micrometer does this so a gauge doesn't hold on to the observed object forever and cause a memory leak.

The fix is to keep the object in a field:

@Component
public class SessionMetrics {
    private final AtomicInteger active;

    public SessionMetrics(MeterRegistry registry) {
        this.active = registry.gauge("sessions.active", new AtomicInteger(0));
    }

    public void onLogin()  { active.incrementAndGet(); }
    public void onLogout() { active.decrementAndGet(); }
}

registry.gauge(...) returns that same object, so store it in a field. Or you can ask for a strong reference with Gauge.builder(...).strongReference(true).

One more difference: a counter counts "what happened", a gauge asks "how many are there now". You don't set a gauge's value yourself: Micrometer reads it through a function at scrape time.