To compress messages, Kafka uses DataOutputStream on top of GZIPOutputStream:
new DataOutputStream(new GZIPOutputStream(buffer, bufferSize));
To decompress messages, Kafka uses DataInputStream on top of GZIPInputStream:
new DataInputStream(new GZIPInputStream(buffer));
This is very straight forward, but actually inefficient. For each message, in addition to the key and value data, Kafka has to write about 30 some metadata bytes (slightly varies in different Kafka version), including magic byte, checksum, timestamp, offset, key length, value length etc. For each of these bytes, java DataOutputStream has to call write(byte) once. Here is the awkward writeInt() method in DataOutputStream, which writes 4 bytes separately in big-endian order.
Unfortunately, GZIPOutputStream does not implement the write(byte) method. Instead, it only provides a write(byte, offset, len) method, which calls the corresponding JNI zlib function. The write(byte) calls from DataOutputStream are translated into write(byte, offset, len) calls in a very inefficient way: (Oracle JDK 1.8 code)
For each meta data byte, the code above has to allocate 1 single byte array, acquire several locks, call two native JNI methods (Deflater.deflateBytes and CRC32.updateBytes). In each Kafka message, there are about 30 some meta data bytes.
The call stack of Deflater.deflateBytes():
DeflaterOutputStream.public void write(int b) -> GZIPOutputStream.write(byte buf, int off, int len) -> DeflaterOutputStream.write(byte b, int off, int len) -> DeflaterOutputStream.deflate() -> Deflater.deflate(byte b, int off, int len) -> Deflater.deflate(byte b, int off, int len, int flush) -> Deflater.deflateBytes(long addr, byte b, int off, int len, int flush)
The call stack of CRC32.updateBytes():
DeflaterOutputStream.public void write(int b) -> GZIPOutputStream.write(byte buf, int off, int len) -> CRC32.update(byte b, int off, int len) -> CRC32.updateBytes(int crc, byte b, int off, int len)
At Uber, we found that adding a small buffer between DataOutputStream and GZIPOutputStream can speed up Kafka GZip compression speed by about 60% in average.
The similar issue also exist in GZip decompression, which can be fixed by adding a buffer with BufferedInputStream.
We have tested this improvement on Kafka 10.2 / Oracle JDK 8, with the production traffic at Uber:
|Topic||Avg Message Size (bytes)||Vanilla Kafka Throughput (MB/s)||Kafka /w GZip Buffer Throughput (MB/s)||Speed Up|