Skip to content

Commit e11b125

Browse files
committed
Don't compress empty or small messages
Fixes grpc#6831. gzip compressing messages less than 21 bytes is always unfruitful, it always results in "compressed" messages that are longer than the original message length, since the minimum length of a gzipped message is 21 bytes, due to headers and CRC trailer.
1 parent 1b05500 commit e11b125

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

rpc_util.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -640,14 +640,23 @@ func encode(c baseCodec, msg any) ([]byte, error) {
640640
return b, nil
641641
}
642642

643-
// compress returns the input bytes compressed by compressor or cp. If both
644-
// compressors are nil, returns nil.
643+
const (
644+
// minCompressionLength is the number of bytes that the gzip algorithm "compresses" an empty message to
645+
minCompressionLength = 21
646+
)
647+
648+
// compress returns the input bytes compressed by compressor or cp. Only
649+
// compresses the bytes if compression is likely to reduce the size of the
650+
// message, otherwise returns nil. If both compressors are nil, returns nil.
645651
//
646652
// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
647653
func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
648654
if compressor == nil && cp == nil {
649655
return nil, nil
650656
}
657+
if len(in) <= minCompressionLength {
658+
return nil, nil
659+
}
651660
wrapErr := func(err error) error {
652661
return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
653662
}

0 commit comments

Comments
 (0)