Skip to content

Performance: New storage engine for stats, with improved key management - #687

Merged
zbjornson merged 16 commits into
prometheus:masterfrom
jdmarshall:perf/storage
Jul 25, 2025
Merged

zbjornson merged 16 commits into
prometheus:masterfrom
jdmarshall:perf/storage

Conversation

@jdmarshall

@jdmarshall jdmarshall commented Jul 8, 2025 •

Copy link
Copy Markdown
Contributor

This change consolidates a lot of util code into a single object that can guarantee that the functionality is all used consistently, which gets the metrics out of the job of managing labelNames and their sorting.

This results in a 20-45% improvement in benchmark time for most of the metric types. Gauges with no labels act weird, but if you disable the counter tests this mostly goes away, suggesting testing artifacts. The benefits are more substantial for metrics with label (which IME is 'every singe metric you have', but may result in a slight decline in the no-label path.

However, since the no-label path has historically been nearly 500 times faster than the label scenario, this is not a real problem. The amortized cost of the entire system is greatly reduced by optimizing for the common case over the rare.

What's it do?

This PR introduces a data structure that owns both the labels and the metrics that correspond with them. It encapsulates all of the lifecycle operations in a single class, which means internal implementation details can be adjusted in the future to explore further improvements. For example, moving validateLabels into the receiving functions and changing the key structure in arbitrary ways, including possibly turning it into an array to reduce string fragment duplication.

The brunt of this PR, besides adding lots of additional benchmarks and culling some other ones to keep the total run time not insane, is this:

  • All possible keys for a metric are known at creation time
  • new values can show up arbitrarily
  • the store becomes a cartesian product of all values for the given keys

You can think of this as a matrix or a table

| label1        |        label2 |        label3 |
| ------------- | ------------- | ------------- | 
|      -        |      200      |     'get'     |
|    orange     |       -       |       -       |
|     blue      |      403      |       -       |

The keys are a sparse list of hits with '' serving as all empty elements, resulting in the following keys for the example above:

  • |200|get instead of label2:200,label3:get,
  • orange|| instead of label1:orange,
  • blue|403| instead of label1:blue,label2:403,

In my experience the tags can be at least as long as the values, and a substantial fraction of tags that can be set will be set, so I believe this will be a net substantial reduction in memory usage.

Structured this way, we can experiment with different solutions. A tree structure? sorting keys by a different order, etc.

What about pipes in the data causing key collisions?

The existing system has the same problem with ':', but worse, because both the keys and values can contain colons. which is a legal character in key names in prometheus., For pipes to cause a problem here, you need two consecutive columns with repeating values, such that for instance 'a' and 'a|b' are legal values in one column, and 'c' and 'b|c' are legal values in the consecutive columns. Essentially you need to generate extra pipes with common substrings in two columns to cause the values to collide.

If this is seen as a problem, we could prometheus-escape the values before inserting them, but that will erode a little of the performance gain by causing an encode on every read operation. We could investigate other options at a later date, as the key structure is, as I mentioned already, now an internal implementation detail.

Note that this branch shares some benchmark-related commits in common with #683 and #680. If either of those merge, this PR will get a lot smaller.

@jdmarshall jdmarshall changed the title New storage engine for stats, with improved key management Performance: New storage engine for stats, with improved key management Jul 8, 2025

@SimenB SimenB left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a big fan of these changes, thanks for working on them 😀

Comment thread lib/util.js Resolved
Comment thread lib/cluster.js Resolved
Comment thread lib/metricAggregators.js Resolved
Comment thread lib/registry.js Resolved
@jdmarshall

jdmarshall commented Jul 8, 2025 •

Copy link
Copy Markdown
Contributor Author

This PR has now been rebased on top of all of my other changes. I had not done this for a few days and several PRs due to the complexity of managing so many parallel before due to an excess of irons in fires.

⚠ counter ➭ inc is 9.359% acceptably slower.
✓ counter ➭ inc with labels is 77.53% faster.
✓ counter ➭ new is 0.2323% faster.
✗ gauge ➭ inc is 40.29% slower.
✓ gauge ➭ inc with labels is 50.06% faster.
✓ histogram ➭ observe#1 with 64 is 58.85% faster.
✓ histogram ➭ observe#2 with 8 is 39.22% faster.
✓ histogram ➭ observe#2 with 4 and 2 with 2 is 72.32% faster.
✓ histogram ➭ observe#2 with 2 and 2 with 4 is 72.89% faster.
✓ histogram ➭ observe#6 with 2 is 79.01% faster.
✓ histogram ➭ startTimer#1 with 64 is 26.64% faster.
✓ histogram ➭ startTimer#2 with 8 is 22.71% faster.
✓ histogram ➭ startTimer#2 with 4 and 2 with 2 is 54.11% faster.
✓ histogram ➭ startTimer#2 with 2 and 2 with 4 is 40.53% faster.
✓ histogram ➭ startTimer#6 with 2 is 45.02% faster.
✓ summary ➭ observe#1 with 64 is 24.94% faster.
✓ summary ➭ observe#2 with 8 is 12.19% faster.
✓ summary ➭ observe#2 with 4 and 2 with 2 is 33.54% faster.
✓ summary ➭ observe#2 with 2 and 2 with 4 is 32.09% faster.
✓ summary ➭ observe#6 with 2 is 42.18% faster.
✓ registry ➭ getMetricsAsJSON() no labels is 33.17% faster.
✓ registry ➭ getMetricsAsJSON() 1 x 64 is 37.12% faster.
⚠ registry ➭ getMetricsAsJSON() 2 x 4 is 1.405% acceptably slower.
✓ registry ➭ getMetricsAsJSON() 2 x 8 is 25.64% faster.
⚠ registry ➭ getMetricsAsJSON() 6 x 2 is 0.8058% acceptably slower.
✓ registry ➭ getMetricsAsJSON() 2 x 4, 2 defaults is 18.81% faster.
✓ registry ➭ getMetricsAsJSON() 2 x 2, 4 defaults is 16.77% faster.
✓ registry ➭ metrics() no labels is 32.44% faster.
✓ registry ➭ metrics() no labels and openMetrics is 30.84% faster.
✓ registry ➭ metrics() 1 x 64 is 1.049% faster.
✗ registry ➭ metrics() 1 x 64 and openMetrics is 34.15% slower.
⚠ registry ➭ metrics() 2 x 4 is 4.388% acceptably slower.
✗ registry ➭ metrics() 2 x 4 and openMetrics is 36.92% slower.
✓ registry ➭ metrics() 2 x 8 is 17.93% faster.
⚠ registry ➭ metrics() 2 x 8 and openMetrics is 1.079% acceptably slower.
✗ registry ➭ metrics() 6 x 2 is 32.61% slower.
✓ registry ➭ metrics() 6 x 2 and openMetrics is 21.96% faster.
✓ registry ➭ metrics() 2 x 4, 2 defaults is 22.15% faster.
✓ registry ➭ metrics() 2 x 4, 2 defaults and openMetrics is 21.87% faster.
✓ registry ➭ metrics() 2 x 2, 4 defaults is 49.21% faster.
✓ registry ➭ metrics() 2 x 2, 4 defaults and openMetrics is 22.96% faster.
✓ cluster ➭ aggregate() is 18.17% faster.

I would estimate that at around ~30% improvement on average, and up to 70% for particularly slow paths.

Actual numbers on the slower metrics:

- counter ➭ inc ➭ prom-client@current x 12,403,052 ops/sec ±2.72% (86 runs sampled)
- counter ➭ inc ➭ prom-client@latest x 13,563,832 ops/sec ±0.25% (90 runs sampled)

The scenarios I've seen in working grafana dashboards are in some cases up to 500x slower than these fictional benchmarks that don't run the label code at all. These changes get that under 400x. But I strongly feel that for this project to be great, we need to get that ratio down below 100x.

The remainder of the 'slower' benchmarks do not reproduce these warnings when run indepently.

In the full suite:

- gauge ➭ inc ➭ prom-client@current x 4,714,826 ops/sec ±42.53% (61 runs sampled)
- gauge ➭ inc ➭ prom-client@latest x 6,614,529 ops/sec ±0.66% (86 runs sampled)
- registry ➭ metrics() 1 x 64 ➭ prom-client@current x 1,885 ops/sec ±1.06% (81 runs sampled)
- registry ➭ metrics() 1 x 64 ➭ prom-client@latest x 1,865 ops/sec ±1.24% (81 runs sampled)
- registry ➭ metrics() 1 x 64 and openMetrics ➭ prom-client@current x 1,501 ops/sec ±38.94% (57 runs sampled)
- registry ➭ metrics() 1 x 64 and openMetrics ➭ prom-client@latest x 2,014 ops/sec ±1.61% (86 runs sampled)

Run as a single file:

- gauge ➭ inc ➭ prom-client@current x 14,877,853 ops/sec ±0.35% (86 runs sampled)
- gauge ➭ inc ➭ prom-client@latest x 14,394,694 ops/sec ±0.82% (91 runs sampled)
- registry ➭ metrics() 1 x 64 ➭ prom-client@current x 2,955 ops/sec ±0.45% (90 runs sampled)
- registry ➭ metrics() 1 x 64 ➭ prom-client@latest x 2,927 ops/sec ±0.31% (91 runs sampled)
- registry ➭ metrics() 1 x 64 and openMetrics ➭ prom-client@current x 2,937 ops/sec ±0.48% (90 runs sampled)
- registry ➭ metrics() 1 x 64 and openMetrics ➭ prom-client@latest x 2,849 ops/sec ±0.47% (91 runs sampled)```

I suspect GC and object retention. Notice how the numbers for the second run are universally almost double of the full run.

I tweaked these metrics() setup to punish #684 severely, and I suspect this is the reason these numbers are so very low, for both versions of the code. I think someone can probably boost that by 2-3x.

@jdmarshall

Copy link
Copy Markdown
Contributor Author

Also found why the benchmarks got slow - Counter.new test was not giving Counter a Registry, so they were all collecting in the global registry.

@jdmarshall

Copy link
Copy Markdown
Contributor Author

Something went sideways with rebasing. Trying again.

This should help with further optimizations, especially for cluster.js
I believe I see some perf issues with default labels and I'd like to
explore those.

Increases code coverage by .6%, but branch coverage by 1.2%

File                             | % Stmts | % Branch | % Funcs | % Lines |
---------------------------------|---------|----------|---------|---------|
All files                        |   51.78 |    28.35 |    48.8 |   52.45 |
All files                        |   52.36 |    29.55 |   49.14 |   53.05 |

Relates to prometheus#676
…rmats.

getMetricsAsJSON and getMetricsAsString use different mechanisms
to merge in default labels. It turns out that the getMetricsAsJSON
version is substantially faster.

... except in how it short circuits out of the inner loop.

✓ registry ➭ getMetricsAsJSON#2 x 4, 2 defaults is 21.55% faster.
✓ registry ➭ getMetricsAsJSON#2 x 2, 4 defaults is 22.69% faster.
✓ registry ➭ metrics#2 x 4, 2 defaults is 26.95% faster.
✓ registry ➭ metrics() 2 x 4, 2 defaults and openMetrics is 25.78% faster.
✓ registry ➭ metrics#2 x 2, 4 defaults is 25.53% faster.
✓ registry ➭ metrics() 2 x 2, 4 defaults and openMetrics is 26.98% faster.
Comment thread benchmarks/counter.js
name: `Counter${count++}`,
help: 'Counter',
labelNames,
registers: [registry],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where all the memory went in the benchmarks. Global registry was full of these and speeding up the code just made it worse.

@zbjornson zbjornson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice improvements to the benchmark quality. 👍

Comment thread lib/registry.js Resolved
@jdmarshall

Copy link
Copy Markdown
Contributor Author

Update: I'm seeing slightly less rosy numbers today and cannot nail down why. 30% has become 25% and 75% has become 55%. Thought it might have something to do with the lower max-heap-size on the final commit, but it seems not.

Break label reuse in the registry tests to demonstrate the cache
lookup bug I discovered. (prometheus#684)

Change 'no label' gauge.inc call to drop the label variable, forcing
the argument defaulting logic to run.
Prep for reworking aggregate()
This is a very small perf improvement, and I suspect it's mostly
down to GC pressure.

Relates to prometheus#611

reduces GC events by ~2%
By requiring 'sortedLabelNames' to be available, we can generate much
shorter keys for the tables. This should help a great deal with prometheus#611

Unfortunately this cannot simply be fixed with changes to hashObject()
because this implementation detail has leaked out across the entire
codebase. So a new implementation that can be subbed into Metrics one
implementation at a time (they all deal with entry.value in a unique
way)
This change reduces the memory required for Map keys, which should
help with prometheus#611

✓ summary ➭ observe#1 with 64 is 37.52% faster.
✓ summary ➭ observe#2 with 8 is 29.74% faster.
✓ summary ➭ observe#2 with 4 and 2 with 2 is 45.97% faster.
✓ summary ➭ observe#2 with 2 and 2 with 4 is 45.28% faster.
✓ summary ➭ observe#6 with 2 is 48.77% faster.
before:

✓ counter ➭ new is 28.65% faster.
⚠ counter ➭ inc is 6.514% acceptably slower.
✗ counter ➭ inc with labels is 26.74% slower.

after:
✓ counter ➭ new is 22.44% faster.
⚠ counter ➭ inc is 8.284% acceptably slower.
✓ counter ➭ inc with labels is 52.40% faster.
Begin moving validateLabels() logic into LabelMap, where it can
use a Set for the comparison (since it's only calculated once)

before:

⚠ gauge ➭ inc is 7.155% acceptably slower.
✗ gauge ➭ inc with labels is 28.19% slower.
And thus ends the rollout of the new storage engine.

✓ histogram ➭ observe#1 with 64 is 26.15% faster.
✓ histogram ➭ observe#2 with 8 is 27.44% faster.
✓ histogram ➭ observe#2 with 4 and 2 with 2 is 43.99% faster.
✓ histogram ➭ observe#2 with 2 and 2 with 4 is 43.75% faster.
✓ histogram ➭ observe#6 with 2 is 51.10% faster.
@jdmarshall

jdmarshall commented Jul 12, 2025 •

Copy link
Copy Markdown
Contributor Author

I took the await change out of this PR. It will resurface as a 'niceness' PR for cluster and worker threads later.

I now have 3 other dependent PRs ready to go for when this one lands. Including a 2.4x improvement to clusterMetrics() by applying the same change to metricAggregators.js

@jdmarshall

Copy link
Copy Markdown
Contributor Author

@zbjornson @SimenB Comments have been addressed.

@SimenB SimenB left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great stuff! Thanks for working on it

Comment thread lib/counter.js
entry.value += value;
} else {
hashMap.set(hash, { value, labels });
this.store.validate(labels); //TODO: this isn't really necessary is it?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems fine for consistency?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can’t remove what isn’t there.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an aside, I've gone back and forth on where the responsibility for validate should lie.

As I was writing this PR, I had the thought, "You know as a follow-on maybe I should fold the validate call into LabelMap.set/setDelta". And that lasted until I got to the labels() methods, and the timer methods in one/a couple of the metrics.

Strictly speaking, we could validate the labels in the labels call, and then skip them for the functions attached to the object returned by these functions. However the whole inc/incWithExemplars, observe/observeWithExemplars trick would make that difficult to unravel. I think there are a lot of other concerns being juggled here and while there's an opportunity to make correctness and performance not fight by inverting some of the code here.

It's probably not impossible, but my my head is pretty full trying to keep the PRs I already have ready to go, straight.

Comment thread lib/gauge.js Outdated
labels = getLabelArg(labels);
if (value === undefined) value = 1;
setDelta(this, labels, value);
setDelta(this, labels, value ?? 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also now handles null. Should it? I guess it makes sense

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of the other files does both for some reason.

Comment thread lib/gauge.js Resolved
Comment thread lib/gauge.js Resolved
Comment thread lib/metric.js
this.sortedLabelNames = [];
}

// TODO: Bad things happen when you call functions on half-initialized objects, yo

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the alternative? Moving it last?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this is a deeper architectural problem. It would require modifying the entire inheritance tree. If this were a threaded language the blast radius would be a lot larger, but even here you have re-entrancy problems.

Which is why the code has to double-initialize the hashMap/storage in most of the Metrics. The reset call expects the storage to be defined already but we are still in the super() call. Calling a method named 'init' from a constructor... happens. But a function called reset? I haven't even finished setting yet.

This is partially spit-balling, I probably should think about this longer before answering, but I suspect the solution is extract a function from reset() to handle the no-label case, call it from the constructor and drop the reset call entirely from Metric.

It might be worth pointing out that several people have taken exception in the issues database for how labelless stats are initialized. But I haven't looked at them long enough to be sure if that's a "change the default value" or "remove the special case entirely". If it's the latter then the correct answer is "delete the code"

Comment thread lib/util.js Resolved
@SimenB
SimenB requested a review from zbjornson July 16, 2025 16:00

@zbjornson zbjornson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good!

@zbjornson

Copy link
Copy Markdown
Contributor

Sorry @jdmarshall, another PR was merged and created a small conflict. If @siimon is okay with it, I think we should remove the changelog reminder and have mergers maintain the changelog instead.

Once that's fixed and @SimenB is good with the revisions, happy to merge.

@jdmarshall

Copy link
Copy Markdown
Contributor Author

I fixed the changelog

@jdmarshall

Copy link
Copy Markdown
Contributor Author

I have some other PRs lined up behind these, and I’m getting a little fuzzy on them since I’ve been working in other things. There are two approvals on this, yes?

@zbjornson
zbjornson merged commit 49d6e76 into prometheus:master Jul 25, 2025
@jdmarshall

Copy link
Copy Markdown
Contributor Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants