You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We recently realised our outbound traffic had increased a fair amount sinced we switched from serving some assets directly from Akamai to serving them from Ambassador, and traced it down to our gzipped assets being much larger.
I then ran some tests, and it appears that gzipping content in Envoy results in fairly poor compression results, even when tweaking the settings to produce the smallest possible output.
For example, when gzipping html & js from Youtube (picked as a random "big website" example), Envoy-compressed html is 12% larger than nginx and js is 13% larger.
This isn't nginx-specific either: I've tested gzip locally, Apache httpd, and nginx, and all of their results are within a few percents of each other while Envoy is consistently over 10% larger.
Is this a known issue? Is there a problem with my configuration? I'm by no means an Envoy expert, so please let me know if there's any obvious issues with the config above or anything else I've missed that might explain this discrepancy.
Thanks a lot!
Florent
Reacted by _gw_, Per Lundberg, Joel Damata, Vithal Reddy, James Wu, Bara E. Brahmantika, Jerome and Remy-Dtonic
@Pluies Do you know what is the delay when compressing with Nginx and Js? In other to reduce latency we decided to compress and flush on each data frame. The downside is that it degrades the compression ratio. The second option is to let gzip to compress until the buffer gets full. I think we could make it configurable.
Do you know what is the delay when compressing with Nginx and Js?
That's a very good question; I guess we could try and measure it with the compose-based stuff. I'll give it a go and report back!
As far as I can tell, compressing in small chunks this way is something only envoy does – httpd, nginx, and Akamai (the one's I've tested so far :) ) all seem to wait until the file is fully available before compressing, if I understand correctly – resulting in much better results. Having it optional would be a great way of letting users choose latency or compression performance, as the current results are a bit baffling.
By the way, by data frame, do you refer exclusively to HTTP/2 streams? (Sorry if it's a silly question, probably need to brush up on my HTTP knowledge).
OK, I've been running tests on a the polymer js file duplicated 10 times, bringing it to 30MB for an extreme test case, with the following curl command: curl -so /dev/null http://localhost:$PORT/$FILE --compressed -w '%{size_download}, Connect: %{time_connect} TTFB: %{time_starttransfer} Total time: %{time_total}\n' (as per this link).
This hopefully should test TTFB, which (once again, if I understand correctly) should be much lower in Envoy than in other servers.
I'm getting a fair amount of variance run-after-run, so please don't read too much in this test, but here are some numbers:
Comparing compression performance for file: assets/desktop_polymer_v2_x10.js (all sizes in bytes)
origin, uncompressed 31668307, Connect: 0.005557 TTFB: 0.020001 Total time: 0.563083
nginx, base 9584605, Connect: 0.005483 TTFB: 0.017597 Total time: 0.620351
nginx, optimised 7821304, Connect: 0.004427 TTFB: 0.021322 Total time: 1.782090
ambassador, base 10881198, Connect: 0.004422 TTFB: 0.022827 Total time: 1.050829
ambassador, optimised 10864866, Connect: 0.004758 TTFB: 0.025497 Total time: 1.316463
envoy, base 10881083, Connect: 0.005510 TTFB: 0.021910 Total time: 0.899159
envoy, optimised 8831289, Connect: 0.004534 TTFB: 0.027110 Total time: 1.713541
apache, base 7853115, Connect: 0.005130 TTFB: 0.019696 Total time: 1.157169
apache, optimised 7820515, Connect: 0.004526 TTFB: 0.023279 Total time: 2.212370
local gzip, base 7854014
local gzip, optimised 7821330
As expected, we're seeing a fair uptick in the total time between "base" and "optimised" version of the same server (as we're trading overall speed for data size), but I'm seeing basically no difference in TTFB between servers... So, other HTTP servers are also compressing-while-streaming, but somehow in an efficient fashion? Or is curl not telling us the full story? (e.g. headers being sent first while the body is being compressed, or other shenanigans)
It looks like that Envoy and Nginx optimized/base are very close:
nginx, base 9584605, Connect: 0.005483 TTFB: 0.017597 Total time: 0.620351
envoy, base 10881083, Connect: 0.005510 TTFB: 0.021910 Total time: 0.899159
nginx, optimised 7821304, Connect: 0.004427 TTFB: 0.021322 Total time: 1.782090
envoy, optimised 8831289, Connect: 0.004534 TTFB: 0.027110 Total time: 1.713541
It could be also the underlying compression library that we are using. I'm looking at some other more modern libraries that may improve the performance.
As you point out, the difference between optimised {nginx,apache,gzip} and optimised Envoy is not huge... But still ~10-15% extra, which wipes out gains from a bunch of other application-level improvements we've been working on at $CURRENT_COMPANY, for example.
Regarding the compression library, as far as I can understand, both envoy and nginx use the venerable zlib? Here's the ngx_http_gzip_filter_module.c source, which refers to the exact same parameters (gzip_comp_level, gzip_window), same function calls (deflateInit2), importing zlib.h, etc.
On a related note, we are also hit by this (getting worse latency via Envoy than Nginx when compressing). I wrote #10464, as a starting point to start measuring things.
Ok, deleted my last comment because it was inaccurate -- the problem was with the mocks. Getting rid of those and I get back ~6ms. I'll keep removing the mocks/boilerplate to get more accurate measurements.
void ZlibCompressorImpl::compress(Buffer::Instance& buffer, State state) {
for (const Buffer::RawSlice& input_slice : buffer.getRawSlices()) {
zstream_ptr_->avail_in = input_slice.len_;
zstream_ptr_->next_in = static_cast<Bytef*>(input_slice.mem_);
// Z_NO_FLUSH tells the compressor to take the data in and compresses it as much as possible
// without flushing it out. However, if the data output is greater or equal to the allocated
// chunk size, process() outputs it to the end of the buffer. This is fine, since at the next
// step, the buffer is drained from the beginning of the buffer by the size of input.
process(buffer, Z_NO_FLUSH);
buffer.drain(input_slice.len_);
}
// Was this meant to be Z_NO_FLUSH? Why should we always flush?
process(buffer, state == State::Finish ? Z_FINISH : Z_SYNC_FLUSH);
}
Sounds like maybe we went a step to far in fixing the missing of Z_FINISH call...
I configured Envoy and Nginx to use similar settings for zlib: compression level 1, default strategy, one thread, memory level 8 and the same sliding window size (window_bits 15). chunk_size is 4096 as Nginx uses buffers of the size of one memory page too.
The test results for downloading a 157K JSON file with
Nginx is about 30% faster overall with TTFB almost 3 times shorter.
I tried to do three things:
avoid excesive flushing with @rgs1's patch modified to fit the latest master;
get rid of memcpy() when moving bytes from zlib's output to the filter's output buffer with rojkov@d084d1e;
configured zlib to use a custom memory management copied mostly from Nginx to allocate memory for zlib only once per request with rojkov@d91afc0.
The first thing improved TTFB a bit (by about 1-2%), but TTLB didn't change at all. The impact of the other two approaches was not noticeable at all.
Flamegraphs show that most of the time is spent in zlib: Envoy and Nginx. Though in case of Envoy callstacks are much deeper.
Callgrind doesn't reveal excessive cache thrashing neither, though I might have interpreted the numbers wrong way (sorted by Last level cache misses for Data writes, limited to 0.25%):
Looks like Nginx moves data more effectively though.
Nginx uses adaptive settings for zlib if Content-Length is known: it tries to narrow the sliding window for small data blobs. We could do the same. It should improve memory consumption in some cases, but won't improve request duration.
Now I run out of ideas. Any help is appreciated :)
So, I did one more try to solve this mystery. Turned out I was measuring wrong numbers. Flamegraphs and profilers show where CPU cycles are spent, not where wall time is spent. I used PerfAnnotationContext to measure exactly how long it takes to deflate() 157k of JSON in a running Envoy instance. On my machine the average is 6.6ms (out of >14ms connection life span). The same measurement for nginx shows 6.2ms (out of ~10ms connection life span) - still better, but not dramatically. When the same JSON is compressed in compressor_filter_speed_test it takes less than 3ms (avg). The explanation is that when running compressor_filter_speed_test the CPU "turboboosts" to 3.8GHz. In case of deflate()'ing in a running Envoy instance the CPU core works at 1.6GHz in average giving a clue that the load is not CPU bound. As a result in case of Envoy writing data to a socket is as long as calling deflate(): after having written ~85k of compressed data to the socket in one chunk the next "write ready" event comes in ~5ms. Then the connection is finally closed. With compression switched off and writing 157k in one chunk the "write ready" event comes in <1ms. Looks like these "ready" events are scheduled with a delay if writes are done not often enough. To make them more frequent I set per_connection_buffer_limit_bytes to 8192 for clusters and listeners. Here is the result:
Nginx doesn't document how to specify memlevel and wbits (because they are calculated dynamically for known Content-Length), but in case of 157k they are 8 and 15 respectively.
Yeah, adding some notes to compressor_filter.rst won't harm. I'll think how to formulate it better.
By the way, at some point I experimented with CPU frequency a bit: while benchmarking compression with k6 I artificially loaded all the cores to 100% (with a full envoy rebuild). This made Envoy serve twice as fast and Nginx showed a similar dynamics. Which can be counterintuitive yet explainable. Just a side note on how important it is to do experiments in the same environmental conditions.
Thanks @rojkov this is amazing work and a really great finding around how buffer sizes effect the overall throughput.
Looks like these "ready" events are scheduled with a delay if writes are done not often enough. To make them more frequent I set per_connection_buffer_limit_bytes to 8192 for clusters and listeners.
After having written ~85k of compressed data to the socket in one chunk the next "write ready" event comes in ~5ms. Then the connection is finally closed. With compression switched off and writing 157k in one chunk the "write ready" event comes in <1ms. Looks like these "ready" events are scheduled with a delay if writes are done not often enough.
I'm a little confused and have a few questions that we can follow up on:
In the compressed case, are we basically doing a single writev with a single slice which is giant?
In the uncompressed case, are we doing a single writev with multiple slices? Or is the data spread over more writes because it is streamed?
If we know all data has been written, what does connection closure have to do with the overall latency? I would assume TTLB on the downstream client would be the same regardless of closure as long as content-length is set? Or is the issue we are chunk encoding and the last chunk is not written until 5ms later?
Is there a way we can split up the writes in the compressed case such that max buffer bytes doesn't come into play? I'm a little confused about how decreasing the max connection buffer bytes is helping. Is it cause back pressure so we are reading in smaller chunks which are then compressed in smaller blocks?
cc @antoniovicente for event and buffer expertise. cc @ggreenway as this very likely relates to the perf work you have been doing.
I used PerfAnnotationContext to measure
As an aside, this is really neat. We should document this approach and/or would it be worthwhile to add this hooks into the code base under some macro guard so that we can more easily use this annotations for perf investigations?
In the compressed case, are we basically doing a single writev with a single slice which is giant?
In the uncompressed case, are we doing a single writev with multiple slices? Or is the data spread over more writes because it is streamed?
I understood that there is one single write with a single slice in both cases. This is how it looks in logs:
ts is a timestamp in microseconds since a ActiveTcpConnection creation. C2 is a downstream connection.
If we know all data has been written, what does connection closure have to do with the overall latency? I would assume TTLB on the downstream client would be the same regardless of closure as long as content-length is set? Or is the issue we are chunk encoding and the last chunk is not written until 5ms later?
A-ha. I should have asked this question myself... So, I did closed loop testing, that is a new connection to the listener is not created until the current one isn't closed. TTLB should be shorter for a real client. I guess I need to use something other than k6 for benchmarking.
I've just tried to benchmark with 10 virtual simultaneous users connecting to a single-threaded Envoy and got
280 reqs/s (default 1M buffer) vs 371 reqs/s (8k per connection buffer).
With 20 virtual users I got 306 reqs/s vs 364 reqs/s respectively.
With 80 VUs I got 420 reqs/s vs 311 reqs/s.
Whereas Nginx consistently gives ~420 reqs/s starting from 10 VUs. Then increasing VUs doesn't increase throughput.
Activity
mattklein123 commentedon Oct 1, 2019
@dio @lizan @gsagula
gsagula commentedon Oct 1, 2019
@Pluies Do you know what is the delay when compressing with Nginx and Js? In other to reduce latency we decided to compress and flush on each data frame. The downside is that it degrades the compression ratio. The second option is to let gzip to compress until the buffer gets full. I think we could make it configurable.
Pluies commentedon Oct 2, 2019
That's a very good question; I guess we could try and measure it with the compose-based stuff. I'll give it a go and report back!
As far as I can tell, compressing in small chunks this way is something only envoy does – httpd, nginx, and Akamai (the one's I've tested so far :) ) all seem to wait until the file is fully available before compressing, if I understand correctly – resulting in much better results. Having it optional would be a great way of letting users choose latency or compression performance, as the current results are a bit baffling.
By the way, by data frame, do you refer exclusively to HTTP/2 streams? (Sorry if it's a silly question, probably need to brush up on my HTTP knowledge).
Pluies commentedon Oct 2, 2019
OK, I've been running tests on a the polymer js file duplicated 10 times, bringing it to 30MB for an extreme test case, with the following curl command:
curl -so /dev/null http://localhost:$PORT/$FILE --compressed -w '%{size_download}, Connect: %{time_connect} TTFB: %{time_starttransfer} Total time: %{time_total}\n'(as per this link).This hopefully should test TTFB, which (once again, if I understand correctly) should be much lower in Envoy than in other servers.
I'm getting a fair amount of variance run-after-run, so please don't read too much in this test, but here are some numbers:
As expected, we're seeing a fair uptick in the total time between "base" and "optimised" version of the same server (as we're trading overall speed for data size), but I'm seeing basically no difference in TTFB between servers... So, other HTTP servers are also compressing-while-streaming, but somehow in an efficient fashion? Or is curl not telling us the full story? (e.g. headers being sent first while the body is being compressed, or other shenanigans)
gsagula commentedon Oct 3, 2019
It looks like that Envoy and Nginx optimized/base are very close:
It could be also the underlying compression library that we are using. I'm looking at some other more modern libraries that may improve the performance.
Pluies commentedon Oct 7, 2019
@gsagula thanks for looking into it! :)
As you point out, the difference between optimised {nginx,apache,gzip} and optimised Envoy is not huge... But still ~10-15% extra, which wipes out gains from a bunch of other application-level improvements we've been working on at $CURRENT_COMPANY, for example.
Regarding the compression library, as far as I can understand, both envoy and nginx use the venerable zlib? Here's the ngx_http_gzip_filter_module.c source, which refers to the exact same parameters (
gzip_comp_level,gzip_window), same function calls (deflateInit2), importingzlib.h, etc.Support window_bits parameter for gzip filter
rgs1 commentedon Mar 20, 2020
On a related note, we are also hit by this (getting worse latency via Envoy than Nginx when compressing). I wrote #10464, as a starting point to start measuring things.
mythi commentedon Mar 23, 2020
Perf annotations and flamegraphs could also help debugging
rgs1 commentedon Mar 23, 2020
Ok, deleted my last comment because it was inaccurate -- the problem was with the mocks. Getting rid of those and I get back ~6ms. I'll keep removing the mocks/boilerplate to get more accurate measurements.
compressor: add more stats
rgs1 commentedon Mar 24, 2020
Adding stats to track flushes: #10500.
rgs1 commentedon Mar 24, 2020
Ok, so started running with the stats added in #10500 and the ratio of flush vs finish vs upstream_rq seems potentially concerning:
I am wondering if the change introduced in #3025 -- which was a fix for #2909 -- didn't mean to use
Z_NO_FLUSHinstead ofZ_SYNC_FLUSHin https://github.com/envoyproxy/envoy/blob/master/source/common/compressor/zlib_compressor_impl.cc#L40:Sounds like maybe we went a step to far in fixing the missing of
Z_FINISHcall...cc: @dio @gsagula
51 remaining items
rojkov commentedon Sep 22, 2020
Yes, I'll take a look. Perhaps there's a way to avoid double buffering.
rojkov commentedon Oct 13, 2020
I configured Envoy and Nginx to use similar settings for zlib: compression level 1, default strategy, one thread, memory level 8 and the same sliding window size (
window_bits 15).chunk_sizeis 4096 as Nginx uses buffers of the size of one memory page too.The test results for downloading a 157K JSON file with
Envoy
Nginx
Nginx is about 30% faster overall with TTFB almost 3 times shorter.
I tried to do three things:
memcpy()when moving bytes from zlib's output to the filter's output buffer with rojkov@d084d1e;The first thing improved TTFB a bit (by about 1-2%), but TTLB didn't change at all. The impact of the other two approaches was not noticeable at all.
Flamegraphs show that most of the time is spent in zlib: Envoy and Nginx. Though in case of Envoy callstacks are much deeper.
Callgrind doesn't reveal excessive cache thrashing neither, though I might have interpreted the numbers wrong way (sorted by Last level cache misses for Data writes, limited to 0.25%):
Looks like Nginx moves data more effectively though.
Nginx uses adaptive settings for zlib if
Content-Lengthis known: it tries to narrow the sliding window for small data blobs. We could do the same. It should improve memory consumption in some cases, but won't improve request duration.Now I run out of ideas. Any help is appreciated :)
rojkov commentedon Oct 29, 2020
So, I did one more try to solve this mystery. Turned out I was measuring wrong numbers. Flamegraphs and profilers show where CPU cycles are spent, not where wall time is spent. I used
PerfAnnotationContextto measure exactly how long it takes todeflate()157k of JSON in a running Envoy instance. On my machine the average is 6.6ms (out of >14ms connection life span). The same measurement for nginx shows 6.2ms (out of ~10ms connection life span) - still better, but not dramatically. When the same JSON is compressed incompressor_filter_speed_testit takes less than 3ms (avg). The explanation is that when runningcompressor_filter_speed_testthe CPU "turboboosts" to 3.8GHz. In case ofdeflate()'ing in a running Envoy instance the CPU core works at 1.6GHz in average giving a clue that the load is not CPU bound. As a result in case of Envoy writing data to a socket is as long as callingdeflate(): after having written ~85k of compressed data to the socket in one chunk the next "write ready" event comes in ~5ms. Then the connection is finally closed. With compression switched off and writing 157k in one chunk the "write ready" event comes in <1ms. Looks like these "ready" events are scheduled with a delay if writes are done not often enough. To make them more frequent I setper_connection_buffer_limit_bytesto 8192 for clusters and listeners. Here is the result:Now envoy is ~25% faster than nginx.
@rgs1 What were the zlib settings in your setup? Could you check if you set them equal to nginx's?
In my setup they are
Nginx doesn't document how to specify memlevel and wbits (because they are calculated dynamically for known
Content-Length), but in case of 157k they are 8 and 15 respectively.dio commentedon Oct 29, 2020
Wow. So awesome!
jmarantz commentedon Oct 29, 2020
Great work!
The only change you made was to set per_connection_buffer_limit_bytes to 8192? What was it prevously?
rojkov commentedon Oct 29, 2020
Yes, only this change. Initially there was nothing in my config and the default is 1M.
rgs1 commentedon Oct 29, 2020
@rojkov hmm, interesting. Could it a problem that we have different limits for listeners and clusters:
?
This is all using zlib-ng right?
rgs1 commentedon Oct 29, 2020
Our settings:
So mostly the same, I don't expect that memory_level:9 vs memory_level:8 would make such a big change...
rojkov commentedon Oct 29, 2020
No, I compiled Envoy with the same old zlib used by Nginx.
I don't think different limits matter so much. Neither memlevel 9. Then I don't understand why your results are so different :(
rgs1 commentedon Oct 29, 2020
@rojkov let me dig a bit more on our side, regardless of our case this is a great finding -- thanks! Shall we document this somewhere?
rojkov commentedon Oct 29, 2020
Yeah, adding some notes to
compressor_filter.rstwon't harm. I'll think how to formulate it better.By the way, at some point I experimented with CPU frequency a bit: while benchmarking compression with k6 I artificially loaded all the cores to 100% (with a full envoy rebuild). This made Envoy serve twice as fast and Nginx showed a similar dynamics. Which can be counterintuitive yet explainable. Just a side note on how important it is to do experiments in the same environmental conditions.
mattklein123 commentedon Oct 29, 2020
Thanks @rojkov this is amazing work and a really great finding around how buffer sizes effect the overall throughput.
I'm a little confused and have a few questions that we can follow up on:
cc @antoniovicente for event and buffer expertise. cc @ggreenway as this very likely relates to the perf work you have been doing.
As an aside, this is really neat. We should document this approach and/or would it be worthwhile to add this hooks into the code base under some macro guard so that we can more easily use this annotations for perf investigations?
rojkov commentedon Oct 29, 2020
I understood that there is one single write with a single slice in both cases. This is how it looks in logs:
tsis a timestamp in microseconds since aActiveTcpConnectioncreation.C2is a downstream connection.A-ha. I should have asked this question myself... So, I did closed loop testing, that is a new connection to the listener is not created until the current one isn't closed. TTLB should be shorter for a real client. I guess I need to use something other than k6 for benchmarking.
I've just tried to benchmark with 10 virtual simultaneous users connecting to a single-threaded Envoy and got
280 reqs/s (default 1M buffer) vs 371 reqs/s (8k per connection buffer).
With 20 virtual users I got 306 reqs/s vs 364 reqs/s respectively.
With 80 VUs I got 420 reqs/s vs 311 reqs/s.
Whereas Nginx consistently gives ~420 reqs/s starting from 10 VUs. Then increasing VUs doesn't increase throughput.
mattklein123 commentedon Oct 29, 2020
I actually do wonder if some of the fixes @ggreenway is working on may impact what we are seeing. Something still doesn't add up to me here.
yongzhang commentedon Jul 7, 2023
The discusstion stops in 2020, is this still a problem for now?