HTTP keşləmə
Brauzer və CDN cavabı yenidən istifadə edib-etməyəcəyinə necə qərar verir: Cache-Control, təzəlik və 304 revalidasiyasından tutmuş hash-li faylara, stale-while-revalidate-ə, Vary-yə, paylaşılan keşdə şəxsi məlumatlara və CDN-in təmizlənməsinə qədər.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
HTTP keşləmə nədir və keşlər harada olur
HTTP keşi cavabları saxlayır və sonrakı sorğularda onları yenidən istifadə edir, beləcə cavab origin serverdən təkrar gəlmək məcburiyyətində qalmır. Keşdən gələn cavab bütöv bir round trip-ə qənaət edə, origin-in yükünü azalda bilər, təkrar ziyarəti isə, xüsusən CSS və skriptlər keşdən gələndə, demək olar ki, ani edir. Amma səhv keş cavabı istifadəçiyə köhnə və ya başqasının məlumatını göstərir. Ona görə keşləmə sürət qədər düzgünlük məsələsidir.
Keşlər harada olur
- Private (şəxsi) keş — bir klientə məxsusdur, adətən brauzerin HTTP keşidir. Şəxsi cavabları saxlaya bilər, çünki onları yalnız həmin istifadəçi görəcək.
- Shared (paylaşılan) keş — klientlərlə origin arasında dayanır və çox istifadəçiyə xidmət edir: CDN, reverse proxy (nginx, Varnish) və ya korporativ proxy. O, bir istifadəçinin şəxsi cavabını heç vaxt başqasına verməməlidir.
/app.js sorğusu hər ikisindən keçə bilər: əvvəlcə brauzer öz keşinə baxır, sonra CDN öz keşinə, origin-ə isə yalnız hər ikisində tapılmayan sorğu çatır.
Keş açarı
Keş cavabları keş açarı ilə axtarır. RFC 9111-ə görə açarda ən azı sorğunun metodu və hədəf URI olur. Keşlərin çoxu yalnız GET cavablarını saxladığı üçün praktikada açar query string də daxil olmaqla tam URL-dir. Vary cavab başlığı açara sorğu başlıqlarını əlavə edir (bu barədə senior bölmələrində). Cavabın asılı olduğu başqa hər şey — cookie, istifadəçinin ölkəsi — sən onu açara qoymasan, açarda yoxdur.
Təzə və ya köhnəlmiş
Server təkrar istifadəni Cache-Control cavab başlığı ilə təsvir edir:
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=3600
ETag: "5f2a-19c"Növbəti bir saat bu cavab təzədir (fresh): keş onu heç kimdən soruşmadan yenidən istifadə edə bilər. Sonra o, köhnəlir (stale). Köhnəlmiş cavab atılmır: keş origin-dən onun hələ də keçərli olub-olmadığını soruşur (şərti sorğu), origin isə ya gövdəsiz 304 Not Modified, ya da yeni 200 qaytarır.
Əsas məqamlar
- Keşləmə susmaya görə açıqdır:
Cache-Control-suz cavab da evristik qaydada keşlənə bilər, ona görə nə istədiyini həmişə açıq yaz. - Təzəlik soruşmağın lazım olub-olmadığını, revalidasiya isə yenidən yükləməyin lazım olub-olmadığını həll edir.
- Açar saxlanılan cavablardan hansının veriləcəyini müəyyən edir. Keşləmə bug-larının çoxu cavabın asılı olduğu nəyisə nəzərə almayan açardan yaranır.
An HTTP cache stores responses and reuses them for later requests, so the response does not have to travel from the origin server again. A cache hit can save a whole round trip, take load off the origin and make a repeat visit feel instant, especially for CSS and scripts. A wrong cache hit shows users old or someone else's data, so caching is as much about correctness as about speed.
Where caches live
- Private cache — belongs to one client, usually the browser's HTTP cache. It may store personalised responses, because only that user will see them.
- Shared cache — sits between clients and the origin and serves many users: a CDN, a reverse proxy (nginx, Varnish) or a corporate proxy. It must never hand one user's personal response to another user.
A request for /app.js can pass through both: the browser checks its own cache, then the CDN checks its cache, and only a miss in both reaches the origin.
The cache key
A cache looks responses up by a cache key. RFC 9111 says it contains at least the request method and the target URI; most caches store only GET responses, so in practice the key is the full URL, query string included. The Vary response header adds request headers to the key (more on that in the senior sections). Anything else the response depends on — a cookie, the user's country — is not in the key unless you put it there.
Fresh or stale
The server describes reuse with the Cache-Control response header:
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=3600
ETag: "5f2a-19c"For the next hour this response is fresh: the cache may reuse it without asking anyone. After that it is stale. A stale response is not thrown away; the cache asks the origin whether it is still valid (a conditional request), and the origin answers 304 Not Modified without a body, or sends a new 200.
Key points
- Caching is on by default: a response without
Cache-Controlcan still be cached heuristically, so always say explicitly what you want. - Freshness decides whether to ask; validation decides whether to download again.
- The key decides which stored response is used. Most caching bugs are a key that misses something the response depends on.
Təzəlik: max-age, Expires, Age və evristika
Keşdəki cavab yaşı (age) təzəlik müddətindən (freshness lifetime) az olduqca təzədir. RFC 9111 bu müddəti uyğun gələn ilk qaydadan götürür:
- Paylaşılan keşdə
Cache-Control-dakıs-maxage=N. Cache-Control-dakımax-age=N.ExpiresiləDatearasındakı fərq (iki mütləq tarix).- Heç biri yoxdursa, açıq müddət yoxdur və keş evristikadan istifadə edə bilər.
Cache-Control: max-age=60, s-maxage=600
Expires: Mon, 16 Nov 2026 12:00:00 GMT
Date: Mon, 16 Nov 2026 10:00:00 GMTCDN bu cavabı 600 saniyə, brauzer isə 60 saniyə saxlayır və hər ikisi Expires-a məhəl qoymur, çünki max-age (paylaşılan keşdə isə s-maxage) üstündür. Expires HTTP/1.0-dan qalıb: mütləq tarix saatların düzgün olmasından asılıdır, max-age da məhz buna görə onu əvəz edib. Yanlış formatlı Expires, məsələn tez-tez rast gəlinən Expires: 0, keçmiş zaman kimi qəbul olunmalıdır, yəni cavab artıq köhnəlib.
Age
CDN bir müddət saxladığı cavabı verəndə Age başlığı göndərir: cavabın origin-də yaradılmasından və ya son dəfə yoxlanmasından neçə saniyə keçib:
Cache-Control: max-age=600
Age: 540Brauzer bu vaxtı da hesaba qatır: bu cavab brauzerdə 600 yox, cəmi 60 saniyə də təzə qalacaq. RFC-nin tam düsturu Date başlığını və şəbəkə gecikməsini də nəzərə alır, amma "Age üstəgəl mənim keşimdə keçən vaxt" praktikada kifayət edən yaxınlaşmadır. Uzun max-age ilə işləyən CDN-in məzmunu gözlədiyindən köhnə göstərməsinin səbəbi də budur.
Evristik təzəlik
Cavabda max-age, s-maxage və ya Expires yoxdursa, keş təxmin edə bilər. RFC Last-Modified-dən keçən vaxtın bir hissəsini, adətən 10%-ni tövsiyə edir: 10 gün əvvəl dəyişdirilmiş fayl təxminən bir gün heç kimdən soruşulmadan yenidən istifadə oluna bilər. Evristika yalnız evristik keşlənə bilən status kodlarına (200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414 və 501) və ya public ilə işarələnmiş cavablara aiddir.
Bunun yaratdığı real bug: API endpoint-i və ya HTML səhifə Cache-Control-suz, amma statik fayl serverinin qoyduğu Last-Modified ilə gedir və istifadəçilər deploy-dan sonra da dünənki versiyanı görür. Həll Cache-Control-u həmişə açıq göndərməkdir — cavab no-cache olsa belə.
Qısa qaydalar
max-age-ə üstünlük ver;Expiresyalnız çox köhnə keşlər üçün ehtiyat variantdır.- CDN nəyisə brauzerlərdən uzun saxlaya bilirsə,
s-maxageişlət. - "Təzə" sadəcə "origin-ə müraciət etmədən yenidən istifadə oluna bilər" deməkdir, bundan artıq heç nə.
A cached response is fresh while its age is less than its freshness lifetime. RFC 9111 takes the lifetime from the first rule that matches:
- In a shared cache,
s-maxage=NfromCache-Control. max-age=NfromCache-Control.ExpiresminusDate(two absolute dates).- Otherwise there is no explicit lifetime, and the cache may use a heuristic.
Cache-Control: max-age=60, s-maxage=600
Expires: Mon, 16 Nov 2026 12:00:00 GMT
Date: Mon, 16 Nov 2026 10:00:00 GMTA CDN keeps this response for 600 seconds, a browser for 60, and both ignore Expires, because max-age (or s-maxage in a shared cache) wins. Expires comes from HTTP/1.0; an absolute date depends on correct clocks, which is why max-age replaced it. An invalid Expires, such as the common Expires: 0, must be treated as a time in the past: already stale.
Age
When a CDN serves a response it has held for a while, it sends an Age header with the seconds since the response was generated or last validated at the origin:
Cache-Control: max-age=600
Age: 540The browser counts that time too: this response is fresh in the browser for only 60 more seconds, not 600. The full RFC formula also accounts for the Date header and the network delay; "Age plus time in my cache" is the useful approximation. This is why a CDN with a long max-age can make content look older than you expect.
Heuristic freshness
If a response has no max-age, s-maxage or Expires, a cache may guess. The RFC suggests a fraction of the time since Last-Modified, typically 10%: a file last modified 10 days ago may be reused for about a day without asking. Heuristics apply only to status codes defined as heuristically cacheable (200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414 and 501) or to responses marked public.
A real bug this causes: an API endpoint or HTML page sent without Cache-Control but with Last-Modified from a static file server, and users keep seeing yesterday's version after a deploy. The fix is to always send Cache-Control explicitly — even if the answer is no-cache.
Quick rules
- Prefer
max-age;Expiresis only a fallback for very old caches. - Use
s-maxagewhen the CDN may keep something longer than browsers. - "Fresh" means "may be reused without contacting the origin", nothing more.
no-cache, no-store, must-revalidate, private, public
Ən çox qarışıqlıq yaradan cavab direktivləri, RFC 9111-in təriflərinə görə:
no-cache— cavabı saxlamaq olar, amma əvvəlcə origin-lə yoxlamadan yenidən istifadə etmək olmaz. Bu, "keşləmə" demək deyil.ETagvarsa, hər təkrar istifadə kiçik bir şərti sorğuya başa gəlir və adətən304ilə bitir.no-store— heç bir keş (şəxsi və ya paylaşılan) sorğunu və cavabı saxlaya bilməz. Heç yerə yazılmamalı cavablar üçündür: bank çıxarışı, birdəfəlik token. Eyni URL-in əvvəl saxlanmış nüsxəsini isə silmir.must-revalidate— cavab təzə olduqca yenidən istifadə oluna bilər; köhnələndən sonra isə istifadədən əvvəl yoxlanmalıdır və heç vaxt köhnəlmiş halda verilə bilməz (origin əlçatmazdırsa, keş504kimi xəta qaytarır). O,stale-while-revalidatekimi icazələrdən üstündür.private— onu yalnız şəxsi (brauzer) keşi saxlaya bilər. Şəxsi cavablar üçün işlət: login-dən sonrakı səhifələr, səbət, hesab səhifələri.public— paylaşılan keş onu adətən saxlaya bilmədiyi halda da saxlaya bilər, ən çox daAuthorizationbaşlıqlı sorğunun cavabını. Buna nadir hallarda ehtiyac olur; onu "keş işləsin deyə" əlavə etsən, CDN autentifikasiyalı cavabları paylaşa bilər.s-maxage=N— yalnız paylaşılan keşlər üçün təzəlik müddəti; şəxsi keşlər ona baxmır.publickimi, o da paylaşılan keşəAuthorization-lı sorğuların cavablarını yenidən istifadə etməyə icazə verir.
Direktivlər bir-biri ilə ziddiyyət təşkil edəndə (məsələn, max-age=600, no-cache) RFC ən sərt olana əməl etməyi deyir.
Tipik birləşmələr
Cache-Control: no-cache
Cache-Control: no-cache, private
Cache-Control: no-store
Cache-Control: max-age=31536000, immutableBirincisi ictimai HTML üçündür: həmişə yoxla, yalnız dəyişəndə yüklə. İkincisi MDN-in şəxsi səhifələr üçün standart tövsiyəsidir: brauzer saxlaya bilər, CDN saxlaya bilməz, hər təkrar istifadə yoxlanır. Üçüncüsü həqiqətən həssas məlumat üçündür; bir çox brauzerdə o, back/forward cache-i də söndürür, ona görə onu refleks kimi işlətmə. Dördüncüsü məzmunu dəyişəndə URL-i də dəyişən fayllar üçündür.
max-age=0, must-revalidate no-cache kimi işləyir; o, köhnə HTTP/1.0 keşləri no-cache-i başa düşmədiyi üçün yaranıb. "Hər şeyi bir yerə yığan" no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate isə cargo cult-dur: saxlamağı tək no-store artıq qadağan edir.
Sorğu direktivləri
Cache-Control sorğularda da olur. Adi reload Cache-Control: max-age=0 və şərti başlıqlar göndərir, ona görə keşlər yoxlama aparır; məcburi reload şərtsiz no-cache göndərir və origin tam 200 qaytarır. Kodda fetch(url, { cache: "no-cache" }) yoxlama aparır, fetch(url, { cache: "reload" }) isə keşdən tamamilə yan keçir.
The response directives that cause the most confusion, as RFC 9111 defines them:
no-cache— the response may be stored, but it must not be reused without validating it with the origin first. It does not mean "don't cache". With anETag, each reuse costs a small conditional request that usually ends in304.no-store— no cache, private or shared, may store the request or the response. Use it for responses that must never be written anywhere: a bank statement, a one-time token. It does not delete a copy stored earlier under the same URL.must-revalidate— the response may be reused while fresh; once stale, it must be validated before reuse and may never be served stale (if the origin is unreachable, the cache returns an error such as504). It overrides permissions likestale-while-revalidate.private— only a private (browser) cache may store it. Use it for personalised responses: after login, a cart, account pages.public— a shared cache may store it even where it otherwise could not, most notably for a request with anAuthorizationheader. You rarely need it; adding it "to make caching work" can make a CDN share authenticated responses.s-maxage=N— the lifetime for shared caches only; private caches ignore it. Likepublic, it also lets a shared cache reuse responses to requests withAuthorization.
When directives conflict (for example max-age=600, no-cache), the RFC says to honour the most restrictive one.
Common combinations
Cache-Control: no-cache
Cache-Control: no-cache, private
Cache-Control: no-store
Cache-Control: max-age=31536000, immutableThe first suits public HTML: always check, download only when changed. The second is MDN's default for personalised pages: the browser may keep the page, the CDN may not, and every reuse is validated. The third is for truly sensitive data; it also costs you the back/forward cache in many browsers, so do not use it by reflex. The fourth is for files whose URL changes when their content changes.
max-age=0, must-revalidate behaves like no-cache; it exists because old HTTP/1.0 caches did not understand no-cache. The "kitchen sink" no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate is cargo cult: no-store alone already forbids storing.
Request directives
Cache-Control also exists on requests. A normal reload sends Cache-Control: max-age=0 plus conditional headers, so caches validate; a forced reload sends no-cache without conditions, so the origin sends a full 200. In code, fetch(url, { cache: "no-cache" }) validates and fetch(url, { cache: "reload" }) bypasses the cache.
Revalidasiya: ETag, Last-Modified və 304
Saxlanmış cavab köhnələndə (və ya no-cache ilə işarələnəndə) keş onu kor-koranə yenidən yükləmir. O, saxladığı validator-larla şərti sorğu göndərir, nəyinsə dəyişib-dəyişmədiyinə isə origin qərar verir.
GET /index.html HTTP/1.1
Host: shop.example
If-None-Match: "33a64df5"
If-Modified-Since: Mon, 16 Nov 2026 08:00:00 GMTHTTP/1.1 304 Not Modified
Cache-Control: no-cache
ETag: "33a64df5"
Date: Mon, 16 Nov 2026 10:00:00 GMT304-ün gövdəsi olmur. Keş saxladığı başlıqları onunla yeniləyir (yeni Date, Cache-Control, ETag) və artıq əlində olan gövdəni verir. Sorğu yenə bir round trip aparır, amma bütöv resurs əvəzinə cəmi bir neçə yüz bayt.
İki validator
ETag/If-None-Match— serverin seçdiyi qeyri-şəffaf versiya identifikatoru, çox vaxt məzmunun hash-i.W/"…"zəif (weak) ETag-dir: bayt-bayt eyni yox, "mənaca eyni" deməkdir. Sorğuda hər iki şərt varsa,If-None-Matchüstün tutulur.Last-Modified/If-Modified-Since— dəqiqliyi bir saniyə olan tarix. Eyni saniyə içində iki dəyişiklik və ya hər deploy-da vaxt damğası dəyişən fayl onu etibarsız edir.
Mümkünsə ETag göndər, əlində varsa Last-Modified-i də.
Praktikada nə görürsən
- Chrome DevTools-da təzə keş cavabı Size sütununda "(disk cache)" və ya "(memory cache)" yazılmış
200-dür, şəbəkəyə heç bir sorğu getməyib. Revalidasiya isə304statuslu real sorğudur. fetch()revalidasiyanı gizlədir: şərti başlıqları brauzer özü əlavə edib304alanda sənin kodun keşdəki cavabı200statusu ilə alır.If-None-Match-i özün qoysan, brauzer öz keşini kənarda saxlayır və kod304-ü görür.
const response = await fetch("/api/catalog", { cache: "no-cache" });
console.log(response.status); // 200Şəbəkədən 304 gəlsə belə, konsolda 200 görünür.
Bilməyə dəyər bug-lar
- Hər serverdə fərqli ETag. Load balancer arxasındakı hər maşın eyni fayl üçün öz ETag-ini hesablayırsa (məsələn, inode nömrələrindən), sorğu başqa maşına düşəndə yoxlama uğursuz olur və hər yoxlama tam yükləməyə çevrilir.
- Dinamik HTML-də validator-lar. Render-dən sonra hesablanan ETag trafikə qənaət edir, amma server hər sorğuda bütün işi görür. Daha ucuz ETag məlumatın versiya nömrəsindən və ya
updatedAt-indən alınır. - Revalidasiya təzəlik deyil. Yaxşı ETag ilə
no-cachesürətlidir, amma yenə də hər təkrar istifadəyə bir round trip deməkdir; heç vaxt dəyişməyən fayllar üçün uzun təzəlik müddəti ver.
When a stored response is stale (or marked no-cache), the cache does not download it blindly. It sends a conditional request with the validators it stored, and the origin decides whether anything changed.
GET /index.html HTTP/1.1
Host: shop.example
If-None-Match: "33a64df5"
If-Modified-Since: Mon, 16 Nov 2026 08:00:00 GMTHTTP/1.1 304 Not Modified
Cache-Control: no-cache
ETag: "33a64df5"
Date: Mon, 16 Nov 2026 10:00:00 GMTA 304 has no body. The cache updates the stored headers from it (new Date, Cache-Control, ETag) and serves the body it already has. The request still costs a round trip, but only a few hundred bytes instead of the whole resource.
Two validators
ETag/If-None-Match— an opaque version identifier chosen by the server, often a content hash.W/"…"marks a weak ETag: "semantically the same" rather than byte-for-byte identical. If a request carries both conditions,If-None-Matchtakes precedence.Last-Modified/If-Modified-Since— a date with one-second resolution. Two changes within the same second, or a file whose timestamp changes on every deploy, make it unreliable.
Send an ETag when you can, and Last-Modified as well if you have it.
What you see in practice
- In Chrome DevTools a fresh hit is a
200with "(disk cache)" or "(memory cache)" in the Size column; no request went out. A revalidation is a real request with status304. fetch()hides revalidation: when the browser adds the conditional headers itself and gets a304, your code receives the cached response with status200. If you setIf-None-Matchyourself, the browser leaves its cache out of it and your code sees the304.
const response = await fetch("/api/catalog", { cache: "no-cache" });
console.log(response.status); // 200The log says 200 even when the network answer was a 304.
Bugs worth knowing
- ETags that differ per server. If every machine behind a load balancer computes its own ETag for the same file (for example from inode numbers), validation fails whenever the request lands on another machine, and every check becomes a full download.
- Validators on dynamic HTML. An ETag computed after rendering still saves bandwidth, but the server does the full work for every request. Cheaper ETags come from a version number or
updatedAtof the data. - Validation is not freshness.
no-cachewith a good ETag is fast, but it is still one round trip per reuse; for files that never change, use long lifetimes instead.
Praktik sxem: hash-li fayllar, qısaömürlü HTML, API-lər
Veb tətbiqlərin çoxuna bir neçə başlıq dəsti bəs edir. İdeya belədir: məzmunu heç vaxt dəyişməyən URL əbədi keşlənə bilər, məzmunu dəyişən URL isə yoxlanmalıdır.
Hash-li fayllar: əbədi keşlə
Bundler-lər fayl adına məzmunun hash-ini yazır: /assets/index-e41d07.js. Kod dəyişəndə hash, deməli URL də dəyişir, ona görə köhnə URL heç vaxt yeni məzmun üçün istifadə olunmur ("cache busting"):
Cache-Control: public, max-age=31536000, immutableBir il şərti "əbədi" sayılır. immutable brauzerə deyir ki, fayl təzə olduqca, hətta reload zamanı belə, onu yoxlamasın. MDN-in uyğunluq cədvəlinə görə Firefox və Safari bunu dəstəkləyir, Chrome isə bu direktivi tətbiq etmir (orada onu göndərmək zərərsizdir). public burada vacib deyil: MDN onu nümunədə işlədir, amma yalnız lazım olanda əlavə etməyi tövsiyə edir.
HTML: həmişə yoxla
HTML sənəd giriş nöqtəsidir: cari hash-li faylların adları ondadır, onun URL-inə isə versiya əlavə etmək olmur. İstifadəçilər deploy-dan dərhal sonra yeni siyahını alsın deyə o, revalidasiya olunmalıdır:
Cache-Control: no-cache
ETag: "AAPuIbAOdvAGEETbgAAAAAAABAAE"Səhifə şəxsidirsə, no-cache, private işlət. HTML-ə uzun max-age vermək klassik "istifadəçilər günlərlə köhnə versiyanı görür" bug-ıdır: brauzer keşlərindən cavabı geri çağırmağın yolu yoxdur.
API-lər və məlumat
Bir az köhnə ola bilən ictimai məlumat (məhsul siyahısı, valyuta məzənnələri cədvəli):
Cache-Control: max-age=10, s-maxage=60, stale-while-revalidate=30Brauzerlər cavabı ən çoxu 10 saniyə (CDN-in bildirdiyi Age də hesaba daxildir), CDN isə 60 saniyə yenidən istifadə edir. Sonra daha 30 saniyə ərzində istənilən keş köhnəlmiş nüsxə ilə cavab verə bilər, təzəsini isə arxa planda gətirir. Bu, stale-while-revalidate-dir (RFC 5861): istifadəçi yenilənməni gözləmir, origin isə hər ziyarətçidən yox, hər CDN məntəqəsindən hər URL üçün təxminən dəqiqədə bir sorğu alır. Brauzerlər də bunu dəstəkləyir (Chrome 75, Firefox 68, Safari 14).
stale-if-error=N origin xəta verəndə (500, 502, 503, 504 və ya əlçatmaz şəbəkə) keşə N saniyə köhnəlmiş nüsxə ilə cavab verməyə icazə verir. Qeyri-stabil origin qarşısındakı CDN-də faydalıdır; CDN-inin bunu dəstəklədiyini yoxla.
Şəxsi və ya tranzaksiya məlumatı (səbət, hesab, checkout qiyməti):
Cache-Control: no-storevə ya brauzer geri qayıdış üçün nüsxə saxlaya bilərsə, private, no-cache.
Deploy ardıcıllığı vacibdir
Deploy-dan sonra köhnə HTML-i hələ açıq olan istifadəçilər köhnə hash-li faylları istəyir. Əvvəlcə yeni faylları yüklə, HTML-i ən sonda dəyiş və köhnə faylları bir müddət saxla. Onları silsən, sonradan chunk-ı lazy yükləyən hər açıq tab sınır (Chromium-da TypeError: Failed to fetch dynamically imported module, webpack tətbiqlərində ChunkLoadError).
Most web apps need only a few header sets. The idea behind them: a URL that never changes its content can be cached forever, and a URL that does change must be checked.
Hashed assets: cache forever
Bundlers put a content hash in file names: /assets/index-e41d07.js. When the code changes, the hash and therefore the URL change, so an old URL is never reused for new content ("cache busting"):
Cache-Control: public, max-age=31536000, immutableOne year is the conventional "forever". immutable tells the browser not to revalidate the file while it is fresh, even on reload; per MDN's compatibility data Firefox and Safari support it, while Chrome does not implement the directive (sending it there is harmless). public is not required here — MDN uses it in its example, but advises adding it only when you need it.
HTML: always check
The HTML document is the entry point that names the current hashed files, and its URL cannot be versioned. It must be revalidated so users get the new asset list right after a deploy:
Cache-Control: no-cache
ETag: "AAPuIbAOdvAGEETbgAAAAAAABAAE"If the page is personalised, use no-cache, private. A long max-age on HTML is the classic "users see the old version for days" bug: there is no way to recall a response from browsers' caches.
APIs and data
Public data that may be a little old (a product list, an exchange-rate table):
Cache-Control: max-age=10, s-maxage=60, stale-while-revalidate=30Browsers reuse the response for up to 10 seconds (counting the Age the CDN reports), the CDN for 60. After that, for 30 more seconds, either cache may answer with the stale copy while fetching a fresh one in the background. That is stale-while-revalidate (RFC 5861): users do not wait for the refresh, and the origin gets roughly one request per URL per minute from each CDN location instead of one per visitor. Browsers support it too (Chrome 75, Firefox 68, Safari 14).
stale-if-error=N lets a cache answer with a stale copy for N seconds when the origin fails (500, 502, 503, 504 or an unreachable network) — useful on a CDN in front of a flaky origin; check that your CDN supports it.
Personal or transactional data (cart, account, checkout quote):
Cache-Control: no-storeor private, no-cache if the browser may keep a copy for back navigation.
Deploy order matters
After a deploy, users who still have the old HTML request old hashed files. Upload new assets first, switch the HTML last, and keep old assets for a while; deleting them breaks every open tab that lazy-loads a chunk later (TypeError: Failed to fetch dynamically imported module in Chromium, ChunkLoadError in webpack apps).
Brauzer keşləri, service worker-lər və CDN-in təmizlənməsi
"Brauzer keşləyib" ifadəsi qaydaları fərqli olan üç ayrı mexanizm demək ola bilər. Debug edəndə doğrusunun adını çək.
HTTP keşi
Yuxarıda deyilənlərin hamısı bura aiddir. DevTools keşdən gələn cavabı "(memory cache)" və ya "(disk cache)" kimi göstərir: bu, brauzerin cavabı harada saxladığıdır, ayrı qaydalar dəsti deyil. Müasir brauzerlər bu keşi həm də top-level sayta görə bölür (partitioning), ona görə ictimai CDN-dən yüklənən kitabxananı iki fərqli sayt ayrı-ayrılıqda yükləyir.
Back/forward cache (bfcache)
İstifadəçi səhifədən gedəndə bfcache bütöv səhifənin, JavaScript heap-i də daxil olmaqla, snapshot-ını saxlayır və Back/Forward düyməsində onu dərhal bərpa edir. Səhifəni oradan bərpa etmək ümumiyyətlə sorğu göndərmir, MDN də xəbərdarlıq edir ki, no-cache tarixçə naviqasiyalarında revalidasiyaya zəmanət vermir. Cache-Control: no-store ilə gələn səhifələr ənənəvi olaraq bfcache-ə düşmür (web.dev yazır ki, Chrome bunu dəyişmək üzərində işləyir). Səhifə bfcache-də qalarkən köhnələ bilən məlumatı, məsələn səbətdəki məhsul sayını, pageshow-da yenilə:
window.addEventListener("pageshow", (event) => {
if (event.persisted) refreshCartBadge();
});Service worker-in Cache API-si
caches.open() və cache.put() sənin kodunun idarə etdiyi yaddaşdır. MDN: Cache API HTTP keşləmə başlıqlarına əməl etmir və qeydlər sən silməyincə heç vaxt vaxtı keçmir. Ondan cavab verən service worker təzəliyə özü qərar verir (cache first, network first, strategiya kimi stale-while-revalidate). Onun öz fetch() çağırışları isə adi sorğular kimi HTTP keşindən keçir, ona görə URL-lər hash-li deyilsə və ya cache: "no-cache" ilə gətirilmirsə, precache addımı köhnəlmiş nüsxə saxlaya bilər.
Təmizləmə (invalidation)
Brauzerlərdə saxlanmış cavabı vaxtı bitməmiş geri çağırmaq olmur; Clear-Site-Data: "cache" brauzer keşini yalnız həmin başlığı alan istifadəçi üçün təmizləyir, aralıq keşlərə isə təsir etmir. Dəyişən URL-lər üçün brauzer müddətlərinin qısa saxlanmasının səbəbi budur. CDN isə idarə olunan keşdir və onu təmizləmək (purge) olar:
- Fayllar üçün versiyalı URL-lər: təmizləməyə ehtiyac yoxdur, yeni deploy yeni URL-lər işlədir.
- Məzmunu dərc edəndən sonra URL və ya prefiks üzrə purge.
- Teq üzrə purge: origin cavabları etiketləyir (Fastly-də
Surrogate-Key, Cloudflare-dəCache-Tag) və, məsələn, 42 nömrəli məhsulun qiyməti dəyişəndə bir çağırış onu göstərən bütün səhifələri təmizləyir. - Soft purge (dəstəklənirsə) qeydləri silmir, köhnəlmiş kimi işarələyir, beləcə yenidən doldurma zamanı
stale-while-revalidatevəstale-if-errorişləməyə davam edir.
Geniş yayılmış bölgü belədir: CDN üçün uzun s-maxage və hadisəyə görə purge, təmizləyə bilmədiyin brauzerlər üçün isə qısa max-age və ya no-cache. RFC 9213-dəki CDN-Cache-Control başlığı CDN-in müddətini Cache-Control-dan ayrıca daşıya bilər.
"The browser cached it" can mean three different mechanisms with different rules. Name the right one when debugging.
The HTTP cache
Everything above applies here. DevTools labels a hit "(memory cache)" or "(disk cache)": that is where the browser happened to keep the response, not a different set of rules. Modern browsers also partition this cache by the top-level site, so a library loaded from a public CDN by two different sites is downloaded once per site.
The back/forward cache (bfcache)
The bfcache keeps a snapshot of the whole page, including its JavaScript heap, when the user navigates away, and restores it instantly on Back or Forward. Restoring a page from it makes no requests at all, and MDN warns that no-cache does not guarantee revalidation on history navigations. Pages sent with Cache-Control: no-store have historically been excluded from the bfcache (web.dev notes that Chrome is working on changing this). Data that can go stale while the page sits in the bfcache, such as a cart count, should be refreshed on pageshow:
window.addEventListener("pageshow", (event) => {
if (event.persisted) refreshCartBadge();
});The service worker's Cache API
caches.open() and cache.put() are storage that your code manages. MDN: the Cache API does not honour HTTP caching headers, and entries never expire unless you delete them. A service worker that serves from it decides freshness itself (cache first, network first, stale-while-revalidate as a strategy). Its own fetch() calls go through the HTTP cache like any other, so a precache step can store a stale copy unless the URLs are hashed or fetched with cache: "no-cache".
Invalidation
A response stored in browsers cannot be recalled before it expires; Clear-Site-Data: "cache" clears the browser cache only for a user who receives that header, and has no effect on intermediaries. That is why browser lifetimes for changing URLs stay short. A CDN, on the other hand, is a managed cache you can purge:
- Versioned URLs for assets: nothing to purge, the new deploy uses new URLs.
- Purge by URL or prefix after publishing content.
- Purge by tag: the origin labels responses (Fastly's
Surrogate-Key, Cloudflare'sCache-Tag) and one call purges every page that shows, say, product 42 when its price changes. - Soft purge (where offered) marks entries stale instead of deleting them, so
stale-while-revalidateandstale-if-errorkeep working during the refill.
A common split is a long s-maxage with event-driven purges for the CDN, and a short max-age or no-cache for browsers, which you cannot purge. RFC 9213's CDN-Cache-Control header can carry the CDN's lifetime separately from Cache-Control.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Keş saxlanmış cavabı təzə olduqca və Cache-Control icazə verdikcə yenidən istifadə edir. Cavab köhnələndə keş If-None-Match və ya If-Modified-Since ilə şərti sorğu göndərir və ya 304, ya da yeni cavab alır. Praktikada hash-li fayllara bir illik max-age və immutable verirəm, HTML-i no-cache və ETag ilə göndərirəm, şəxsi olan hər şeyi isə private və ya no-store ilə işarələyirəm."
Gözlənilən suallar
no-cacheiləno-store-un fərqi?no-cachesaxlayır və hər təkrar istifadədən əvvəl yoxlayır,no-storeheç vaxt saxlamır.no-store-un bir çox brauzerdə bfcache-i də söndürdüyünü qeyd et.- Deploy-dan sonra istifadəçilər yenə köhnə versiyanı görür — niyə? HTML-də və ya versiyasız faylda uzun müddət,
Cache-Control-suz cavabda evristik təzəlik və ya öz keşindən cavab verən service worker. Onları DevTools-da necə ayırd edəcəyini izah et (Size sütununda "(disk cache)" ilə200,304və ya "(ServiceWorker)"). - Statik faylları necə keşləyirsən? Fayl adlarında məzmun hash-i,
max-age=31536000, immutable, HTML-in revalidasiyası; faylları HTML-dən əvvəl deploy et və köhnələri saxla. - CDN nə əlavə edir? Paylaşılan keş,
s-maxage,Age, purge API-ləri, origin-i qorumaq üçünstale-while-revalidatevəstale-if-error. - Keşləmə məlumat sızmasına necə səbəb ola bilər? Şəxsi cavabı paylaşılan keş saxlayanda:
privateunudulub, autentifikasiyalı cavablardapublicvə yas-maxagevar, ya da açar cavabın asılı olduğu cookie-ni nəzərə almır.
Bal itirdən səhvlər
no-cache-in "keşlənmir" demək olduğunu söyləmək.max-ageolduğu haldaExpires-ın hələ də rol oynadığını düşünmək.304-ü "sorğusuz keşdən verildi" kimi qəbul etmək — bu, sorğudur, sadəcə gövdə ötürülmür.- Səhv məlumat bug-ını keşi silməklə "düzəltmək". Senior cavab keşi saxlayıb açarı və ya müddəti düzəltməkdir.
- bfcache-i, HTTP keşini və Cache API-ni ayırmadan hamısını "brauzer keşi" adlandırmaq.
Senior səviyyəni göstərən məqamlar
Yalnız başlıqlardan yox, açardan və təmizləmədən danış: cavab nədən asılıdır, onu kim paylaşa bilər, səhv cavab nə qədər yaşaya bilər və onu necə siləcəksən (versiyalı URL-lər, teq üzrə purge, qısa brauzer müddətləri). Keşləmənin sadəcə effektiv yox, həm də düzgün olduğunu göstərən metriki qeyd et: hit ratio və origin yükünün yanında düzgünlük yoxlaması, məsələn, keşdəki cavablardan nümunələrin origin-lə müqayisəsi.
A 30-second answer. "A cache reuses a stored response while it is fresh, as long as Cache-Control allows it. When it goes stale, the cache sends a conditional request with If-None-Match or If-Modified-Since and gets either a 304 or a new response. In practice I give hashed assets a one-year max-age with immutable, send HTML with no-cache and an ETag, and mark anything personal private or no-store."
Questions you are likely to get
no-cachevsno-store?no-cachestores and validates before every reuse;no-storenever stores. Mention thatno-storealso costs the bfcache in many browsers.- Users still see the old version after a deploy — why? A long lifetime on HTML or on an unversioned file, heuristic freshness on a response without
Cache-Control, or a service worker serving its own cache. Explain how you would tell them apart in DevTools (a200from "(disk cache)", a304, or "(ServiceWorker)" in the Size column). - How do you cache static assets? Content hashes in file names,
max-age=31536000, immutable, HTML revalidated; deploy assets before HTML and keep old ones. - What does a CDN add? Shared cache,
s-maxage,Age, purge APIs,stale-while-revalidateandstale-if-errorto protect the origin. - How can caching leak data? A personalised response cached by a shared cache: missing
private,publicors-maxageon authenticated responses, or a key that ignores a cookie the response depends on.
Mistakes that cost points
- Saying
no-cachemeans "not cached". - Thinking
Expiresstill matters whenmax-ageis present. - Treating a
304as "served from cache without a request" — it is a request, only the body is skipped. - Fixing a wrong-data bug by removing the cache. The senior answer is to fix the key or the lifetime and keep the cache.
- Calling the bfcache, the HTTP cache and the Cache API "the browser cache" without distinguishing them.
Senior signal
Talk about the key and invalidation, not only headers: what the response depends on, who may share it, how long a wrong answer may live, and how you will remove it (versioned URLs, purge by tag, short browser lifetimes). Mention the metric that tells you caching is correct, not just effective: hit ratio and origin load next to a correctness check, for example sampling cached responses against the origin.
HTTP keşləmə başlıqlarını review edərkən nəyi yoxlamalı
Bu siyahını özün yazmadığın keşləmə başlıqlarında və ya keş kodunda işlət: komanda yoldaşının pull request-i, kitabxananın konfiqurasiyası və ya AI assistentinin təklifi. Səhv başlıq bütün testlərdən keçir, sonra istifadəçilərə günlərlə köhnə versiyanı, ya da bir istifadəçinin məlumatını başqasına göstərir. Brauzerlərdə saxlanmış nüsxələri isə geri çağırmaq olmur.
- Şəxsi cavablar
privatevə yano-storeilə işarələnibmi, autentifikasiyalı cavablardapublicvə yas-maxageyoxdurmu? Bu ikisi CDN-əAuthorization-lı sorğuların cavablarını təkrar verməyə icazə verir, sessiya cookie-si isə paylaşılan keşin onları saxlamasına mane olmur. Başlıqlara DevTools-un Network panelində bax. - HTML uzun
max-ageilə yox,no-cachevəETagilə gedirmi (şəxsidirsə, üstəlikprivate)? Cari hash-li faylların adları ondadır, ona görə bir günlük təzəlik deploy-dan sonra bir gün köhnə tətbiq deməkdir. - Hər cavab
Cache-Control-u açıq göndərirmi? O olmasa, keş müddətiLast-Modified-ə görə özü təxmin edə və dünənki versiyanı verməyə davam edə bilər. max-age=31536000vəimmutableyalnız məzmun hash-i olan URL-lərdədirmi?/logo.svgkimi versiyasız URL-də yeni versiya istifadəçilərə bir il ərzində çatmır.- Cavabın asılı olduğu hər şey keş açarına daxildirmi? Açar praktikada URL-dir: cookie-dən oxunan dil orada yoxdur, ona görə ilk saxlanan cavab hamı üçün qalib gəlir. Dəyəri URL-ə və ya CDN-in açarına qoy;
Vary: Cookiehər ziyarətçiyə ayrıca qeyd deməkdir. - Hər direktiv müəllifin düşündüyü mənanı verirmi?
no-cachesaxlayır, amma hər təkrar istifadədən əvvəl yoxlayır;no-storeheç vaxt saxlamır və bir çox brauzerdə back/forward cache-i də söndürür. Network panelinin Size sütunundakı "(disk cache)" heç bir sorğu getmədiyini göstərir,304isə real sorğudur.
Use this list on caching headers or cache code you did not write: a teammate's pull request, a library's config or an AI assistant's suggestion. A wrong header passes every test, then shows users an old version for days or one user's data to another, and copies stored in browsers cannot be recalled.
- Are personalised responses marked
privateorno-store, with nopublicors-maxageon authenticated ones? Those two let a CDN reuse responses to requests withAuthorization, and a session cookie does not stop a shared cache from storing them. Check the headers in the DevTools Network panel. - Is the HTML sent with
no-cacheand anETag(plusprivateif personalised), not a longmax-age? It names the current hashed files, so a day of freshness means a day of the old app after a deploy. - Does every response set
Cache-Controlexplicitly? Without it a cache may guess a lifetime fromLast-Modifiedand keep serving yesterday's version. - Are
max-age=31536000andimmutableonly on URLs with a content hash? On an unversioned/logo.svg, a new version cannot reach users for a year. - Is everything the response depends on part of the cache key? In practice the key is the URL: a language read from a cookie is not in it, so the first stored response wins for everyone. Put the value in the URL or the CDN key;
Vary: Cookiemeans one entry per visitor. - Does each directive mean what the author thinks?
no-cachestores but validates before every reuse;no-storenever stores and in many browsers costs the back/forward cache. In the Network panel's Size column, "(disk cache)" means no request went out; a304was a real request.
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.