<p>I'd like to get the 0.95 percentile memory usage of my pods from the last x time. However this query start to take too long if I use a 'big' (7 / 10d) range.</p>

<p>The query that i'm using right now is:</p>

<pre><code>quantile_over_time(0.95, container_memory_usage_bytes[10d])
</code></pre>

<p>Takes around 100s to complete</p>

<p>I removed extra namespace filters for brevity</p>

<p>What steps could I take to make this query more performant ? (except making the machine bigger)</p>

<p>I thought about calculating the 0.95 percentile every x time (let's say 30min) and label it <em>p95_memory_usage</em> and in the query use <em>p95_memory_usage</em> instead of <em>container_memory_usage_bytes</em>, so that i can reduce the amount of points the query has to go through.</p>

<p>However, would this not distort the values ?</p>

RVandersteen
<p>As you already observed, aggregating quantiles (over time or otherwise) doesn't really work.</p>

<p>You could try to build a histogram of memory usage over time using recording rules, looking like a "real" Prometheus histogram (consisting of <code>_bucket</code>, <code>_count</code> and <code>_sum</code> metrics) although doing it may be tedious. Something like:</p>

<pre><code>- record: container_memory_usage_bytes_bucket
  labels:
    le: 100000.0
  expr: |
    container_memory_usage_bytes &gt; bool 100000.0
      +
    (
      container_memory_usage_bytes_bucket{le="100000.0"}
        or ignoring(le)
      container_memory_usage_bytes * 0
    )
</code></pre>

<p>Repeat for all bucket sizes you're interested in, add <code>_count</code> and <code>_sum</code> metrics.</p>

<p>Histograms can be aggregated (over time or otherwise) without problems, so you can use a second set of recording rules that computes an increase of the histogram metrics, at much lower resolution (e.g. hourly or daily increase, at hourly or daily resolution). And finally, you can use <code>histogram_quantile</code> over your low resolution histogram (which has a lot fewer samples than the original time series) to compute your quantile.</p>

<p>It's a lot of work, though, and there will be a couple of downsides: you'll only get hourly/daily updates to your quantile and the accuracy may be lower, depending on how many histogram buckets you define.</p>

<p>Else (and this only came to me after writing all of the above) you could define a recording rule that runs at lower resolution (e.g. once an hour) and records the current value of <code>container_memory_usage_bytes</code> metrics. Then you could continue to use <code>quantile_over_time</code> over this lower resolution metric. You'll obviously lose precision (as you're throwing away a lot of samples) and your quantile will only update once an hour, but it's much simpler. And you only need to wait for 10 days to see if the result is close enough. (o:</p>
