cosmos-sdk icon indicating copy to clipboard operation
cosmos-sdk copied to clipboard

perf: Pool allocations of cachekv stores

Open fastfadingviolets opened this issue 6 months ago • 11 comments

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:

Screenshot 2025-04-29 at 11 38 07 AM

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:

Screenshot 2025-04-29 at 11 46 44 AM

To 80.72 after this fix:

Screenshot 2025-04-29 at 11 47 18 AM

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.

fastfadingviolets avatar Apr 29 '25 15:04 fastfadingviolets

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.

ironbird-prod[bot] avatar Apr 29 '25 15:04 ironbird-prod[bot]

📝 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.

❤️ Share
🪧 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 @coderabbitai in 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 @coderabbitai in 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 pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file 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.

coderabbitai[bot] avatar Apr 29 '25 15:04 coderabbitai[bot]

@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.

zsystm avatar May 07 '25 22:05 zsystm

@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:

Screenshot 2025-05-12 at 2 20 50 PM

Allocation rates (i.e. same thing but in MB) goes from ~100MB/s to ~80MB/s:

Screenshot 2025-05-12 at 2 21 36 PM

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:

Screenshot 2025-05-12 at 2 27 18 PM

The 99th percentile goes up pretty significantly (it's likely this is also affected by startup operations, though):

Screenshot 2025-05-12 at 2 28 29 PM

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:

Screenshot 2025-05-12 at 2 29 47 PM

Lastly, just for the heck of it, we went from cacheTxContext being responsible for 12% of objects allocated to <0.1%:

Screenshot 2025-05-12 at 2 31 56 PM

This translates to about 10% fewer allocated objects in runTx:

Screenshot 2025-05-12 at 2 34 16 PM

Let me know if you'd like me to collect any more metrics!

fastfadingviolets avatar May 12 '25 18:05 fastfadingviolets

@fastfadingviolets we will need a changelog in both the root CHANGELOG.md and the one in ./store

aljo242 avatar May 13 '25 16:05 aljo242

@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

fastfadingviolets avatar May 13 '25 17:05 fastfadingviolets

adding @aaronc to take a look

aljo242 avatar May 14 '25 14:05 aljo242

@fastfadingviolets we have some conflicts

aljo242 avatar May 15 '25 20:05 aljo242

@aaronc just wondering if you've had a chance to take a peek at this!

fastfadingviolets avatar May 27 '25 14:05 fastfadingviolets

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!

ValarDragon avatar May 27 '25 21:05 ValarDragon

@fastfadingviolets looks like there are some conflicts

aljo242 avatar May 29 '25 19:05 aljo242

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

faddat avatar Jun 20 '25 10:06 faddat

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

yihuang avatar Jun 20 '25 15:06 yihuang

@fastfadingviolets conflicts here! we'd like to get this in!

aljo242 avatar Oct 27 '25 17:10 aljo242