Shrink compression codec buffers to prevent memory bloat#184
Open
enomado wants to merge 2 commits into
Open
Conversation
CompPacketCodec's in_buf and out_buf grow to accommodate large packets but never shrink, effectively leaking memory for the connection lifetime. With 20+ compressed connections this wastes 200-500 MB of RSS. After each decode/encode cycle, if a buffer is fully drained and its capacity exceeds 4 MiB, replace it with a fresh BytesMut::new(). This is zero-cost for normal-sized packets and only triggers for genuinely bloated buffers. Relates to blackbeam/mysql_async#349
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
CompPacketCodec'sin_bufandout_buf(BytesMut) grow to accommodate large compressed/decompressed packets but never shrink back. Over time every compressed connection accumulates megabytes of idle capacity in these buffers. With 20+ compressed connections this easily wastes 200–500 MB of RSS.Relates to blackbeam/mysql_async#349.
Fix
After each decode/encode cycle, if a buffer is fully drained (
is_empty()) and its allocated capacity exceeds a 4 MiB threshold, replace it with a freshBytesMut::new().This is:
Production status
We've been running an equivalent patch (with a 1 MiB threshold) in production for several months against MySQL 5.1.53 with compression enabled, ~20 concurrent connections. Memory usage dropped from ~400 MB to ~40 MB with no issues.
Open to feedback
If you'd prefer this threshold to be configurable (e.g. via a field on
CompPacketCodecor a connection option), happy to rework. The hardcoded constant felt like the least invasive starting point.