Understanding HTTP/2: How HPACK Compression Shrinks Headers for Faster Transmission

To achieve smaller and faster message transmission, the headers in HTTP/2 are compressed using the HPACK compression algorithm. This article starts by visually demonstrating the effect of header compression through Wireshark screenshots, followed by an analysis of how this compression algorithm works.

I. Compression Effect Comparison

1. Before Compression

Taking the user-agent in the header as an example, the size before compression is 63 bytes.

HTTP/2 >

2. After Compression

After compression, the size of the user-agent in the header is 1 byte.

HTTP/2 >

In summary: How does HTTP/2 reduce the user-agent in the header from 63 bytes to 1 byte?

II. HPACK Algorithm

The headers in HTTP/2 are compressed using the HPACK algorithm, which relies on the server and client maintaining an index table. These index tables are divided into static and dynamic tables.

1. Pseudo-Header Fields

The headers are transmitted in the form of binary frames, and to distinguish them from HTTP1 headers, these fields beginning with a colon are called “pseudo-header fields.”

2. Static Table

The static table defines 61 header fields and their indices, allowing the transmission of indices to greatly reduce the message size. The fields and values in the static table are fixed and read-only.

Some values in the static table

See: https://tools.ietf.org/html/rfc7541#appendix-A

3. Dynamic Table

The dynamic table follows the static table; it has the same structure and can be updated at any time. In the image below, indices 62 and 63 are dynamic table fields.

III. Conclusion

Referring back to the compression effect comparison at the beginning of this article, the client transmits index numbers, and the server retrieves the header key and value from the dynamic table based on these indices. The user-agent index number occupies 1 byte. Additionally, fields not present in the index table are encoded using Huffman coding and then updated to the dynamic table.