The Impossibility of Perfectly Caching HTTP Range Requests
Published: 2021-06-07 13:47:06

---
title: The Impossibility of Perfectly Caching HTTP Range Requests
published: true
date: 2021-06-04 22:03:00 UTC
tags: 
canonical_url: https://kevincox.ca/2021/06/04/http-range-caching/
---

<main><p>I was just bitten by range request caching in NGINX. <a href="https://www.nginx.com/blog/smart-efficient-byte-range-caching-nginx/#NGINX%E2%80%99s-Default-Byte%E2%80%91Range-Caching-Behavior">The default behaviour upon receiving a range request is to upgrade that to a full request</a> (effectively stripping the <a href="https://datatracker.ietf.org/doc/html/rfc7233#section-2.3"><code>Range</code> header</a>) and then return the requested subset to the client. This can certainly be suboptimal in some cases such as when the client tries to download the small table of contents at the end of a large video file and ends up waiting while NGINX downloads the entire video before answering the request.</p>
<p>This issue can be mitigated by setting <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_max_range_offset"><code>proxy_cache_max_range_offset</code></a>. Which keeps the range header—but doesn’t cache the response—if the start offset of the requested range is greater than the specified value.</p>
<p>This is a pretty bad user experience as there is a huge delay before starting the video, or we are disabling caching. It got me thinking, what better strategies are there?</p>
<h2 id="range-caching-techniques"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#range-caching-techniques">Range Caching Techniques</a></h2>
<p>I looked at a number of proxies and found common patterns for caching range requests. I separated into 3 primary dimensions that can be used to summarize the basic behaviour of most proxies.</p>
<h3 id="rounding"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#rounding">Rounding</a></h3>
<p>Some caches round the requested ranges. Rounding can improve cache hit rate and simplify implementation at the cost of using more origin bandwidth. Additionally if there is a significant difference between the requested range and start of the range after rounding the client will experience additional latency as the cache downloads “unnecessary” data from the origin before receiving the content relevant to the client.</p>
<p>As an extreme case some proxies simply strip the <code>Range</code> header from the origin request, effectively rounding to the entire file. This uses a lot of unnecessary bandwidth (if the rest of the file is not later needed) and can add massive delay when requesting a range far into the file. For example if the client requests data 10GiB into the file they will not receive any content until the proxy has finished downloading the first 10GiB from the origin. (This is the surprising NGINX behaviour described above.)</p>
<h4 id="aside-out-of-order-fill"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#aside-out-of-order-fill">Aside: Out of Order Fill</a></h4>
<p>In theory it is possible to avoid the extra latency by generating a <code>Range</code> header with the content that the client wants first. (ex: for a server rounding to 10MiB chunks and a request <code>Range: bytes=12345678-20000000</code>, the proxy could request <code>Range: bytes=12345678-20971519,10485760-12345677</code> from the origin) However this is unlikely to work in practice as many servers will ignore or reject requests like this. Such a rejection is legal and even somewhat suggested by the RFC.</p>
<ol>
<li>“A client SHOULD NOT request multiple ranges that are inherently less efficient to process and transfer than a single range that encompasses the same data.” While requesting ranges in this way may be more efficient overall it is almost certainly less efficient for the origin.</li>
<li>“[A server] MAY ignore or reject a <code>Range</code> header field that consists of […] many small ranges that are not listed in ascending order, since [it is an indication] of either a broken client or a deliberate denial-of-service attack”. I guess we aren’t requesting “many” ranges out of order but that term is not precisely specified and some real-word proxies ignore all out-of-order requests.</li>
</ol>
<p>Although we are not fully against the RFC because it does say that a client may suggest ranges out-of-order if “there is a specific need to request a later part earlier”. Which in this case applies because we need to request the data the client requested first to provide the lowest latency.</p>
<p>However even if out-of-order requests are supported most systems are designed for streaming responses in order, so this may have unacceptable overheads anyways.</p>
<h3 id="match-mode"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#match-mode">Match Mode</a></h3>
<p>There are a couple of techniques used to match the request to the cached content.</p>
<h4 id="none"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#none">None</a></h4>
<p>Ranges are not cached. The range is passed onto the origin server without the response being stored in the cache.</p>
<p>Some caches have mixed behaviour where even though they do not cache partial responses they can respond to range requests if the <strong>full</strong> resource is in the cache.</p>
<h4 id="exact"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#exact">Exact</a></h4>
<p>The requested range is stored in the cache key. This means that that a cached response will only be used for future requests with the exact same range. This works excellently when clients are frequently requesting the same ranges, and especially well when the same ranges are always used to download a file. For example if serving video files where the player always buffers 1MiB chunks then it can be effectively optimal. However if clients request ranges that overlap, redundant data will be fetched from the origin and stored in the cache.</p>
<p>For example if a request for <code>Range: bytes=0-99</code> is made it will be passed to the origin origin and cached. If another request comes in for <code>Range: bytes=0-99</code> the cache will be used. However if a request is then made for <code>Range: bytes=0-49</code> it will miss the cache and be passed to the origin. Afterwards bytes <code>0-49</code> will be stored twice in the cache, consuming valuable space.</p>
<h4 id="full"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#full">Full</a></h4>
<p>All data will only be stored in the cache once, and the request will be fulfilled from the cache if the requested data is available. If only some of the requested content is in the cache the rest will be fetched according to the <a href="https://kevincox.ca/2021/06/04/http-range-caching/#fill-mode">Fill Mode</a>.</p>
<p>For example if a request for <code>Range: bytes=0-99</code> is made it will be passed to the origin and cached. If a request is then made for <code>Range: bytes=0-49</code> is made it will be fulfilled from the cache.</p>
<h3 id="fill-mode"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#fill-mode">Fill Mode</a></h3>
<p>There are two main ways that caches fetch content from the origin. The simplest is “full fill” where upon a cache miss for any content the full requested range is requested from the origin. An alternative approach is “partial fill” where only the missing data is requested. Partial fill can be more efficient but has hard to manage consistency issues if the resource is changing. If the response does not match the already cached data the proxy will need to make another request. Furthermore nothing guarantees that the second request matches the first! In the extreme case of the origin returning a random <code>ETag</code> you would never be able to build a consistent response. The only way to guarantee a consistent response is to fetch the entire requested range in a single request. In practice range requests from quickly changing files are rare, but I’m sure that you could get a PhD analyzing the performance of different fallback behaviours.</p>
<p>If the origin server was determined it could ensure that the fallback was not necessary by keeping around old versions of the file even after a new version is available. This way the old content can be served for partial requests based on the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Range"><code>If-Range</code></a> or <a href="https://datatracker.ietf.org/doc/html/rfc7232#section-3.1"><code>If-Match</code></a> headers, allowing partial updates until the previously cached content becomes stale.</p>
<h4 id="aside-if-range-limitations"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#aside-if-range-limitations">Aside: If-Range Limitations</a></h4>
<p>HTTP has a clever <a href="https://datatracker.ietf.org/doc/html/rfc7233#section-3.2"><code>If-Range</code></a> mechanism to allow making a range request for a known version with an automatic fallback if the resource has changed. However this header assumes that the desired fallback is the entire resource. This means that it is unsuitable for a partial fill that is fulfilling a range request as in this case the fallback should be the client’s request range, not the entire resource. In this case the only option is to use <a href="https://datatracker.ietf.org/doc/html/rfc7232#section-3.1"><code>If-Match</code></a> and make a second request if validation fails.</p>
<h2 id="what-are-cdns-doing"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#what-are-cdns-doing">What are CDNs Doing?</a></h2>
<p>I read the docs of some CDNs to see how they handle <code>Range</code> requests. The landscape is quite varied. If anyone can test the behaviour of various CDNs I would be happy to update this list.</p>
<p>Here is a table of what I could identify. Notes with sources are below.</p>
<table>
<thead><tr>
<th>Proxy</th>
<th>Rounding</th>
<th>Matching</th>
<th>Fill</th>
</tr></thead>
<tbody>
<tr>
<td>Amazon CloudFront</td>
<td>Yes</td>
<td>Full</td>
<td>Full</td>
</tr>
<tr>
<td>Cloudflare</td>
<td>Entire File</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>Fastly</td>
<td>Fixed Chunks</td>
<td>Full</td>
<td>Partial</td>
</tr>
<tr>
<td>Google Cloud CDN</td>
<td>Fixed Chunks</td>
<td>Full</td>
<td>Partial</td>
</tr>
<tr>
<td>NGINX default</td>
<td>Entire File</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>NGINX http_proxy_module</td>
<td>Fixed Chunks</td>
<td>Full</td>
<td>Partial</td>
</tr>
<tr>
<td>NGINX proxy_pass Range</td>
<td>None</td>
<td>Exact</td>
<td>-</td>
</tr>
<tr>
<td>NGINX proxy_no_cache</td>
<td>None</td>
<td>None</td>
<td>-</td>
</tr>
</tbody>
</table>
<h3 id="amazon-cloudfront"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#amazon-cloudfront">Amazon CloudFront</a></h3>
<p>The docs say that they may perform rounding, the exact nature is not described.</p>
<p><a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RangeGETs.html">How CloudFront Processes Partial Requests for an Object (Range GETs) - Amazon CloudFront</a></p>
<h3 id="cloudflare"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#cloudflare">Cloudflare</a></h3>
<p>I couldn’t find any docs for how Cloudflare handles <code>Range</code> requests! However based on my own testing they appear to use the default NGINX behaviour of “rounding” to the entire file.</p>
<h3 id="fastly"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#fastly">Fastly</a></h3>
<p>If the partial fill fails they appear to return an error on <code>ETag</code> mismatch based on the <a href="https://docs.fastly.com/en/guides/common-otfp-errors#500-responses">“Flapping origin entity”</a> error response.</p>
<p><a href="https://docs.fastly.com/en/guides/segmented-caching">Segmented Caching | Fastly Help Guides</a></p>
<h3 id="google-cloud-cdn"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#google-cloud-cdn">Google Cloud CDN</a></h3>
<p>Google Cloud CDN has some unique behaviour. Notably it will never cache the first <code>Range</code> request for a given cache key. However if the server supports <code>Range</code> requests along with a strong <code>ETag</code> it will then cache future requests. Fill is done via multiple requests of 2MiB-16B each.</p>
<aside>The chunk size is interesting. Presumably they store 16 bytes of metadata inline with the cached data.</aside><p>I couldn’t find anything concrete about how partial fill mismatches are handled. <a href="https://cloud.google.com/cdn/docs/troubleshooting-steps#responses-not-cached">This page</a> seems to imply that a full fill is done on <code>ETag</code> mismatch.</p>
<p><a href="https://cloud.google.com/cdn/docs/caching#byte-range-requests">Caching overview | Cloud CDN | Google Cloud</a></p>
<h3 id="nginx"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#nginx">NGINX</a></h3>
<p>NGINX can be configured a number of ways. The <a href="https://nginx.org/en/docs/http/ngx_http_slice_module.html">http_slice_module</a> module can be used for fixed-size chunk rounding. <code>proxy_pass Range</code> and adding <code>$http_range</code> to the cache key can be used to perform exact matching. Alternatively the cache can be disabled for range requests.</p>
<p><a href="https://www.nginx.com/blog/smart-efficient-byte-range-caching-nginx/">Smart and Efficient Byte-Range Caching with NGINX</a></p>
<h2 id="what-is-the-best-strategy"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#what-is-the-best-strategy">What is the Best Strategy?</a></h2>
<p>There is no perfect strategy, especially when you consider implementation complexity. However there are definitely some options that are better than others in the vast majority of cases.</p>
<h3 id="rounding-1"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#rounding-1">Rounding</a></h3>
<p>“Rounding” to the entire file is behaviour that performs very poorly in common scenarios, but rounding to a fixed chunk size is a reasonable tradeoff. It can make implementation simpler and avoids issues such as needing to request a couple of bytes between cached ranges. Just be sure that the chunk size is small enough that the extra first-byte latency isn’t significant.</p>
<h3 id="matching"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#matching">Matching</a></h3>
<p>Full matching is clearly superior as it avoids unnecessary origin fetch and avoids wasting cache capacity on duplicate data.</p>
<p>However if you are rounding to fixed boundaries and slicing the content Exact and Full become equivalent so rounding can be an effective way to simplify the matching implementation.</p>
<h3 id="fill"><a href="https://kevincox.ca/2021/06/04/http-range-caching/#fill">Fill</a></h3>
<p>In general partial fill is superior however in edge cases the behaviour can be suboptimal with extra requests leading to a full fill anyways. I think a perfect solution would use a set of heuristics (or configuration) to select the best behaviour for various circumstances. For example if only a couple of bytes are already cached it probably makes sense to perform a full fill to avoid the risk of validation failure. However if you have 900MiB/1Gib cached it is likely worth trying the partial fill as even if the resource has changed the overhead of an extra request will be minimal compared to the transfer. Other heuristics include estimating churn rate per file or directory to guess how likely a match is.</p>
<p>Another option is sending one request with <code>If-Match</code> and one request with <code>If-None-Match</code> in parallel. Most of the time exactly one response will return content. In the rare case that neither return you can resend a full fill and in the rare case that both return content you can abort one.</p>