You've been caching your content website wrong

This video features Rémy Sanchez at Wagtail Space NL 2024 in Arnhem, Netherlands.

You've been caching your content website wrong
0:20:38
Published June 27, 2024
125 views

Wagtail Space NL 2024 https://nl.wagtail.space

Summary

Rémy Sanchez argues that ETags are a useful alternative to time-based caching for content sites whose pages change infrequently but must become stale immediately when edited. Django can generate and validate a site-wide ETag, while deploys should rotate it as well so code and design changes are reflected; the browser and CDN still make a validation request, but unchanged pages need not be regenerated. He explains the extra proxy plumbing required for ETags, cache-key separation between frontend and API URLs, safe handling of private cookie-based responses, and recommends Apache Traffic Server for forwarding ETags, normalising compression headers, and performing fast Brotli or gzip compression.

Key takeaways

  • ETags let browsers and CDNs validate whether a page changed, avoiding backend rendering when it has not.
  • A site-wide ETag can be rotated on any content edit, while a build ID should rotate it after code or design changes.
  • ETag support is straightforward in Django and browsers but difficult to implement correctly in reverse proxies.
  • Responses involving cookies must be marked private, and frontend and API resources need distinct cache keys even when their public URLs match.
  • Apache Traffic Server can forward conditional requests, manage cache headers, normalise Accept-Encoding, and compress responses efficiently.

Summarised automatically from the transcript.

Questions this talk answers

How does HTTP ETag caching work, and why is it useful?

The server sends an ETag with a response, and the browser later asks whether that tag has changed. If it has not, the server returns 304 Not Modified, so the client reuses its cached response without regenerating the page; this shifts much of the caching burden away from the backend.

Discussed at 0:58

Which reverse proxy supports ETags reliably?

Rémy found that common options such as Nginx, Squid, Varnish, Cloudflare, Apache HTTPD, and Caddy did not provide the needed behavior straightforwardly. Apache Traffic Server supported ETags natively and was the practical choice for this setup.

Discussed at 3:16

What are the pros and cons of ETag caching versus time-based expiration?

ETags require a round trip to the server, so they are slower than a cache entry that is still fresh under a time-based policy. In return, changing the tag invalidates content immediately—including browser and CDN caches—without waiting for an expiry interval or calling vendor-specific purge APIs.

Discussed at 4:55

How do you implement site-wide ETag invalidation in Django?

Use one ETag for the whole site, store it through Django’s caching framework, and regenerate it whenever content is edited so the cache can rebuild itself. Wrap the page’s `serve` method with Django’s ETag decorator, which handles `If-None-Match` validation and 304 responses.

Discussed at 7:14

How do you make deployments invalidate cached pages as well as content edits?

Include the CI/CD build ID in the key used to store the ETag. When the source code or design changes and the build ID changes, Django automatically generates a new ETag instead of serving pages from the previous build.

Discussed at 7:59

How should a proxy handle ETags when a frontend and backend use the same URLs?

The proxy must forward the client’s `If-None-Match` header to the origin and return the origin’s ETag, cache-control, Vary, and 304 responses. To keep separately rendered frontend and backend resources from colliding in caches, the backend path is prefixed with a marker such as `__/foo` rather than relying on the often-ignored `Vary` header.

Discussed at 12:22

How can Apache Traffic Server compress cached responses efficiently?

Configure its compression and header-rewrite plugins with the encodings and MIME types to cache and generate. Traffic Server can perform Brotli compression in real time far faster than doing the same work in Django/Python.

Discussed at 18:27

Open full transcript Markdown

Transcript

3,605 words · auto-generated · en Show transcript

Automatically transcribed, so expect mistakes in names and technical terms.

Okay, here we go. So we are going to talk about cash again. So it's pretty independent from previous one we've we've had in the sense that we our scope is more on the browser slash proxy side, slash CDN. But with a specific approach that is the e tag mechanism. So it's not time based and it's a different approach that suits the suit like the needs that I had at the moment. Definitely not for everyone, but I'll show you the pros and cons for it. So the idea of the E-tag mechanism is something that saved my ass quite a couple of times.

For performance is pretty easy. When you reply to HTTP query, you say the tag of this query is whatever, random string, you decide. And then when the server asks for the same when the browser asks for the same resource again, they say, okay, tell me if it has changed since last e-tag. And you say yes or no. And if no, you just say it didn't change and the browser is like, oh fine, okay, I'll just display the one I had before. So There's a request to the server, but you don't need to generate the answer if the answer has not changed. And that's a great way to put the burden of caching on the client and not on the backend Like you don't need the Redis or whatever to cache stuff. Support for

e-tags is great in browsers, great in Django. terrible in proxies because it's actually very hard for proxies. Like imagine in the scenario the proxy has the thing in cache so There's a new client that doesn't have the thing in cache that asks the proxy give me this page. The proxy needs to because the proxy proxies, right? So it's going to relay the headers coming from the client So if the client did not put the if not match header in the request, then it needs to go get the if not match header that it has somewhere else, get a 304 from the server, and then reply with a 200 and the tag to the client. If you did not understand it doesn't matter, it's just to illustrate the point is pretty confusing. And you see here the

truth table that you need to implement, and that's a simplify simplified one, right? At the proxy level. So and then I tried many different options that didn't work out at all. So Nginx is complic I mean Nginx is I'm sure you can make it work with Nginx one way or the other, but I just Did not find it. Squid just ignores the thing altogether. Varnish almost does it but not exactly. Cloudflare ignores the tag, even though they say they support it. Apache HTTPD does not. I tried also you know all the CADI type all this well it didn't work out. In the end I like Apache Traffic Server, it's

you go to the website, it looks horrible. And then you're like oh my god, this thing must you know that date from Paleolithic era or something like this And it's it's not going to be nice, but actually it was supporting the thing natively and very easily and So I'm I'm very glad it pushed me to discover this thing but more on that later. So it used to be commercial so basically what happened with this traffic server it used to be commercial software made by a company that got acquired by Yahoo for something entirely different and they did not know what to do with it so they just said well let's open source it that's it. So it got open source given to the Apache Foundation. And it's out of all the things I've listed except for Vanish, I think it's the only one that is intended to be a reverse proxy.

That is made for this use case because all of them it's HTTP servers that accidentally do reverse proxy. And it has auto-comparation of content with simple plugins like GZ, Broadly, WebP, and so on. And also different use cases like you can authenticate against s3 bucket and have public and signing URLs and stuff like this. So really great piece of software but let's go on the attacks so we are basically having two things that is expiring things with it or expiring things with the time, right? So the attack you still need a round trip to the server, so like the latency is maybe not going to be great. So of course if you go through CDN you will do the round trip to the CDN and the CDN has a keep alive connection

to your back end so there's not so much handshaking happening but still you need to reach the server. The in the tag the real the content expires in real time like if you change the value of the tag, it's expired automatically. So that's that's really convenient if you don't want to I mean if you want immediate you know, eradication of cash. If it's time based you need to call an API or wait for the amount of time And which is in my opinion like for example I have the website for which I did this has lot of content. Expires pretty like that is edited pretty rarely. But if I edit it I want it to change quickly.

So I don't want to put a one week expiration on the pages when really I want them to expire automatically the attack is conceptually simple, not for the proxies, but for you know the browser, it's simple. But for the time-based expiration you need to call APIs and deal with vendor specific specificities to you know expire the stuff. The e-tag is fast enough. I had two second generation for my pages and now it's about a hundred millisecond. So that's good enough. That's not the best. The time-based will you know no need to run trip to the server. So It's going to be immediate. The e-tag is going to be longer. The e tag also works for the browser, so

if the browser and I mean the browser will also cache the different pages. So depending on your use case that can be interesting. Because you cannot expire remotely, you there's no API for the browser to expire the stuff, right? So having the tag in the browser to validate the content it can be pretty interesting. So it's really a question of how do you want to expire your content and what is the performance trade-off you want to be doing. And in my case it's definitely that was interesting. So how do I implement this? So basically I'm going to show you snippets of code that are integrated with model W that I talked about earlier. But you can it like it's the concept you can re-adapt

In any way you want is just like the different things to consider I'm going to list. So on the Django side, what we decided to do is have one e tag for the whole website to do any edit in the website. and it expires everything because then you don't have to because otherwise you know you change the title of a page, then you need to change it in the menu everywhere. or you change something, you know, it can be a read more section and so on. So there's a lot of things that can have, you know, there's a lot of possible repercussions. So since I don't edit the website that often, I prefer just to expire everything when there's an edit made and let the cache rebuild itself. So just needed to hook up to Vogtail

to clear the cache. And the clear cache is just so I'm using basically the Django caching framework. just to store the e-tag value and that's it. How do you generate this e-tag? Okay. So the tag is anything you want, it's any string you want. So it just generated random enough string And that's it. One thing that is important however is to also expire the tag when you rebuild your website because if you change your source code And the design has changed or whatever, you don't want to be serving an old version of your source code. So it's not just the content, it's also what the page looks like. And that's pretty easy with CICD to put you know

the build ID as an environment variable. So that's what we do. We have the build ID as an environment variable and we store it there So this key function allows us to store the e-tag in the Redis and then we get this key. And so basically if we change the build prefix, we are going to generate automatically a new e-tag. And the generation of the tag itself is just a random string of I don't know fifty characters length or something like this. Just one detail here, you see the W slash in front of the E tag, which means it's a weak E tag meaning that you can apply content transformations on the content and you'll see later where it's helpful so then you need to inject this e-tag into every page. And in the context of Vogtail

today it's a bit artisanal, right? You do it as you want. So what we decided to do is that we can have one model that is parent in terms of class over all the other class page and pass page classes in which we added two different attributes that is use e-tag yes or no and cache control headers where we set literally the content of the cache control headers and it's in the we put it in the promote section in the in the pages. So then we have a decorator that we use to decorate the serve method. That like it's conflicting a bit with a rotable page mixing, so it was a bit complicated to get it

right. But basically the idea is that we just invoke the e -tag decorator from Django and wrap the serve method with it and that's it. So this attack for this attack decorator basically will handle for you the checking if not match, if it matches then this and otherwise not and so on So it's all provided by Django. It's just some wrapping and plumbing. Then you need to fix the HTTP headers. So I discovered doing this that Django is actually very smart in dealing with HTTP headers. because the like if you put if you use the session for example it will automatically add in the vary header so that is the header that tells on which other HTTP

header you need to look to know what is your cache key. It will add the cookies to the very header if you use the session but otherwise not okay so and that for lots of things the JZIP needleware also will add its own stuff and so on. So it's pretty interesting. And there's just one thing that we need to do from that. That is the how to say, to check if the cookie is indeed in the very headers and if so to mark the cache as private no matter what because otherwise it means that we are potentially serving some private content to in the cache and caching it forever so that could be annoying. So my advice is do not enable the JZP middleware from

Django because if you put traffic server in front, traffic server is much better at doing this than the middleware from Django. And yeah that's it. So but the main point of this middleware is just to mark the cache as private if needs to and that just adding up with the other mechanisms of Longo there's another thing that is cash busting the thing. So if you remember the previous talk, right? There's I say it's a proxy. Like if you ask slash foo on the front end, the front end will ask slash foo from the API. But If the front end that runs in the browser asks for a slash foo, and that it needs to be the answer from the back end

and not from the front end, not the pre-rendered you know, thing from the front end. Then it can be very confusing because the same URL and it's completely different resources. And you could deal with it with a very header, but actually you could not because lots of software d ignores the very header. So bottom line is if you ask slash foo from the front end, then it's translated into a slash underscore row underscore slash foo. URL, so it's just a prefix. And in order not to trifle with Django roots and YTL routing and so on, I just modify here the path on the request. Object so that everybody thinks it's just like a request on slash instead of slash row and that's it.

Then on the next side, what do we do? So if you remember, the next side is a is a proxy that is adding JavaScript and CSS. But what you need to do when a request comes in, you need to look for the if non-match header and put it in your own request to the server. Otherwise the whole mechanism is broken. Same thing, you need to prefix your URLs with underscore row because otherwise you will not you will have the caching issue I was talking about And then you need to proxy back, so when the server replies, all the different cache control headers. So the vary, the tag.

cache control and then if the answer is not modified to reply as well not modified and basically next we create an error because there's a way to deal with it in a next, to say okay three or four not modified the same as if it was five hundred or 404 or 301. It's non-200 HTTP code basically and we are replying not modified. And the browser accepts it, so it's fine. And we there's no rendering process happening in next type because we just short shortcut it like this. Then how do you configure the forward proxy with the cache, right? So as I was saying, traffic server is very easy to use, but the request.

config file is horrible. And when you open the Debian version of this configuration file that has all the options already listed and commented, it's like a wall of text, like there's no space, it's just you know suffocating. So I created the Docker image of Traffic Server that is making it easier to use. It does two things. yaml, the records. config file, you can fill it up in YAML That is much more readable than the original syntax. And you can also interpolate environment variables in any configuration file for traffic server, so that's you know more the Docker way of life. So we have different files. So let's start with

remap. config, okay, that is And what you're going to see here is the full configuration, just so you understand it's very easy to configure. So basically here you map the URLs from what's you know you're going to get as an input and you map it to an origin server. So you say everything that is on slash back goes to my API and everything else goes to my frontend. Super straightforward. Here you see Django templatey stuff. It's not really Django template but inspired syntax. And that is the Docker image that does this. It's not stock with a traffic server. You have then the records. config file. So I'm not going to explain all the options, but three are pretty important.

First one is to limit the RAM used because otherwise you're going to like if you deploy it on Kubernetes and you did not put any limit on this, it will use all the RAM available for you know all the other containers. So You need to not forget to limit it. Of course I thought of that before pushing it to production. Then you have to configure the DNS resolution to be looking for the default domains. Again if you deploy in Kubernetes, that's how you know the internal URLs of API and front end. So by default not looking into that And then another one that I find extremely convenient is the normalize AE, that is normalize accept encoding because

The way the vary header works is that you say it varies depending on this header, this header, this header, but it's not semantic inside the header. So If one client says very GZIP says accept encoding and says gzip broadly and the other one says broadly gzip, it's two different headers. So you can have an infinite amount almost of you know variations. But since you don't even understand all the encodings possible and so on, it doesn't make any sense. So what it does is that it will sort them in a specific order and it will you know always accept I mean remove the ones that it does not understand. So basically when you configure it, you say okay, you understand

Gzip and botly and you normalize it this way and this way your page will be compressed well more on this later so We are going to use two plugins that are compress and header rewrite. Okay. So first one header rewriting is just to add some stuff. So there's a first thing to say if it's a hit or miss in the cache. And then remove the server and expowered by headers because it's well known that it's a great security improvement to hide the name of the server. And then we enable test compression and that's really an amazing part of it because you get is basically what Cloud Cloudflare

does, but it's like the open source version of Cloudflare so you say the algorithms that you want to handle, you want to you say you want to cache them and generate them, and you say which MIME types you want to compress, and then that's it. And it's it's blazing fast, it's much faster than GZP implementation of Django. It's doing broadly in real time. If you try to do it in Python, it's it's very slow. Like I mean to give you an example, broadly compression. on my pages it was 700 milliseconds when I tried to do in Python side but there it's you know insignificant so it's very good at doing this and I highly recommend using ATS also for that. So as a conclusion,

this is based on model W that I presented earlier, but even if you're not using it, obviously you can inspire your yourself from the different checkpoints. Like really each slide is a requirement that you need to follow if you want to implement it yourself. The tag is very convenient, at least for some use cases like mine and it's especially convenient if you want to expire pages immediately from and the browser and the CDN. Of course it has some drawbacks and I'm also very surprised in this process to have discovered the traffic server that is actually a great piece of software and very easy to use despite some looks that are a bit frightening.

And that will be it for this presentation.

Conference

Wagtail Space NL

June 12 - 14, 2024

Arnhem, Netherlands

Note: We understand that names change, people change, and bodies change. We respect each individual's journey and privacy. If you have any concerns about a video or need us to remove content, please don't hesitate to contact us. We will handle your request with care and promptly address any issues.

More videos by Rémy Sanchez

More videos from Wagtail Space NL