Skip to content

Compress packets from 512 bytes and reuse zlib streams per connection - #199

Merged
blackbeam merged 4 commits into
blackbeam:masterfrom
lohmag:reuse-zlib-streams
Nov 3, 2026
Merged

blackbeam merged 4 commits into
blackbeam:masterfrom
lohmag:reuse-zlib-streams

Conversation

@lohmag

@lohmag lohmag commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

With compression on, every outgoing packet of 50 bytes or more is compressed with a new ZlibEncoder, and every incoming compressed packet is inflated with a new ZlibDecoder.

This change:

  • Raises MIN_COMPRESS_LENGTH from 50 to 512 bytes. A packet below a few hundred bytes barely shrinks, but each compression costs about 3 µs of setup. The server decides on its own packets with its own threshold, so the result of a small query is still compressed.
  • Keeps one Compress and one Decompress in the compressed codec for the life of the connection, reset between packets. The public compress and CompDecoder::decode keep their signatures.
  • Sends a packet uncompressed when compression does not make it smaller, as libmysqlclient does.
  • Fails to decode a packet that inflates to more bytes than its header declares. Until now the extra bytes were dropped silently. Fewer bytes already failed.

PacketCodec encode and decode of one packet, default level, Ryzen 9 7950X3D, one pinned core, median of 5 runs. Decode input is compressed as the server sends it.

Packet Encode before Encode after Decode before Decode after
100 B 2.73 µs 0.02 µs 0.60 µs 0.25 µs
300 B 3.46 µs 0.03 µs 0.69 µs 0.37 µs
600 B 4.54 µs 3.93 µs 1.68 µs 1.39 µs
2000 B 7.25 µs 6.66 µs 2.61 µs 2.30 µs
64 KB 200.5 µs 198.6 µs 39.6 µs 39.4 µs

New codec tests cover round trips around the threshold up to more than one 16 MB chunk on one codec, a level change, small and incompressible packets sent uncompressed, and packets that inflate to another length. cargo test --features test passes. The mysql_async and mysql lib tests were run with COMPRESS=1 against MySQL 8.0.46, with this branch and with master patched in: same results.

Switching an already compressing codec from none to default must start compressing.
Fails with the level comparison inverted.
Pins the boundary of "does not get smaller" in deflate_into.
Fails with < turned into <= or && turned into ||.
Brings CompDecoder::decode_with from CRAP 11.2 down to 9.2.
Full test suite passes unchanged.
@blackbeam
blackbeam merged commit 23c3b1a into blackbeam:master Nov 3, 2026
1 check passed
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.

2 participants