r/webdevelopment • u/IncomeOk7237 • 22h ago
Frameworks & Libraries HTTP/2 requests cost my server 4x the CPU of HTTP/1.1, so I started replaying HPACK blocks
I've been working on viltrum, a web framework for V where the HTTP/1.1, HTTP/2 and TLS parts are all written from scratch. It was doing fine on HttpArena's HTTP/1.1 tests, but on the h2 ones it was burning noticeably more CPU per request than the leader.
So I ran callgrind on a plain GET over h2c, one connection, 100 streams. About 21.5k instructions per request. The HTTP/1.1 version of the same request is around 5.1k.
Over a third of that was the HPACK encoder looking up header names in the static table and then walking the dynamic table byte by byte. For every single response, even though the headers were basically identical every time.
The fix ended up being kind of dumb. The HPACK tables now keep a counter that bumps whenever they change. If the last response block didn't touch the table and the head text is the same, I just write the same bytes again. Same coder state and same input means same output, so nothing changes on the wire. Date changes once a second, so a busy route re-encodes once a second.
Same idea on the request side. If a connection sends the exact same header block bytes and the table hasn't changed, skip decode, Huffman and validation. Later I also kept the parsed head per connection so it doesn't go through the HTTP/1.1 parser again. Stream id checks, limits etc still run on every request.
The part I was nervous about: the same bytes can mean a different request once the table changes, because an indexed entry now points somewhere else. There's a test for exactly that. Four identical requests, then the same bytes after a new :path entry, and it has to answer the new path.
In callgrind it went 21,477 -> 6,352 -> 4,161 instructions per request on h2c. Costs about 1.5 KB of fixed memory per HTTP/2 connection and still nothing allocated per request. I'm not quoting wall clock because it swings around 15% on my bench box.
Code (MIT): https://github.com/Tuntii/viltrum
The two PRs if you want the details: https://github.com/Tuntii/viltrum/pull/139 and https://github.com/Tuntii/viltrum/pull/142
Curious if other servers do something like this or if most just eat the HPACK cost.