runtime: IOptionsSnapshot is very slow
This came up after a perf investigation on a recently refactored endpoint. Moving us back from IOptionsSnapshot to IOptionsMonitor knocked off ~100us, nothing else changed.
This option type of ours is fairly costly to create and looking into OptionsManager<TOptions> showed an obvious clue why we saw issues. OptionsManager does not just cache the instance for the duration of the DI scope but it also creates from scratch an instance through the factory per scope.
Looking through the docs this is vaguely alluded to (though there are contra-indicators) but after doing a search on SO and blogs on the subject most users seem to focus entirely on the ‘you get a constant value during a scope/request’ aspect of it.
As nobody (famous last words) seems to care whether it is entirely recreated my question would be:
Why doesn’t OptionsManager<TOptions> cache the result of an IOptionsMonitor.Get call? (leaving out the backwards compatibility part for the sake of argument)
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 4
- Comments: 48 (28 by maintainers)
Right. We should consider changing the implementation so that it caches the currently cached value so scoped services are a consistent view of the data but there’s no need to recompute if nothing changes
IOptionsSnapshot can’t use IOptionsMonitor. In fact, we tried to do that in .NET 7 and it is a major breaking change. IOptionsSnapshot supports injecting scoped
IConfigureOptions<T>. That’s the problem.The combination of IOptionsSnapshot with uncached configuration binding is a performance pit of failure worth investigating. Specifically, the problem is that calling:
@deeprobin I think the bottleneck is this: #33954. And if we use
IOptionsSnapshot, it runs on every request. If we useIOptionsMonitor, it runs once, and then it’s cached until the configuration is changed (and reloaded). I encourage you to try this with IConfiguration that contains several thousand key-value pairs (and nesting, etc.)I agree, alright will be cooking it up.
If we are talking specifically about IOptionsSnapshot, that was intended to be really the no-caching you get a really new fresh instance on every scope, so it literally was intended to recompute everything on every request
In our production environment, the configuration isn’t as large as in the example above. The significant optimization in production (> 100x) is due to the absence of Config Code Gen by default, the fact that the service still uses .NET 6, and our use of DeepCloner instead of serialization and deserialization (which can be much faster in many common cases). Btw, the example above has thousands of lines, which may be rare, but it is not “deep” (only 3-4 levels).
I can provide a simpler example to show the issue (with enabled config code gen). Consider a configuration containing only int properties, without any custom types. Below are the benchmark results for configurations with 1,000 int properties and 100 int properties.
In this case, the performance difference between configuration binding with code gen and json serialization isn’t significant. However, json serialization is not well-suited for deep cloning. Using real deep cloning shows a performance improvement of hundreds of times. I think maybe we can use code gen to do the deep clone for us.
I don’t think it’s out of the ordinary to have some pretty complicated configuration files. It’s common to utilize several configuration sources. And Microsoft encourages usage of configuration for more than just IOptions.
For instance Microsoft feature management (feature flags) relies on it: https://learn.microsoft.com/en-us/azure/azure-app-configuration/feature-management-dotnet-reference
Performance Comparison Between IOptionsSnapshot and IOptionsMonitor with Deep Cloning
We’ve obviously had a long discussion here. If I understand correctly, ensuring that each scope’s configurations remain independent—allowing modifications in different scopes—makes it challenging to have caching. However, I want to raise something new here.
Issue: In our distributed .NET application, using
IOptionsSnapshotto handle complex configurations for each user (for A/B tests, so each request has a isolated settings and we overwrite them with different experiment config overwrites) has led to performance bottlenecks. Profiling revealed that configuration binding was consuming approximately 16% of the total CPU workload.Key Observation: Despite our assumption that
IOptionsSnapshot’s performance should be comparable to deserializing the configuration from a string for each request, this was not the case in fact. Simplified benchmark test results showed a 10x gap in cpu and memory allocations (see code at the bottom), and in our production environment with more complex configurations, the gap widened to over 100x.Specifically, we benchmarked
IOptionsSnapshotagainst a custom solution that usedIOptionsMonitorand deep cloning of the configuration for each request (using serialization and deserialization, which is clearly not optimal and only for testing purposes):Solution: We switched to using
IOptionsMonitor, and performed deep cloning with a third-party library (DeepCloner). This reduced real CPU workload by 16% and memory allocation by 12%. The configuration-related CPU and memory allocation overheads were reduced by hundreds of times. The one line code change was as follows:I believe these two lines are actually behave the same way, cloning and create a isolated scope level configuration which can be changed and will only have impacts inside the scope. I understand the runtime lacks a generic deep clone implementation, but isn’t the performance gap of IOptionsSnapshot so extreme? I believe there must be some room for improvement. If it’s impossible, maybe we should just never use IOptionsSnapshot in any cases. The configuration builder bind methods are too expensive. Any thoughts on this?
Benchmark code:
This came up again today and to move this forward without breaking changes is to Iintroduce IOptionsMonitorSnapshot<T> that was what the original fix by @NinoFloris had. This new type would be scoped and would read the current value from
IOptionsMonitor<T>. This solves the performance issues with IOptionsSnapshot because it doesn’t do anything but cache the last value (which itself is cached and only changes when config changes).The biggest performance challenge is the mixing
IOptionSnapshot<T>with any expensive operation inIConfigureOptions<T>. The most common problem is running configuration binding per scope (usually per request in asp.net core). We want to cache the configuration that was bound until it changes, applying those cached values to the object. This is a difficult to do efficiently and would require codegen to make it fast (basically generating left hand right handcode to copy values):Yes it’s a workaround that we can’t ship but you can use in your apps if they don’t hit this scenario
This is a similar solution that I implemented as a workaround for issue in our code. I ended up writing an extension to provide a custom binder, and wrote some binders by hand that were written for the exact types used. It performed very well.
A source generator that will generate similar code as the one I wrote by hand sounds like a very good solution to me.
@davidfowl that was an honest question, I would like to fix it up but suggestions are welcome.
Yes this is a known issue https://github.com/dotnet/runtime/issues/42222. IOptionsSnapshot is currently a performance trap.
Agreed that this implementation would have been more efficient. My only guess as to why it was done this way was because we had unified IOptions and IOptionsSnapsot implementations via the OptionsManager (though that’s now changed in .NET 6).
The sad truth is that it would have been fixed if our own components were using it.
I’d be willing to take this change and see if there was any real impact not re-running factories per request. There are some very subtle differences but maybe worth the break.
cc @HaoK to see if he remembers why it was done this way.