<h1>Context</h1>
<p>We have a Spring Boot application, deployed into K8s cluster (with 2 instances) configured with Micrometer exporter for Prometheus and visualization in Grafana.</p>
<h2>My custom metrics</h2>
<p>I've implemented couple of additional Micrometer metrics, that report some information regarding business data in the database (PostgreSQL) and I could see those metrics in Grafana, however separately for each pod.</p>
<h1>Problem:</h1>
<p>For our 2 pods in Grafana - I can see separate set of same metrics and the most recent value can be found by choosing (by label) one of the pods.</p>
<p>However there is no way to tell which pod reported the most recent values.</p>
<p><strong>Is there a way to somehow always show the metrics values from the pod that was scraped last (ie it will contain the most fresh metric data)?</strong></p>
<p>Right now in order to see the most fresh metric data - I have to switch pods and guess which one has the latest values.</p>
<p>(The metrics in question relate to database, therefore yielding the same values no matter the pod from which they are requested.)</p>

<p>In Prometheus, you can obtain the labels of the latest scrape using <code>topk()</code> and <code>timestamp()</code> function:</p>
<pre><code>topk(1,timestamp(up{job=&quot;micrometer&quot;}))
</code></pre>
<p>This can then be used in Grafana to populate a (hidden) variable containing the instance name:</p>
<pre><code>Name: instance
Type: Query
Query: topk(1,timestamp(up{job=&quot;micrometer&quot;}))
Regex: /.*instance=&quot;([^&quot;]*)&quot;.*/
</code></pre>
<p>I advise to active the refresh on <code>time range change</code> to get the last scrape in your time range.</p>
<p>Then you can use the variable in all your dashboard's queries:</p>
<pre><code>micrometer_metric{instance=&quot;${instance}&quot;}
</code></pre>
<hr />
<p>EDIT: requester wants to update it on each data refresh</p>
<p>If you want to update it on each data refresh, it needs to be used in every query of your dashboard using <a href="https://prometheus.io/docs/prometheus/latest/querying/operators/#logical-set-binary-operators" rel="nofollow noreferrer">AND logical operator</a>:</p>
<pre><code>micrometer_other_metric AND ON(instance) topk(1,timestamp(up{job=&quot;micrometer&quot;}))
</code></pre>
<blockquote>
<p>vector1 AND vector2 results in a vector consisting of the elements of vector1 for which there are elements in vector2 with exactly matching label sets. Other elements are dropped.</p>
</blockquote>
