Lesson 16 / الدرس 16

Caching: the request that never happens / التخزين المؤقت: الطلب الذي لا يحدث

The fastest request is the one nobody makes. Browsers keep copies of what they fetched, and two headers decide how long — which is also why a change you deployed is invisible to you.

أسرع طلب هو الذي لا يقوم به أحد. فالمتصفحات تحتفظ بنسخ مما جلبته، وترويستان تقرران المدة — وهو أيضًا سبب اختفاء تغيير نشرته عن عينيك.

The second visit to a site is almost always faster than the first, and not because anything improved. The browser kept what it fetched — the stylesheet, the fonts, the logo — and on the next page it uses its own copy instead of asking again. That store is the cache, and the server controls it.

Two questions, two headers

Cache-Control: max-age=31536000, immutable    ← keep it a year, it will never change
Cache-Control: max-age=300                     ← keep it five minutes
Cache-Control: no-store                        ← never keep this at all
ETag: "a91f3c"                                 ← a fingerprint of this exact version
The first header answers "may I keep this, and for how long". The second answers a different question: when the time is up, has it actually changed? The browser sends the fingerprint back and the server replies 304 Not Modified — the code from lesson 8 — with no body at all if it still matches.
What is being asked forSensible policyReason
The HTML pageno-cache, or a few minutesIts content changes; it names everything else
A stylesheet or scriptA year, with a version in the filenameThe name changes when the file does
A photo or logoWeeks to a yearRarely changes, and large
A logged-in pageno-storeIt must never sit in a shared cache
A price or a stock countno-storeA stale answer here is a wrong answer

The second row is the pattern behind everything else. Cache the parts that are named precisely, and keep the page that names them fresh.

Why the deploy you just made is invisible

You change the stylesheet, upload it, reload, and nothing happens. The browser is not broken and neither is the server: you told the browser a year ago — in cache terms — that style.css was good for a year, and it is honouring that. The file on the server changed; the instruction about it did not.

<link rel="stylesheet" href="/assets/css/site.css">           <!-- a year of guessing -->
<link rel="stylesheet" href="/assets/css/site.css?v=27">      <!-- a new address, so a new file -->
The standard fix, and it is a trick worth recognising: change the address whenever the file changes. A different address is a different resource as far as the cache is concerned, so it fetches it and you still get a year of caching on the version before it. This very site does exactly that.

Check yourself / اختبر نفسك

1. You uploaded a new stylesheet but the site looks unchanged. Most likely reason?

2. What does a 304 response contain?

3. Which of these must never be cached?