cosmos-sdk
cosmos-sdk copied to clipboard
perf: Pool allocations of cachekv stores
Description
Last week, on April 25, we ran a load test involving close to 40 validators and collected performance metrics from them. One thing that came up is that the cachekv that gets allocated to run each transaction is the top allocator:
My suggested perf improvement is to pool the cache objects themselves, as implemented in this PR. I tried a load test on a small set of nodes to see what this would do, and the result is a reduction in failures per second (i.e. "tx broadcasts that fail") from 96.73 in the baseline:
To 80.72 after this fix:
Note that I opened this against main, but it includes both changes to the sdk itself and to store. Let me know if you'd like this refactored at all, or split into two.
I'll throw the changelog together once I know that we're merging this, and how different bits are getting into different components.
Author Checklist
All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues. Your PR will not be merged unless you satisfy all of these items.
I have...
- [x] included the correct type prefix in the PR title, you can find examples of the prefixes below:
- [ ] confirmed
!in the type prefix if API or client breaking change - [x] targeted the correct branch (see PR Targeting)
- [ ] provided a link to the relevant issue or specification
- [ ] reviewed "Files changed" and left comments if necessary
- [ ] included the necessary unit and integration tests
- [ ] added a changelog entry to
CHANGELOG.md - [ ] updated the relevant documentation or specification, including comments for documenting Go code
- [ ] confirmed all CI checks have passed
Summary by CodeRabbit
-
New Features
- Introduced pooling for cache multi-stores and cache stores to optimize resource usage and reduce memory allocations.
- Added methods to release pooled resources automatically after use, improving resource management and performance.
-
Performance Improvements
- Enhanced cache reset operations to reuse existing data structures instead of reallocating memory, leading to more efficient cache management.
Ironbird - launch a network
To use Ironbird, you can use the following commands:- /ironbird start
OR /ironbird start --load-test-config= - Launch a testnet with the specified chain and load test configuration. - /ironbird chains - List of chain images that ironbird can use to spin-up testnet
- /ironbird loadtests - List of load test modes that ironbird can run against testnet
Custom Load Test Configuration
You can provide a custom load test configuration using the `--load-test-config=` flag:/ironbird start cosmos --load-test-config={
"block_gas_limit_target": 0.75,
"num_of_blocks": 50,
"msgs": [
{"weight": 0.3, "type": "MsgSend"},
{"weight": 0.3, "type": "MsgMultiSend"},
{"weight": 0.4, "type": "MsgArr", "ContainedType": "MsgSend", "NumMsgs": 3300}
]
}
Use /ironbird loadtests to see more examples.
📝 Walkthrough
Walkthrough
A set of changes introduces object pooling for cache multi-stores and cache key-value stores within the application's storage layer. New interfaces and types are defined to support pooled cache stores, including lifecycle management via Release() methods. Constructors and internal logic are updated to utilize object pools, reducing allocations by reusing store instances. Methods for clearing internal data structures are added to facilitate reuse. The transaction execution flow in the base application is updated to leverage pooled cache multi-stores when available, ensuring proper resource cleanup after use. Several method receivers are converted to pointers for consistency and to support pooling.
Changes
| File(s) | Change Summary |
|---|---|
| baseapp/baseapp.go | Introduced poolingStore interface; updated transaction context handling to use pooled cache multi-stores if available; added deferred Release() calls for pooled stores in transaction execution. |
| store/types/store.go | Added new PooledCacheMultiStore interface embedding CacheMultiStore and adding a Release() method. |
| store/cachekv/internal/btree.go | Added Clear() method to BTree type to clear all entries without reallocating. |
| store/cachekv/store.go | Introduced PooledStore struct for pooling; added storePool for managing pooled instances; implemented NewPooledStore() and Release(); updated cache reset logic to clear rather than reallocate BTree. |
| store/cachemulti/store.go | Added PooledStore type for pooled cache multi-stores; implemented pooling via storePool; updated constructors to return pointers; added CacheMultiStorePooled() and Release(); changed method receivers to pointers. |
Sequence Diagram(s)
sequenceDiagram
participant BaseApp
participant MultiStore (poolingStore)
participant PooledCacheMultiStore
participant RegularCacheMultiStore
BaseApp->>MultiStore: cacheTxContext()
alt MultiStore implements poolingStore
MultiStore->>PooledCacheMultiStore: CacheMultiStorePooled()
BaseApp->>PooledCacheMultiStore: use for tx processing
BaseApp-->>PooledCacheMultiStore: defer Release()
else
MultiStore->>RegularCacheMultiStore: CacheMultiStore()
BaseApp->>RegularCacheMultiStore: use for tx processing
end
sequenceDiagram
participant PooledStorePool
participant PooledStore
participant ParentStore
BaseApp->>PooledStorePool: NewPooledStore(parent)
PooledStorePool->>PooledStore: retrieve or create
PooledStore->>ParentStore: set parent reference
BaseApp->>PooledStore: use for caching
BaseApp->>PooledStore: Release()
PooledStore->>PooledStore: reset caches, clear parent
PooledStore->>PooledStorePool: return to pool
✨ Finishing Touches
- [ ] 📝 Generate Docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
🪧 Tips
Chat
There are 3 ways to chat with CodeRabbit:
‼️ IMPORTANT Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai generate unit testing code for this file.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.@coderabbitai read src/utils.ts and generate unit testing code.@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.@coderabbitai help me debug CodeRabbit configuration file.
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (Invoked using PR comments)
@coderabbitai pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile to the root of your repository. - Please see the configuration documentation for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
Documentation and Community
- Visit our Documentation for detailed information on how to use CodeRabbit.
- Join our Discord Community to get help, request features, and share feedback.
- Follow us on X/Twitter for updates and announcements.
@fastfadingviolets The optimization is related to memory allocation and garbage collection, but the metrics you shared are from Locust, so it's a bit hard to grasp the direct impact on memory and GC.
Would it be possible to share metrics specifically related to memory and GC as well? I’m curious to see the quantitative improvements, if any.
@fastfadingviolets The optimization is related to memory allocation and garbage collection, but the metrics you shared are from Locust, so it's a bit hard to grasp the direct impact on memory and GC.
Would it be possible to share metrics specifically related to memory and GC as well? I’m curious to see the quantitative improvements, if any.
absolutely! Let me share some graphs here. I ran two half-hour load tests; you'll see two big humps in my graph. The first one is without the optimization, the second one's with it.
First, rates of objects being allocated go down from ~1.4M to ~1.1M:
Allocation rates (i.e. same thing but in MB) goes from ~100MB/s to ~80MB/s:
Annoyingly, the GC histogram seems to show GCs getting longer with the fix, but I think that that's because we're doing fewer garbage collections, and so there's more to collect. This graph doesn't have the 99th percentile:
The 99th percentile goes up pretty significantly (it's likely this is also affected by startup operations, though):
However! If I look at the CPU profile, I can see we're spending less time in garbage collection overall, by about 8%, which would be consistent with the theory that we're just doing fewer GCs:
Lastly, just for the heck of it, we went from cacheTxContext being responsible for 12% of objects allocated to <0.1%:
This translates to about 10% fewer allocated objects in runTx:
Let me know if you'd like me to collect any more metrics!
@fastfadingviolets we will need a changelog in both the root CHANGELOG.md and the one in ./store
@aljo242 added changelog stuff & i think i've incorporated all your comments! I'm assuming this is gonna get squashed so I'm just pushing new commits, but lmk if you want me to squash them myself
adding @aaronc to take a look
@fastfadingviolets we have some conflicts
@aaronc just wondering if you've had a chance to take a peek at this!
Didn't review changes in detail (tbh sending it on a live node and seeing if things run seems easiest. Alternatively just that nested cache kv stores work properly)
Been wanting a change like this for a long time to improve perf, so really supportive of it getting in!
@fastfadingviolets looks like there are some conflicts
What does ironbird do? Is it open source? If it is not open source how are the metrics meaningful to third party users?
First of all I think this is a great pull request
Secondly is ironbird open source?
Thirdly what a cool name, though I prefer the name meteorite
It reminds me that we solved similar issues using lazy init:
https://github.com/crypto-org-chain/cosmos-sdk/pull/248
https://github.com/crypto-org-chain/cosmos-sdk/pull/242
@fastfadingviolets conflicts here! we'd like to get this in!