Image from https://www.keycdn.com/support/vary-header
I had struggled with a situation where a browser cache does not work normally. It looked obvious that my code has a problem since the cache system worked normally on CDN contents. I read the standard HTTP Cache from the beginning and I would like to write a short retrospective post about what I faced while debugging.
Sorry for the ugly images
Even though the contents are same with the previous ones, Fetch
was sending the request repeatedly. As you can see in the second image, a header value cache-control
was provided successfully. I was hoping to remove the repeated requests on the frontend.
Fetch
is the main HTTP client that my team has used on frontend applications. My first hypothesis was that Fetch
Cache was configured improperly.
How cache works on Fetch https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
Easily, I could remember that I set the cache policy as no-cache
to avoid any stale data. Referring to the docs, no-cache
makes a conditional request whether it is fresh or not. This policy itself sounded reasonable to me except for the weird name. Whatever, I wanted to get rid of the repeated requests, thus, I thought that it might be working properly if I change it to default
, which skips a request if stale data exists on the browser.
However, the change could not resolve the problem. It worked samely and was far from what I expected. I was expecting that the browser cache works since we have fresh data with the proper Cache-Control
value. Unfortunately, I was still at the same step after the change. Did I miss something?
There was something that I did not find important. Right after the part of Cache-Control
on the docs, I found out that it is describing the header Vary
, which supports the variability of cache and I could see that the default value of Vary
of my server was including Cookie
. Yes, it was weird. The cache was working for every different cookie. It might be valuable if you treat every different cases by each user, however, the APIs that I wanted to cache had no needs like that. In the detail, Django Session has patched the Vary value. Thus, I fixed the part.
After fixing Vary
by removing Cookie
on it, I could see the disk cache on the Chrome Developer Tools and 200ms got faster in average.