first // what is a cache?najpierw // czym jest pamięć podręczna (cache)?
Keep the answer, don't ask againZachowaj odpowiedź, nie pytaj ponownie
Visitoropens a pageOdwiedzającyotwiera stronę
askspyta
Cachekeeps ready answersCachema gotowe odpowiedzi
only if there is nonetylko gdy nie ma
Databasethe source, but slowBaza danychźródło, ale powolne
A page asks the database 10 to 30 questions, and most of them have the same answer for every visitor.Strona zadaje bazie danych od 10 do 30 pytań, a większość z nich ma taką samą odpowiedź dla każdego odwiedzającego.
cachea place that keeps the answer to an expensive question, so the next visitor gets it at once.miejsce, gdzie czeka odpowiedź na kosztowne pytanie, żeby kolejny odwiedzający dostał ją od ręki.
the promise // of this talkobietnica // tego wystąpienia
Remembering is easy. Forgetting at the right moment is the hard part.Zapamiętywanie jest łatwe. Trudne jest zapominanie w odpowiednim momencie.
Forget too late: visitors see what is no longer true.Za późno: odwiedzający widzą nieaktualne treści.
Forget a lot, or everything, at once: the cache is busy throwing cached pages away, and whoever asks it meanwhile waits in line.Za dużo naraz: cache jest zajęty usuwaniem, a każdy, kto w tym czasie pyta, czeka w kolejce.
Forget at a busy moment: every visitor finds the cached page gone and runs to the database for it, all at the same moment.W szczycie ruchu: strony nie ma w cache, więc wszyscy naraz biegną po nią do bazy.
the road // the map of this talkdroga // mapa tej prezentacji
Fifteen stops, one problemPiętnaście przystanków, jeden problem
At every stop you will see it break, and then see it fixed.Na każdym przystanku coś się psuje, a potem to naprawiamy.
stop 1 // of 15przystanek 1 // z 15
NoBezcache
Every page is built from scratch, for every visitor.Każda strona jest tworzona od podstaw, dla każdego odwiedzającego.
the problem // no cacheproblem // brak cache
The database answers everyoneBaza odpowiada wszystkim
Every page asks the database 10 to 30 questions.Każda strona kieruje do bazy danych od 10 do 30 zapytań.
The database works on a few questions at a time; the others wait in line.Baza obsługuje naraz tylko kilka zapytań, reszta czeka w kolejce.
A busy evening or a sale: the line grows, every page gets slower, then pages fail.Wieczorny szczyt albo promocja: kolejka rośnie, strony zwalniają, aż w końcu padają.
More visitors, longer waitsWięcej odwiedzających, dłuższe oczekiwanie
no cache · then filesbrak cache · potem pliki
the fix // stop 2: a file cacherozwiązanie // przystanek 2: cache plikowy
Keep the answer in a fileZapisz odpowiedź w pliku
// ask the database once, keep the answer for 5 minutes
return $store->get('front-page', fn() => $db->frontPage(), ttl: 300);
The first visitor waits for the database. The next ones get the file.Pierwszy odwiedzający czeka na bazę. Następni dostają plik.
After 5 minutes the file is thrown away, and the next visitor asks again.Po 5 minutach plik jest kasowany i następny odwiedzający znów pyta bazę.
ttl"time to live": how long a saved answer may be used before it is thrown away.„time to live”: jak długo zapisana odpowiedź może być używana, zanim zostanie usunięta.
the problem // 5 minutes is a long timeproblem // 5 minut to długo
The editor fixes a typo, but it's still visible.Redaktor poprawia literówkę, lecz nadal ją widać.
12:00The front page is saved for 5 minutes.Strona główna jest przechowywana przez 5 minut.
12:01The editor fixes a typo in the headline.Redaktor poprawia literówkę w tytule.
12:01–12:05All visitors still see the page with a typo.Wszyscy odwiedzający nadal widzą stronę z literówką.
12:05The application's cached page expires; the fix shows…Strona w cache aplikacji wygasa, poprawka się pojawia…
12:05–12:10…unless a second cache sits in front of the site: it can keep the old page up to 5 minutes more. The waits add up.…chyba że przed serwisem stoi drugi cache: może trzymać starą stronę jeszcze do 5 minut. Opóźnienia się sumują.
front cachecache przed serwisema cache in front of the whole site that keeps whole pages: Varnish, or a CDN such as Cloudflare (the site, kept on servers around the world).cache na całe strony, stojący przed całym serwisem: Varnish albo CDN, np. Cloudflare (kopie serwisu na serwerach po całym świecie).
the fix // stop 3: tagsrozwiązanie // przystanek 3: tagi
Tag every cached page, forget by tagTaguj każdą stronę, zapominaj po tagu
DisplayWyświetlanie
// showing the front page
return $store->get(
'front-page',
fn() => $db->frontPage(),
ttl: 3600,
tags: ['article-42', 'category-7'],
);
EditEdycja
// the editor saves article 42
$db->saveArticle(42, $text);
// every cached page tagged with it is forgotten
$store->invalidateTags(['article-42']);
taga name on a cached page, saying what it contains. To invalidate a tag is to throw away every cached page that carries it.etykieta na stronie w cache, która mówi, co zawiera. Unieważnić tag to skasować wszystkie strony nim oznaczone.
A tag, and every cached page with itTag i wszystkie jego strony
the file cache: cached pages and tagscache plikowy: strony w cache i tagi
stop 4 // of 15przystanek 4 // z 15
When filesGdy plikistart to hurtzaczynają boleć
Two problems arrive together:Dwa problemy naraz:
Forgetting gets slow: one tag can sit on thousands of cached pages, and every cached page is a file to delete, one by one.Zapominanie zwalnia: jeden tag może mieć tysiące stron w cache, a każdą trzeba skasować osobno, plik po pliku.
One server is not enough: more visitors than it can handle, so the site runs on several, and each keeps its own files.Jeden serwer nie wystarcza: ruchu jest więcej, niż jest w stanie obsłużyć, więc serwis stoi na kilku, a każdy ma własne pliki.
the problem // one delete per cached pageproblem // kasowanie strona po stronie
Forgetting a tag touches every cached page that was tagged with itZapomnienie tagu dotyka każdej zapisanej strony, która była nim oznaczona
Category 7 appears on 20 000 pages: its tag is on 20 000 cached pages.Kategoria 7 jest na 20 000 stron, więc jej tag ma 20 000 stron w cache.
The editor changes category 7: its tag is forgotten, and 20 000 files must be found and deleted.Redaktor zmienia kategorię 7: zapominamy jej tag, czyli trzeba znaleźć i skasować 20 000 plików.
Twice the pages, twice the time. The cost grows with every cached page.Dwa razy więcej stron, dwa razy więcej czasu. Każda strona w cache dokłada swoje.
And on every server: with several servers, each has its own 20 000 files to delete.I na każdym serwerze: przy kilku serwerach każdy kasuje własne 20 000 plików.
One file per page, deleted one by oneKażda strona to plik, kasowany osobno
file cache · one tagcache plikowy · jeden tag
the problem // more than one serverproblem // więcej niż jeden serwer
Two servers, two memoriesDwa serwery, dwie pamięci
VisitorsOdwiedzający
spread byprzez
Load balancertakes turnsLoad balancerna zmianę
todo
Server Aits own files · the edit landed hereSerwer Awłasne pliki · tu trafiła zmiana
Server Bits own files · never heard of itSerwer Bwłasne pliki · nic o niej nie wie
Server A forgets its cached pages with article 42.Serwer A czyści u siebie strony z artykułem 42.
Server B keeps serving its old cached page: every second visitor sees the old article.Serwer B dalej serwuje starą wersję z cache: co drugi odwiedzający widzi stary artykuł.
load balancerspreads the visitors over several identical servers, so more of them can be served at once.rozkłada ruch na kilka identycznych serwerów, żeby obsłużyć więcej osób naraz.
The edit reaches one serverZmiana trafia na jeden serwer
two servers · each with its own filesdwa serwery · każdy z własnymi plikami
stop 5 // of 15przystanek 5 // z 15
OneJedenshared cache serverwspólny serwer cache
Files forget slowly, and every server keeps its own.The fix for both: one shared place, an in-memory store like Redis, Valkey or ElastiCache.Pliki zapominają powoli, a każdy serwer ma własne.Oba problemy załatwia jeden wspólny cache w pamięci, jak Redis, Valkey czy ElastiCache.
One cached page for all servers: an edit is forgotten everywhere at once.Jedna kopia dla wszystkich serwerów: po edycji znika wszędzie naraz.
Memory instead of files: no disk to touch, and one delete serves every server.Pamięć zamiast plików: bez dysku, a jedno usunięcie wystarcza wszystkim serwerom.
first // what is Redis?najpierw // czym jest Redis?
One shared memory, very fastWspólna pamięć, błyskawiczna
A server that keeps data in memory and answers in a fraction of a millisecond.Serwer, który trzyma dane w pamięci i odpowiada w ułamku milisekundy.
Every web server talks to the same one.Każdy serwer WWW rozmawia z tym samym Redisem.
It does one thing at a time, very quickly. Remember this.Robi jedną rzecz naraz, bardzo szybko. Zapamiętajcie to.
redisan in-memory data server. Picture a shop with one very fast checkout: one customer at a time.serwer danych w pamięci. Wyobraźcie sobie sklep z jedną bardzo szybką kasą: klienci po kolei.
valkeyRedis's open-source fork, started in 2024 when Redis changed its license. It works the same way.open-source'owy fork Redisa, powstały w 2024, kiedy Redis zmienił licencję. Działa tak samo.
elasticachea managed service from AWS: it runs Redis (up to 7.1) or Valkey (up to 9.1) for you.zarządzana usługa AWS: uruchamia za was Redisa (do 7.1) albo Valkey (do 9.1).
The same edit, every server sees itTa sama zmiana, a widzi ją każdy serwer
two servers · one Redisdwa serwery · jeden Redis
the problem // memory runs outproblem // kończy się pamięć
Memory is not endlessPamięć nie jest z gumy
Every cached page takes memory, and more keep coming.Każda strona w cache zajmuje pamięć, a ciągle dochodzą nowe.
Without a limit, Redis grows until the server runs out of memory, and the operating system kills it.Bez limitu Redis rośnie, aż serwerowi zabraknie pamięci i system operacyjny go ubije.
Then the whole cache is gone at once, and every visitor rebuilds at the same moment.Wtedy cały cache znika naraz, a wszyscy jednocześnie generują strony od nowa.
the fix // a limit and a policyrozwiązanie // limit i polityka
A limit, and a rule for what to forgetLimit i zasada, co zapomnieć
# redis.conf
maxmemory 4gb
# when full: forget the least recently used cached page that has an expiry
maxmemory-policy volatile-lru
When memory is full, Redis forgets the cached pages nobody asked for lately, by itself.Gdy pamięć się zapełni, Redis sam wyrzuca strony, o które nikt ostatnio nie pytał.
volatile-lru: only cached pages with an expiry may go, the least recently used first; what has none stays.volatile-lru: wylatują tylko strony z TTL, najpierw najdłużej nieużywane; te bez TTL zostają.
eviction policypolityka usuwaniathe rule Redis follows to choose which cached pages to throw away when memory is full.zasada, według której Redis wybiera, co wyrzucić, gdy zabraknie pamięci.
the policy's name // lrunazwa polityki // lru
Which cached page goes first?Która strona znika pierwsza?
volatile-lru has two halves: lru picks which cached page goes first, volatile which may go at all: only cached pages with an expiry.volatile-lru to dwie połówki: lru decyduje, która strona znika pierwsza, a volatile, które w ogóle mogą zniknąć: tylko te z TTL.
lruleast recently used: the cached page nobody has asked for the longest. Ours: popular cached pages stay, because they keep being served.least recently used: strona, o którą najdłużej nikt nie pytał. Nasz wybór: popularne strony zostają, bo ciągle ktoś je czyta.
lfuleast frequently used: the cached page asked for the fewest times.least frequently used: strona, o którą pytano najrzadziej.
ttlthe cached page closest to expiring anyway.strona, która i tak wygaśnie najwcześniej.
randomany cached page.dowolna strona.
the first half of the name // volatilepierwsza połowa nazwy // volatile
Forget cached pages, never the listsZapominaj strony, listy tagów nigdy
Tag listsno expiry without them, an edit reaches no cached pageListy tagównie wygasają bez nich edycja nie dotrze do żadnej strony
point towskazują na
Cached pagesalways an expiry, at most 30 days can be built againStrony w cachezawsze z TTL, najwyżej 30 dni można je wygenerować od nowa
allkeys-lru
Anything may go, a tag's list too.Może zniknąć wszystko, także lista tagu.
Forgetting that tag then finds nothing: the old cached pages stay.Zapomnienie tagu nic wtedy nie znajdzie: stare strony zostają w cache.
volatile-lru
Only what has an expiry may go: the cached pages.Zniknąć może tylko to, co ma TTL: strony w cache.
A forgotten cached page is only a miss: it is built again.Zapomniana strona to tylko miss: wygenerujemy ją od nowa.
So every cached page needs an expiry: the versioned store caps it at 30 days, even for one saved "forever".Dlatego każda strona musi mieć TTL: wersjonowany store daje najwyżej 30 dni, nawet gdy ktoś zapisuje „na zawsze”.
stop 6 // of 15przystanek 6 // z 15
SmallerMniejszecached pagesstrony w cache
Memory is not endless.The fix: compress every cached page.Pamięć nie jest z gumy.Rozwiązanie: kompresja każdej strony.
Half the memory or less: twice as many cached pages fit, or more.Najwyżej połowa pamięci: zmieści się co najmniej dwa razy więcej stron.
zstd instead of gzip: the same size, decompressed faster on every read.zstd zamiast gzip: ten sam rozmiar, szybsza dekompresja przy każdym odczycie.
ANSa way of packing data, used inside zstd: as tight as the slow methods, nearly as fast as the quick ones. By Jarosław Duda, Jagiellonian University in Kraków, and free for everyone.metoda kompresji używana w zstd: ściska jak wolne metody, a działa niemal tak szybko jak te szybkie. Wymyślił ją Jarosław Duda z Uniwersytetu Jagiellońskiego w Krakowie i oddał wszystkim za darmo.
zstd: the same size, less waitingzstd: ten sam rozmiar, mniej czekania
Compressed pages and models take half the memory or less, but every read has to decompress them first.Skompresowane strony i modele zajmują najwyżej połowę pamięci, ale przy każdym odczycie trzeba je rozpakować.
a cached value of…wartość w cache…
codeckodek
size afterrozmiar po
compress, mskompresja, ms
decompress, msdekompresja, ms
~300 B recordsrekordy ~300 B
deflate
66 %66 %
0.0110,011
0.0030,003
zstd
72 %72 %
0.0070,007
0.0030,003
~2.6 KB modelsmodele ~2,6 KB
deflate
48 %48 %
0.0560,056
0.0140,014
zstd
51 %51 %
0.0240,024
0.0060,006
335 KB web pagestrona 335 KB
deflate
18.5 %18,5 %
6.4256,425
0.4830,483
zstd
19.0 %19,0 %
1.0571,057
0.2010,201
Decompressing: over 2× faster on models and pages, and every read decompresses. Compressing: up to 6× faster, once per save.Dekompresja: ponad 2× szybsza dla modeli i stron, a rozpakowuje się przy każdym odczycie. Kompresja: do 6× szybsza, raz przy zapisie.
A mark at the start: 4 bytes tell a compressed page from a plain one. Symfony's current compression has none, so it tries to decompress every value.Sygnatura na początku: 4 bajty odróżniają skompresowaną stronę od zwykłej. Obecna kompresja w Symfony jej nie ma, więc próbuje rozpakować każdą wartość.
deflatethe compression inside gzip and zip: gzip is deflate plus a small header. Symfony's cache uses it today.kompresja, której używają gzip i zip: gzip to deflate z małym nagłówkiem. Korzysta z niej dziś cache Symfony.
stop 7 // of 15przystanek 7 // z 15
TagListyliststagów
Every tag keeps a list of its cached pages. Forgetting a tag means deleting every one of them.Każdy tag ma listę swoich stron. Zapomnieć tag to znaczy skasować każdą z nich.
how it works // the classic designjak to działa // klasyczny backend
A list for every tagLista dla każdego tagu
cache:
persistent:
! store: \Talk\Store\RedisClassic # the design Magento made famous
Every saved page: one entry in Redis.Każda zapisana strona: wpis w Redisie.
Every tag: a list of the pages that carry it.Każdy tag: lista stron z tym tagiem.
Forgetting a tag: read its list, delete every page on it.Zapomnienie tagu: odczytaj listę, skasuj jej strony.
the problem // one at a timeproblem // po kolei
Forgetting a million cached pages makes visitors waitZapominamy milion stron, a odwiedzający czekają
Forgetting a tag deletes every cached page on the list, in one go.Zapomnienie tagu usuwa naraz każdą stronę z listy.
Redis does one thing at a time: while it deletes, visitors wait. Their pages come only once it has finished deleting.Redis robi jedną rzecz naraz: kiedy kasuje, odwiedzający czekają. Strony dostaną dopiero, gdy skończy.
Every page waits, not only the edited one.Czeka każda strona, nie tylko ta edytowana.
Often one Redis serves several websites: their visitors wait too.Często jeden Redis służy kilku serwisom: ich odwiedzający też czekają.
When a cached page expires, its name stays on the tag lists until a garbage collector walks them: a million expired pages left their names in the tag lists, 28 MB.Strona wygasa, a jej nazwa zostaje na listach tagów, dopóki nie przejdzie po nich garbage collector: po milionie wygasłych stron zostało tam 28 MB nazw.
Everyone else, waitingCała reszta czeka
forgetting tags on many cached pages · 24 visitors read cached pages meanwhilezapominanie tagów na wielu stronach · w tym czasie 24 odwiedzających czyta strony z cache
the fix // smaller bitesrozwiązanie // mniejsze kawałki
Forget in small batchesZapominaj na raty
At most 1 000 cached pages per call; other visitors are served between calls.Najwyżej 1 000 stron na wywołanie, w przerwach Redis obsługuje innych.
The lists clean themselves: each entry expires together with its cached page (HEXPIRE).Listy sprzątają się same: wpis wygasa razem ze stroną (HEXPIRE).
The steps run inside Redis, as small programs loaded once.Kroki wykonuje sam Redis: to małe programy ładowane raz.
redis functionfunkcja redisaa small program stored in Redis and run there, next to the data, in one go.mały program, który Redis trzyma i wykonuje przy danych, za jednym razem.
hexpirenew in Redis 7.4: one field of a hash expires on its own. A tag's list is a hash, a field per page.nowość w Redisie 7.4: pojedyncze pole hasha wygasa samo. Lista tagu to hash, pole na stronę.
how it works // smaller bitesjak to działa // mniejsze kawałki
One bite per callJeden kęs na wywołanie
Inside Redis (Lua)W Redisie (Lua)
local function cache_unlink_by_tag(keys, args)
local list, cursor = args[1], args[2]
local bite = redis.call('HSCAN', list, cursor,
'COUNT', 1000, 'NOVALUES')
-- bite[1]: the next cursor; bite[2]: up to 1 000 keys
for _, id in ipairs(bite[2]) do
redis.call('UNLINK', id) -- the page goes
end
if #bite[2] > 0 then -- #: how many keys
-- off the tag's list; unpack: keys as arguments
redis.call('HDEL', list, unpack(bite[2]))
end
return bite[1] -- the next bite, '0': done
end
Store\Redis (PHP)
foreach($tags as $tag)
{
$cursor = '0';
do
{
$cursor = $redis->fcall(
'cache_unlink_by_tag',
[], [$tag, $cursor],
);
// Redis serves others here
}
while($cursor !== '0');
}
cursorkursora bookmark in the list: Redis returns it with every bite, PHP sends it back for the next ("0": start, and done).zakładka na liście: Redis zwraca ją z każdą porcją, PHP odsyła ją po następną („0”: start i koniec).
The same work, nobody waitsTa sama praca, nikt nie czeka
forgetting tags on many cached pages · in one go, then in batcheszapominanie tagów na wielu stronach · naraz, potem porcjami
stop 8 // of 15przystanek 8 // z 15
Round tripsDo Redisato Redisi z powrotem
Every step is a trip to Redis and back, and the data rides along both ways.Każdy krok to osobny kurs do Redisa i z powrotem, a dane płyną w obie strony.
the problem // one step, one tripproblem // jeden krok, jeden kurs
The data rides both waysDane płyną tam i z powrotem
Forgetting a tag from PHP: the whole list of names comes to PHP, then goes back to Redis in the delete commands.Zapominanie tagu z PHP: cała lista nazw leci do PHP, a potem wraca do Redisa w poleceniach usunięcia.
Every step is a question and an answer over the network: fast, but never free, and it adds up.Każdy krok to pytanie i odpowiedź przez sieć: szybko, ale nigdy za darmo, i to się sumuje.
Between two trips, another server can change the list: a cached page saved in that moment is missed, and stays old.Między dwoma krokami inny serwer może zmienić listę: strona zapisana akurat wtedy umyka i zostaje nieaktualna.
round tripa question sent over the network to Redis, and its answer coming back.pytanie do Redisa przez sieć i odpowiedź z powrotem.
the fix // a Lua library inside Redisrozwiązanie // biblioteka Lua w Redisie
Send the job, not the stepsWyślij zadanie, nie kroki
# once, when the application starts: a whole library (Cache.lua) is stored in Redis
FUNCTION LOAD REPLACE "#!lua name=cache ..."
# then every time: the names in, a short answer out; the work happens inside
FCALL cache_set 1 front-page "<the page>" 3600 "article-42,category-7"
FCALL cache_unlink_by_tag 0 article-42 0 # the next bite's cursor comes back
One call per job: PHP sends the names, the work runs next to the data.Jedno wywołanie na zadanie: PHP wysyła nazwy, praca odbywa się przy danych.
Nobody gets in between: a call runs to its end before Redis serves anyone else.Nikt się nie wciśnie pomiędzy: Redis kończy wywołanie, zanim obsłuży kogoś innego.
luaa small programming language built into Redis: a library of functions is written in it and stored there.mały język programowania wbudowany w Redisa: pisze się w nim bibliotekę funkcji, którą Redis przechowuje.
how it works // php-library's Functionsjak to działa // Functions z php-library
A whole library, loaded onceCała biblioteka, ładowana raz
#!lua name=cache -- added by php-library: one file, one library
local function cache_set(keys, args) ... end
local function cache_unlink_by_tag(keys, args) ... end -- ... Cache.lua has 16
redis.register_function('cache_set', cache_set)
redis.register_function('cache_unlink_by_tag', cache_unlink_by_tag)
redis.register_function('cache_src_9f2c41d0', function() return 1 end) -- which version
Once per server: FUNCTION LIST LIBRARYNAME says whether the library is there, the last function whether it is this version; an edited file replaces it.Raz na serwer: FUNCTION LIST LIBRARYNAME mówi, czy biblioteka już tam jest, ostatnia funkcja – czy to ta wersja; zmieniony plik ją podmienia.
A minute without asking: once one process has seen the library there, every process on the host skips the check for 60 s (APCu).Minuta bez pytania: gdy jeden proces zobaczy bibliotekę na serwerze, pozostałe procesy na hoście przez 60 s pomijają sprawdzanie (APCu).
Never missing: Redis only answers "Function not found"; php-library then loads the library again and repeats the call, once.Zawsze na miejscu: Redis tylko odpowiada „Function not found”; php-library ładuje wtedy bibliotekę od nowa i raz ponawia wywołanie.
measured // what travels between PHP and Rediszmierzone // co leci między PHP a Redisem
The same job, a fraction of the trafficTo samo zadanie, ułamek ruchu
the jobzadanie
howjak
commandspolecenia
bytes to Redisbajty do Redisa
bytes backbajty z Redisa
save a page, 5 tagszapis strony, 5 tagów
stepskroki
9
804
45
functionfunkcja
1
493
4
forget a tag, 100 000 cached pageszapomnienie tagu, 100 000 stron
stepskroki
12
2 489 149
1 678 983
functionsfunkcje
101
15 787
2 216
Forgetting a tag: 4.2 MB become 18 KB. The list never leaves Redis. 101 small calls, on purpose: between two of them everyone else is served.Zapomnienie tagu: 18 KB zamiast 4,2 MB. Lista nie wychodzi z Redisa. 101 małych wywołań, celowo: między nimi obsługiwani są wszyscy inni.
Releasing a lock: one call instead of three, so no other server can take the lock between the check and the delete.Zwolnienie blokady: jedno wywołanie zamiast trzech, więc żaden inny serwer nie przejmie blokady między sprawdzeniem a usunięciem.
what remains // after the batchesco zostaje // po porcjach
Nobody waits, but the work remainsNikt nie czeka, ale praca zostaje
A million cached pages are still a million deletes: seconds of work for Redis, now spread out.Milion stron to wciąż milion usunięć: sekundy pracy Redisa, tyle że rozłożone w czasie.
Every deleted cached page has to be built again, by the next visitor who asks for it.Każdą skasowaną stronę ktoś musi wygenerować od nowa: pierwszy, kto o nią poprosi.
And if many visitors ask for the same cached page at once, they all build it at the same time.A jeśli o tę samą stronę poprosi naraz wielu odwiedzających, wszyscy generują ją równocześnie.
stop 9 // of 15przystanek 9 // z 15
TheCachestampede
The cached report is gone, and everyone runs to the database at once.Raport wypadł z cache i wszyscy naraz rzucają się na bazę.
the problem // everyone at onceproblem // wszyscy naraz
The cached report is gone. Everyone rebuilds it.Raport wypadł z cache. Każdy generuje go od nowa.
The monthly report takes the database 300 ms to build.Raport miesięczny to 300 ms pracy bazy danych.
An editor publishes: the saved report is forgotten.Redaktor publikuje: raport z cache idzie w niepamięć.
24 visitors ask for it in those 300 ms: 24 identical queries.W tych 300 ms proszą o niego 24 osoby: 24 identyczne zapytania.
A lock would help: one builds, the others wait. If every server can see it.Pomogłaby blokada: jeden generuje, reszta czeka. O ile widzi ją każdy serwer.
stampedemany requests rebuilding the same missing cached page at the same moment.wiele żądań naraz generuje od nowa tę samą brakującą stronę.
24 requests, one missing report24 żądania, jeden brakujący raport
the database takes 300 ms · slow motionbaza: 300 ms · zwolnione tempo
the fix // memolockrozwiązanie // memolock
One lock for every serverJedna blokada na wszystkie serwery
// once, on any pool; get() unchanged
$pool->setCallbackWrapper(
MemoLock::fromDsn('redis://redis'));
lockblokadaa sign that says "someone is already doing this": the others wait instead of doing it too.znak „ktoś już to robi”: reszta czeka, zamiast robić to samo.
the fix // woken by a signalrozwiązanie // obudzeni sygnałem
Woken by a message, not a timerBudzi ich wiadomość, nie zegar
-- MemoLock.lua: the release, one call
if redis.call('GET', lock_key) == lock_value then
redis.call('PUBLISH', channel, '1') -- the others wake now
return redis.call('DEL', lock_key)
end
return 0
Symfony's LockRegistry checks every 100 ms: a waiting request answers up to 100 ms after the report is ready. A message wakes it at once.LockRegistry w Symfony sprawdza co 100 ms: czekające żądanie dostaje raport nawet 100 ms po czasie. Wiadomość budzi je od razu.
Only the request that took the lock can release it: it writes its own token into the lock, and the release checks that the token matches.Blokadę zwolni tylko żądanie, które ją założyło: zapisuje w niej swój token, a zwolnienie sprawdza, czy token się zgadza.
Waiting needs its own connection: on a shared one replies reach the wrong command, so a cache read gets a Pub/Sub message and the waiter gets a cached value.Czekanie wymaga osobnego połączenia: na wspólnym odpowiedzi się rozjeżdżają, więc odczyt z cache dostaje wiadomość z Pub/Sub, a czekający – wartość z cache.
The same 24 requests, MemoLockTe same 24 żądania, MemoLock
the database takes 300 ms · slow motionbaza: 300 ms · zwolnione tempo
how it works // memolockjak to działa // memolock
One builds, the others are wokenJeden generuje, reszta się budzi
pub/subpublish and subscribe: clients wait on a channel, and one message to it wakes every one of them at once.publish/subscribe: klienci czekają na kanale, a jedna wiadomość budzi ich wszystkich naraz.
memolock // not only cached pagesmemolock // nie tylko cache
The same lock for a thumbnailTa sama blokada dla miniatury
php-library
// a new photo, 50 visitors open the gallery at once
$memoLock->lockAndQueue('thumbnails:' . $file,
// after waiting: is the thumbnail there now?
fetcher: fn() => file_exists($thumbnail) ? true : null,
// only the request that has the lock makes it
resolver: fn() => $this->generateThumbnail($file));
$memoLock->releaseActiveLock('thumbnails:' . $file);
Symfony: artigo/cache-stampede
// the same; the lock is released for you
$lock->once('thumbnails:' . $file,
exists: fn() => is_file($thumbnail) ? $thumbnail : null,
make: fn() => $this->generateThumbnail($file));
One request resizes the photo; the other 49 wait for the message, then find the file.Jedno żądanie skaluje zdjęcie, pozostałe 49 czeka na wiadomość i zastaje gotowy plik.
Anything expensive and the same for everyone: a thumbnail, a PDF, a token from an API, an import.Wszystko, co kosztowne i dla każdego takie samo: miniatura, PDF, token z API, import.
thumbnailminiaturaa small preview image, made from the full photo.mały podgląd zrobiony z pełnego zdjęcia.
memolock // any codememolock // dowolny kod
The same lock, around any codeTa sama blokada dla dowolnego kodu
php-library
// the import: on every server, one at a time
$cache->lockAndQueue('import:companies');
try { $this->importCompanies(); }
finally { $cache->releaseActiveLock('import:companies'); }
Symfony: artigo/cache-stampede
// the same, released even when it throws
$lock->exclusively('import:companies',
fn() => $this->importCompanies());
Nothing cached, just the lock: the import runs on one server at a time.Nic w cache, sama blokada: import działa w danej chwili tylko na jednym serwerze.
A server dies mid-import? The lock expires on its own after lock_ttl_ms.Serwer padł w trakcie importu? Blokada sama wygaśnie po lock_ttl_ms.
Or tryLock(): if the import is already running elsewhere, skip it instead of waiting.Albo tryLock(): jeśli import już gdzieś trwa, pomiń go zamiast czekać.
critical sectionsekcja krytycznaa piece of code that only one process may run at a time.fragment kodu, który w danej chwili może wykonywać tylko jeden proces.
memolock // in shortmemolock // w skrócie
One rebuild, every server, no timerJeden generuje, wszędzie, bez zegara
What it givesCo daje
One request rebuilds; the others, on every server, wait for it.Jedno żądanie generuje, reszta na każdym serwerze czeka.
The others are woken by a message: +3 ms, not +100.Resztę budzi wiadomość: +3 ms, nie +100.
Only the request that has the lock can release it. If that request crashes, the lock expires after lock_ttl_ms (5 s here) and another request takes over.Blokadę zwalnia tylko żądanie, które ją ma. Gdy padnie, blokada wygasa po lock_ttl_ms (tu 5 s) i przejmuje ją inne żądanie.
A cached page that is there costs nothing: the lock is only taken on a miss.Cache hit nic nie kosztuje: blokadę zakładamy tylko przy cache miss.
Where to get itSkąd go wziąć
php-library, the first PHP port: queue: enabled: yes.php-library, pierwszy port na PHP: queue: enabled: yes.
Proposed for Symfony itself: RFC #68051.Propozycja do samego Symfony: RFC #68051.
The idea: Instagram's "Thundering Herds & Promises", April 2019. MemoLock, name and all: Loris Cro, May 2019.Pomysł: „Thundering Herds & Promises” z Instagrama, kwiecień 2019. MemoLock i jego nazwa: Loris Cro, maj 2019.
stop 10 // an experimentprzystanek 10 // eksperyment
AMałydetourobjazd
Forgetting a tag means finding every saved page that carries it. What if Redis indexed the tags itself, and we kept no tag lists at all?Zapomnieć tag to znaleźć wszystkie strony z tym tagiem. A gdyby Redis sam indeksował tagi, a list tagów w ogóle by nie było?
the experiment // redisearcheksperyment // redisearch
Let Redis index the tagsNiech Redis indeksuje tagi
The ideaPomysł
Every saved page keeps its tags in a field, and Redis indexes it.Każda strona trzyma tagi w polu, które Redis indeksuje.
Saving: one write. No tag lists to keep right.Zapis: jedna operacja, bez list tagów do pilnowania.
Forgetting a tag: ask the index for its pages, delete them.Zapomnienie tagu: pytamy indeks o strony i kasujemy je.
Measured: one tag, a million pagesPomiar: jeden tag, milion stron
Classic, fresh database: about 2.5 s, everyone else waiting up to 2 s.Klasyczny backend, świeża baza: około 2,5 s, reszta czeka do 2 s.
RediSearch: around 5 s, but nobody waited over 10 ms.RediSearch: około 5 s, ale nikt nie czekał ponad 10 ms.
After weeks: classic 8.7 s, everyone waiting up to 3.9 s. RediSearch: still around 5 s.Po tygodniach: klasyczny 8,7 s, reszta czeka do 3,9 s. RediSearch: nadal około 5 s.
Pages expired: nothing left. Classic kept all their names in its lists (28 MB).Strony wygasły: nic nie zostało. Klasyczny miał w listach wszystkie ich nazwy (28 MB).
redisearchthe search engine of Redis, shipped with it since Redis 8.0: nothing to install. It indexes fields of the data, so Redis can find, say, every saved page with a given tag.wyszukiwarka wbudowana w Redisa od wersji 8.0: nic do instalowania. Indeksuje pola danych, więc Redis znajdzie np. każdą stronę z danym tagiem.
stop 10 // measuredprzystanek 10 // pomiar
RediSearch: good for small sitesRediSearch: dobry dla małych serwisów
Forgetting one tag, by the pages it is onZapomnienie jednego tagu a liczba jego stron
The verdictWerdykt
Nobody waits: under 7 ms, at any size.Nikt nie czeka: poniżej 7 ms, przy każdej skali.
Nothing left behind: an expired page drops out of the index.Nic nie zostaje: wygasła strona wypada z indeksu.
Beyond 200 000, deleting decides: about 5 µs a page, however the pages are found.Powyżej 200 000 decyduje usuwanie: około 5 µs na stronę, wszystko jedno, jak je znajdziemy.
the lesson // stop 10lekcja // przystanek 10
Every design so far deletes every page. That is the cost to remove.Dotąd każde podejście usuwa każdą stronę. Ten koszt trzeba wyciąć.
The next stop deletes nothing: invalidation takes a few milliseconds, no matter how many pages.Następny przystanek nic nie usuwa: unieważnienie to parę milisekund, choćby stron był milion.
stop 11 // of 15przystanek 11 // z 15
Don't delete,Nie kasuj,decidedecyduj
Every design so far deletes every cached page it forgets: a million pages, a million deletes.The fix: stop deleting, add an invalidation rule instead.Dotąd każde podejście kasuje wszystko, co zapomina: milion stron to milion kasowań.Rozwiązanie: zamiast kasować, dodaj regułę unieważnienia.
OutdatedNieaktualneeverything tagged article-42 made before 12:05wszystko z tagiem article-42 sprzed 12:05
One rule, no matter how many cached pages: a handful of commands for 3 or a million.Jedna reguła, bez względu na liczbę stron: kilka poleceń, czy 3 strony, czy milion.
Decided on fetch: each cached page is checked against the rules when someone asks for it.Decyzja przy odczycie: gdy ktoś prosi o stronę, sprawdzamy, czy nie łapie jej któraś reguła.
the idea // an invalidation rulepomysł // reguła unieważnienia
Add a rule, throw nothing awayDodaj regułę, nic nie wyrzucaj
12:00The front page is saved and stamped "made at 12:00".Strona główna zapisana ze znacznikiem „zrobiona o 12:00”.
12:05Article 42 changes. One invalidation rule is added: "everything tagged article-42, made before 12:05, is outdated".Artykuł 42 się zmienia. Dochodzi jedna reguła unieważnienia: „wszystko z tagiem article-42 sprzed 12:05 jest nieaktualne”.
12:05:01A visitor asks for the front page: older than the rule, tagged article-42, so outdated. Built again, stamped 12:05:01.Ktoś otwiera stronę główną: starsza od reguły, z tagiem article-42, więc nieaktualna. Wygenerowana od nowa, znacznik 12:05:01.
12:06The next visitor asks for the front page: newer than every rule, so the same cached page is served.Kolejna osoba otwiera stronę główną: nowsza od każdej reguły, więc dostaje tę samą stronę z cache.
invalidation rulereguła unieważnieniaone line saying which cached pages are outdated: everything with this tag, made before this moment.jedna linijka o tym, które strony w cache są nieaktualne: wszystko z tym tagiem sprzed tej chwili.
how it works // redisversionedjak to działa // redisversioned
The rules are a streamReguły to stream
Forget a taginvalidateTags(['article-42'])Zapomnienie taguinvalidateTags(['article-42'])
appendsdopisuje
Streamrule at 12:05: tag article-42Streamreguła z 12:05: tag article-42
checked bysprawdzany przez
Read a cached pagestamp "made at 12:00", tags article-42, category-7Odczyt z cacheznacznik „zrobiona o 12:00”, tagi article-42, category-7
Forgetting: one rule, a handful of commands, no matter how many cached pages match.Zapomnienie: jedna reguła, kilka poleceń, bez względu na to, ile stron pasuje.
Reading: one fetch, then a check against the rules newer than the cached page's stamp.Odczyt: jedno pobranie, potem sprawdzenie reguł nowszych niż znacznik strony.
The cost on fetch: the check in PHP, and at most one more read from Redis per second per server, made by one request and shared with all through APCu.Koszt przy odczycie: sprawdzenie w PHP plus co najwyżej jeden dodatkowy odczyt z Redisa na sekundę na serwer; robi go jedno żądanie, a przez APCu korzystają z niego wszystkie.
streama list in Redis you can only add to; an entry's id is the time it was added, and only grows.lista w Redisie tylko do dopisywania; identyfikator wpisu to czas dopisania i tylko rośnie.
the fix // one line, againrozwiązanie // znów jedna linijka
Forgetting one tag: 10 cached pages or a millionZapomnienie jednego tagu: 10 stron czy milion
every storekażdy store
A million cached pages, nobody noticesMilion stron, a nikt nic nie zauważa
C
the trade-offs // stop 11kompromisy // przystanek 11
What it costs, what it guaranteesCena i gwarancje
CostsKoszty
An edit reaches the other servers up to a second later: each re-reads the rules once a second.Inne serwery widzą edycję z opóźnieniem do sekundy: każdy odświeża reguły raz na sekundę.
Outdated cached pages stay in memory until read, cleaned up at night, or expired.Nieaktualne strony zostają w pamięci do odczytu, nocnego sprzątania albo wygaśnięcia.
The rules must never be evicted: like the tag lists, they carry no expiry.Redis nie może wyrzucić reguł: tak jak listy tagów, nie mają TTL.
GuaranteesGwarancje
On its own server, an edit counts at once. A cron job (the CLI) counts as another server.Na własnym serwerze edycja działa od razu. Cron (CLI) liczy się jako inny serwer.
Rules older than 30 days are dropped automatically: no cached page lives longer.Reguły starsze niż 30 dni znikają same: żadna strona w cache nie żyje dłużej.
Rules lost (evicted, deleted): every older cached page is built again. A failover to a replica without the newest rule loses that edit, like any write Redis loses.Gdy reguły przepadną (wyrzucone, skasowane), każda starsza strona generuje się od nowa. Failover na replikę bez najnowszej reguły gubi tę edycję – jak każdy zapis, który Redis zgubi.
compared // stop 11porównanie // przystanek 11
Three ways to forget a tagTrzy sposoby zapominania tagu
Rare, but it may happen: one visitor's page is still being built when the editor saves. The old page lands in the cache after the edit.Rzadko, ale się zdarza: czyjaś strona jeszcze się generuje, gdy redaktor zapisuje zmianę. Stara wersja ląduje w cache już po edycji.
the problem // a late deliveryproblem // spóźniona dostawa
A slow page, a fast editWolna strona, szybka edycja
0 ms0 msA visitor's cached page is missing; the server starts reading the article (the old text).Cache miss: serwer zaczyna czytać artykuł (jeszcze stary tekst).
50 ms50 msThe editor saves the new text, and the article's tag is forgotten.Redaktor zapisuje nowy tekst, a tag artykułu zostaje zapomniany.
300 ms300 msThe first read finishes and saves the old text, after the edit.Pierwszy odczyt się kończy i zapisuje stary tekst, już po edycji.
thenpotemWithout a fix, the old text stays until that cached page expires.Bez zabezpieczenia stary tekst zostaje w cache, dopóki strona nie wygaśnie.
Rare: it takes an edit in the moment a missing page is being built. But on a busy site, sooner or later it happens.Rzadki przypadek, bo edycja musi wpaść akurat wtedy, gdy strona się generuje. Ale przy dużym ruchu prędzej czy później się wydarzy.
racewyścigtwo things happening at once, where the result depends on which one finishes first.dwie rzeczy dzieją się naraz, a wynik zależy od tego, która skończy pierwsza.
1 000 rounds, how many late cached pages stay?1 000 rund, ile spóźnionych stron zostaje w cache?
without the guard, then with itbez strażnika, potem z nim
the fix // the guardrozwiązanie // strażnik
The system remembers recent editsSystem pamięta ostatnie edycje
We note when the miss happens; its save is refused if a newer edit came in between.Zapamiętujemy moment cache miss; jeśli w międzyczasie przyszła edycja, zapis jest odrzucany.
A twist: the versioned store was nearly immune already when invalidating with tags (4 in 1 000): a late page carries the number of an older rule, so the next read finds it outdated.Niespodzianka: przy tagach wersjonowany store był już prawie odporny (4 na 1 000): spóźniona strona ma numer starszej reguły, więc następny odczyt ją odrzuci.
Only nearly: if its server reloads the rules during the build, the old page is saved with the new number and served as fresh. Luck, not design: the guard fixes it.Tylko prawie: jeśli serwer przeładuje reguły w trakcie generowania, stara strona zapisze się z nowym numerem i pójdzie jako świeża. To przypadek, nie projekt: strażnik to naprawia.
However long the page takes to build, the edit is caught: a tag's stamp lives a day, a versioned rule 30 days.Nieważne, jak długo trwa generowanie: edycja zostanie wyłapana. Znacznik tagu żyje dobę, reguła wersjonowana 30 dni.
store_options:
invalidation_window_ms: 60000 # on by default; 0 turns it off
how it works // the guardjak to działa // strażnik
A tombstone and a stampNagrobek i znacznik
A cached page deletedStrona usunięta z cache
Its key becomes a tombstone: a token, kept for 60 s.Jej klucz zmienia się w nagrobek: token na 60 s.
A late save finds a different token from the one its miss saw: refused.Spóźniony zapis widzi już inny token: odrzucony.
The tag gets a stamp: the time, kept for a day.Tag dostaje znacznik czasu, który żyje dobę.
A late save with that tag, begun before the stamp: refused.Spóźniony zapis z tym tagiem, zaczęty przed znacznikiem: odrzucony.
A million cached pages under the tag: one stamp, not a million tombstones.Milion stron z tym tagiem: jeden znacznik, a nie milion nagrobków.
tombstonenagrobek (tombstone)a small mark left where something was deleted, so that a late arrival can tell it came too late.mały ślad tam, gdzie coś usunięto, żeby spóźniony gość wiedział, że przyszedł za późno.
how it works // the tombstonejak to działa // nagrobek
The token lives in the cached page's own keyToken żyje w kluczu samej strony
In Redis: a hash per cached pageStrona w Redisie to hash
> HGETALL cache:front-page
data "<html>…"
tags "article-42"
# after delete(): the token, for 60 s
> HGETALL cache:front-page
epoch "9f2c6e1a4d7b3080"
Inside Redis (Lua): one stepLua w Redisie: jeden krok
-- delete(): token = 8 random bytes, from PHP
redis.call('DEL', key)
redis.call('HSET', key, 'epoch', token)
redis.call('PEXPIRE', key, 60000)
-- the save after a miss: another token? refused
local current = redis.call('HGET', key, 'epoch')
-- ~= is PHP's !==; no token at all refuses nothing
if current and current ~= miss_seen then return 0 end
A miss reads the page and its token together, and keeps the token it saw: none, here.Przy cache miss czytamy stronę razem z tokenem i zapamiętujemy, jaki był: tu żaden.
The late save brings none, finds 9f2c6e1a…: refused. A plain DEL would leave nothing to compare.Spóźniony zapis bez tokenu zastaje 9f2c6e1a…: odrzucony. Sam DEL nie zostawiłby śladu.
epochthe token's field: a generation of the key, not a moment in time. Every delete starts a new one.pole tokenu: generacja klucza, nie punkt w czasie. Każde usunięcie zaczyna nową.
stop 13 // of 15przystanek 13 // z 15
NobodyNiktwaitsnie czeka
When a cached page expires, someone waits for the new one.The fix: nobody does.Gdy strona w cache wygasa, ktoś czeka na nową.Rozwiązanie: nikt nie czeka.
The previous cached page, for a moment: handed out at once, until the new one is ready (a minute at most).Na chwilę poprzednia wersja: zaserwowana od razu, aż nowa będzie gotowa (najwyżej minutę).
One rebuild, after the answer: the new one is built in the background, once the visitor has the page.Jedno generowanie, po odpowiedzi: nowa generuje się w tle, gdy odwiedzający ma już stronę.
When a cached page expires, someone waitsGdy strona w cache wygasa, ktoś czeka
The saved report expires after its 5 minutes.Raport w cache wygasa po 5 minutach.
MemoLock lets one request rebuild it, and the others wait for that one.MemoLock wpuszcza do generowania jedno żądanie, a reszta na nie czeka.
A report that takes 300 ms to build: every visitor in those 300 ms waits for it.Raport generuje się 300 ms, więc każdy, kto przyjdzie w tym czasie, czeka.
the fix // stale-while-revalidaterozwiązanie // stale-while-revalidate
Hand out the previous cached page, for a momentNa chwilę serwuj poprzednią wersję
// once; get() unchanged
$pool = new StaleCache($inner, staleSeconds: 60,
staleIfErrorSeconds: 3600, election: $lock);
$pool->setDeferrer($queue = new RefreshQueue());
$queue->flushAtShutdown(); // after the response
The previous cached page is served only until the new one is ready: here after 300 ms, the report's build. At most 60 s if the rebuild is slow, an hour if it fails.Poprzednia wersja idzie tylko do chwili, gdy nowa jest gotowa: tu 300 ms, tyle generuje się raport. Najwyżej 60 s, gdy generowanie się wlecze, godzinę, gdy padnie.
stale-while-revalidateserve the slightly old cached page while one request fetches the new one.serwuj lekko nieaktualną stronę z cache, póki w tle generuje się nowa.
stale-if-errorstaleIfError (Symfony: staleIfErrorSeconds): when the rebuild fails, say the database is down, the last good cached page goes out for up to that many seconds more, instead of an error.staleIfError (Symfony: staleIfErrorSeconds): gdy generowanie się nie uda, bo np. baza leży, ostatnia dobra strona wychodzi jeszcze przez najwyżej tyle sekund, zamiast błędu.
The cached page expires, nobody waitsStrona w cache wygasa, nikt nie czeka
16 visitors around an expiry16 odwiedzających, 1 wygaśnięcie
stop 14 // of 15przystanek 14 // z 15
ForgetZapomnijsoftlymiękko
An edit takes cached pages out of use at once, and the next visitors wait for the rebuilds.The fix: nobody waits there either.Edycja od razu unieważnia strony w cache, a kolejni odwiedzający czekają, aż strony wygenerują się od nowa.Rozwiązanie: tu też nikt nie czeka.
An edit ages the cached pages: handed out a moment longer instead of being deleted.Edycja postarza strony w cache: zamiast zniknąć, są serwowane chwilę dłużej.
Live once rebuilt: each cached page rebuilt once, after the answers; a minute at most.Zmiana widoczna po wygenerowaniu: każda strona generuje się raz, po odpowiedzi; najwyżej minuta.
the problem // one edit, everywhereproblem // jedna edycja, wszędzie
One edit, 300 rebuildsJedna edycja, 300 stron do wygenerowania
The editor renames a menu item.Redaktor zmienia nazwę pozycji menu.
The menu is part of 300 saved page fragments: all 300 are forgotten at once.Menu jest częścią 300 fragmentów stron w cache: wszystkie 300 zapominamy naraz.
The next visitors wait while the fragments are rebuilt.Następni odwiedzający czekają, aż fragmenty wygenerują się od nowa.
the problem // why stale is not enoughproblem // czemu stale nie wystarcza
stale: 60 needs a page to hand outstale: 60 musi mieć co zaserwować
stale: 60
freshświeża✕ edit✕ edycjanothing: everyone waitsnic: wszyscy czekająnewnowa
The edit takes the page out of use at once: it never expires, so stale has nothing to hand out.Edycja od razu unieważnia stronę, więc stale nie ma czego zaserwować.
stale: 60 soft: true
freshświeżaeditedycjaold: still handed outstara: nadal serwowananewnowa
The edit marks the page old instead of deleting it: stale hands it out while one request rebuilds it.Edycja, zamiast kasować stronę, oznacza ją jako starą: stale serwuje ją dalej, a nowa generuje się w tle.
soft: true is for edits only: past the TTL, stale: 60 hands out the old page without it.soft: true dotyczy tylko edycji: po upływie TTL stale: 60 serwuje starą stronę i bez niego.
the fix // soft invalidationrozwiązanie // miękkie unieważnienie
An edit ages the cached pageEdycja postarza stronę w cache
DisplayWyświetlanie
// showing the menu
return $store->get(
'menu',
fn() => $db->menu(),
ttl: 0,
tags: ['menu'],
stale: 60, // after an edit: 60 s more…
soft: true, // …while one rebuilds it
);
EditEdycja
// a menu item renamed: soft
$store->invalidateTags(['menu']);
// an urgent fix that must show
// at once: hard
$store->invalidateTags(
['menu'],
hard: true,
);
Nobody waits, and the edit is live as soon as the page is rebuilt: seconds, a minute at most.Nikt nie czeka, a edycja jest widoczna, gdy tylko strona wygeneruje się od nowa: sekundy, najwyżej minuta.
soft invalidationmiękkie unieważnieniean edit marks the cached page as old instead of deleting it, for a moment.edycja na chwilę oznacza stronę w cache jako starą, zamiast ją usuwać.
The same edit, nobody waitsTa sama edycja, nikt nie czeka
16 visitors around an edit16 odwiedzających, jedna edycja
all together // one callwszystko razem // jedno wywołanie
One call, every stopJedno wywołanie, każdy przystanek
$store->get('front-page', fn() => $this->build(),
ttl: 300, // fresh for 5 minutes
tags: ['article-42'], // forgotten when article 42 changes
stale: 60, // then served one more minute while one request rebuilds it
soft: true, // after an edit, too
staleIfError: 3600, // the database down? the last good one, for an hour
);
// the lock (stop 9) and the guard (stop 12): on by default, nothing to write
all together // symfonywszystko razem // symfony
The same, in SymfonyTo samo w Symfony
// once: the pool, in layers (artigo/versioned-cache, artigo/cache-stampede)
$inner = new VersionedRedisTagAwareAdapter($redis, // versioned tags (stop 11), the guard (12)
softGraceSeconds: 60); // what an edit reaches, kept a minute
$lock = MemoLock::fromDsn('redis://redis');
$inner->setCallbackWrapper($lock); // the lock (stop 9)
$pool = new StaleCache($inner, staleSeconds: 60, // served stale while one request rebuilds
staleIfErrorSeconds: 3600, // the database down? the last good one
election: $lock, soft: true); // after an edit, too
$pool->setDeferrer($queue = new RefreshQueue()); // the rebuild runs after the response
$queue->flushAtShutdown(); // once Symfony has sent it
// then every time: Symfony's own get(), unchanged
$pool->get('front-page', function(ItemInterface $item) {
$item->expiresAfter(300)->tag(['article-42']);
return $this->build();
});
detours // not on the mapobjazdy // poza mapą
Two side roadsDwie boczne drogi
Two tiers, side by side: APCu inside every server, for small things every request needs: loaded config, translations, routes, short lookup lists, the invalidation rules. Redis for everything else: pages, fragments, and data such as nested collections an API returns as JSON.Dwie warstwy obok siebie: APCu na każdym serwerze, na drobiazgi potrzebne każdemu żądaniu: wczytaną konfigurację, tłumaczenia, routing, krótkie słowniki, reguły unieważnienia. Redis na resztę: strony, fragmenty i dane, np. zagnieżdżone kolekcje, które API zwraca jako JSON.
Redis Cluster: the same store spread over several Redis servers.Redis Cluster: ten sam store rozłożony na kilka serwerów Redisa.
MemoLock: the lock in Redis, the others woken by a message (+3 ms).MemoLock: blokada w Redisie, resztę budzi wiadomość (+3 ms).
FleetLock: the same lock on any symfony/lock store, PostgreSQL too; on most stores the others check every 100 ms (+108 ms).FleetLock: ta sama blokada na dowolnym store z symfony/lock, także PostgreSQL; na większości z nich reszta sprawdza co 100 ms (+108 ms).
StaleCache: serves the previous version until the new one is built in the background.StaleCache: serwuje poprzednią wersję, dopóki w tle nie wygeneruje się nowa.
composer require artigo/versioned-cache artigo/cache-stampede · MIT
upstream // symfony/symfony
Three RFCs and a pull requestTrzy RFC i pull request
#68050 A tag-aware Redis adapter that does not walk the matches.#68050 Adapter Redisa z obsługą tagów, bez przeglądania pasujących wpisów.
#68051 Stampede protection across all servers, woken by a message.#68051 Ochrona przed stampede na wszystkich serwerach, budzenie wiadomością.
#68052 Serve the old value while one request refreshes it.#68052 Serwuj starą wartość, póki w tle generuje się nowa.
#68083 ZstdMarshaller.
Read them, comment, try the packages.Czytajcie, komentujcie, testujcie pakiety.
the road // what it taughtdroga // czego nas nauczyła