rg-dev #69 // 25 nov 2026rg-dev #69 // 25 lis 2026
Teaching websitesJak nauczyć strony
when to forgetzapominać w porę

The surprising half of caching.Zaskakująca połowa cache'owania.

fifteen stops · real demos · open sourcepiętnaście przystanków · prawdziwe dema · open source

the slides, on your deviceslajdy na własnym urządzeniu artigo-dev.github.io/cache-talk
who // is talkingkto // występuje

Marcin Gil

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.

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
NoBez cache

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

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);
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ć.

  1. 12:00The front page is saved for 5 minutes.Strona główna jest przechowywana przez 5 minut.
  2. 12:01The editor fixes a typo in the headline.Redaktor poprawia literówkę w tytule.
  3. 12:01–12:05All visitors still see the page with a typo.Wszyscy odwiedzający nadal widzą stronę z literówką.
  4. 12:05The application's cached page expires; the fix shows…Strona w cache aplikacji wygasa, poprawka się pojawia…
  5. 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.

read morewięcej php-library · tagsphp-library · tagi

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 pliki start to hurtzaczynają boleć

Two problems arrive together:Dwa problemy naraz:

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

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
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
OneJeden shared 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.

read morewięcej redis.io · key evictionredis.io · usuwanie kluczy valkey.io

first // what is Redis?najpierw // czym jest Redis?

One shared memory, very fastWspólna pamięć, błyskawiczna

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

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
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.

  1. 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.
  2. lfuleast frequently used: the cached page asked for the fewest times.least frequently used: strona, o którą pytano najrzadziej.
  3. ttlthe cached page closest to expiring anyway.strona, która i tak wygaśnie najwcześniej.
  4. 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 page
Listy 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 again
Strony 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
SmallerMniejsze cached pagesstrony w cache

Memory is not endless. The fix: compress every cached page.Pamięć nie jest z gumy. Rozwiązanie: kompresja każdej strony.

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.

read morewięcej symfony/symfony #68083 · ZstdMarshaller zstd Duda · asymmetric numeral systemsDuda · asymetryczne systemy liczbowe

compression // our Symfony PR #68083kompresja // nasz PR #68083 do Symfony

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…codeckodeksize afterrozmiar pocompress, mskompresja, msdecompress, msdekompresja, ms
~300 B recordsrekordy ~300 Bdeflate66 %66 %0.0110,0110.0030,003
zstd72 %72 %0.0070,0070.0030,003
~2.6 KB modelsmodele ~2,6 KBdeflate48 %48 %0.0560,0560.0140,014
zstd51 %51 %0.0240,0240.0060,006
335 KB web pagestrona 335 KBdeflate18.5 %18,5 %6.4256,4250.4830,483
zstd19.0 %19,0 %1.0571,0570.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
TagListy liststagó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.

read morewięcej Cm_Cache_Backend_Redis · the classic designCm_Cache_Backend_Redis · klasyczny backend php-library · bans, measuredphp-library · czystki, pomiary

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
the problem // one at a timeproblem // po kolei

Forgetting a million cached pages makes visitors waitZapominamy milion stron, a odwiedzający czekają

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

  cache:
    persistent:
-     store: \Talk\Store\RedisClassic
+     store: Redis                        # php-library's Store\Redis
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 Redisa to 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.

read morewięcej redis.io · functionsredis.io · funkcje php-library · Cache.lua

the problem // one step, one tripproblem // jeden krok, jeden kurs

The data rides both waysDane płyną tam i z powrotem

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
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
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 jobzadaniehowjakcommandspoleceniabytes to Redisbajty do Redisabytes backbajty z Redisa
save a page,
5 tags
zapis strony,
5 tagów
stepskroki980445
functionfunkcja14934
forget a tag,
100 000 cached pages
zapomnienie tagu,
100 000 stron
stepskroki122 489 1491 678 983
functionsfunkcje10115 7872 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

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
TheCache stampede

The cached report is gone, and everyone runs to the database at once.Raport wypadł z cache i wszyscy naraz rzucają się na bazę.

read morewięcej php-library · README.MEMOLOCK.md artigo-dev/cache-stampede symfony/symfony #68051 Instagram · thundering herds & promises

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.

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

The code: unchangedKod: bez zmian

// application/stores/Reports.php
return $this->cacheService->getStore()->get(
    'report-' . $month,
    // the database: 300 ms
    fn() => Origin::work('report ' . $month),
    ttl: 300,
    tags: ['reports'],
);

The config: one line switches it onKonfiguracja: jedna linijka to włącza

  cache:
    persistent:
      store: Redis
      queue:
-       enabled: no      # the stampede you just saw
+       enabled: yes     # MemoLock, the default
        lock_ttl_ms: 5000

Symfony: artigo/cache-stampedeSymfony: artigo/cache-stampede

// 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

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

the first requestpierwsze żądanie redis the 23 otherspozostałe 23 SET lock 9f2c… NX PX 5000 no cached report: the first one takes the lockbrak raportu w cache: pierwsze zakłada blokadę NX: only if free · PX: gone after 5 sNX: tylko gdy wolna · PX: znika po 5 s lock SET lock a71b… NX → takenSET lock a71b… NX → zajęta SUBSCRIBE lock:done wait for a message, no checking every 100 msczekają na wiadomość, bez sprawdzania co 100 ms asks the database: 300 mspyta bazę: 300 ms saves the reportzapisuje raport FCALL release: my token? PUBLISH · DELFCALL release: mój token? PUBLISH · DEL one call: frees the lock, wakes everyonejedno wywołanie: zwalnia blokadę, budzi resztę message: donewiadomość: gotowe the others wake at once: +3 msreszta budzi się od razu: +3 ms GET report → thereGET report → jest one rebuild for all 2424 żądania, jedno generowanie
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.
  • Symfony: artigo/cache-stampede, a drop-in.Symfony: artigo/cache-stampede, do podpięcia.
  • 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.

read morewięcej php-library · README.MEMOLOCK.md artigo-dev/cache-stampede symfony/symfony #68051 Instagram · thundering herds & promises redis.io · caches, promises and locks

stop 10 // an experimentprzystanek 10 // eksperyment
AMały detourobjazd

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?

read morewięcej redis.io · search and query php-library · README.CACHE.md

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

under a secondponiżej sekundy 0 1 s 2 s 3 s 4 s 5 s 6 s 0 200 000 400 000 600 000 800 000 1 000 000 cached pages on the tagstron w cache z tym tagiem 0.99 s0,99 s 2.51 s2,51 s 5.15 s5,15 s 50 000 pages: 0.22 s 100 000 pages: 0.46 s 200 000 pages: 0.99 s 300 000 pages: 1.60 s 500 000 pages: 2.51 s 1 000 000 pages: 5.15 s 50 000 stron: 0,22 s 100 000 stron: 0,46 s 200 000 stron: 0,99 s 300 000 stron: 1,60 s 500 000 stron: 2,51 s 1 000 000 stron: 5,15 s

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ąć.

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.

read morewięcej artigo-dev/versioned-cache symfony/symfony #68050

the idea // an invalidation rulepomysł // reguła unieważnienia

Add a rule, throw nothing awayDodaj regułę, nic nie wyrzucaj

  1. 12:00The front page is saved and stamped "made at 12:00".Strona główna zapisana ze znacznikiem „zrobiona o 12:00”.
  2. 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”.
  3. 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.
  4. 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-7
Odczyt z cacheznacznik „zrobiona o 12:00”,
tagi article-42, category-7
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

Same code, another storeTen sam kod, inny store

  cache:
    persistent:
-     store: Redis
+     store: RedisVersioned
      queue:
        enabled: yes

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

RedisTagAwareAdaptersymfony/cacheTagAwareAdaptersymfony/cacheversionedphp-library · artigo/versioned-cachewersjonowanyphp-library · artigo/versioned-cache
forgetting a million pages1 000 tags, 50 per callzapomnienie miliona stron1 000 tagów, 50 na wywołanie1.4 s1,4 s1 006 000 commands, others wait up to 61 ms1 006 000 poleceń, reszta czeka do 61 ms3 ms3 ms20 commands: deletes version keys20 poleceń: usuwa klucze wersji3 ms3 ms81 commands, for 3 pages or a million81 poleceń, 3 strony czy milion
10 reads, a fresh PHP workerone by one, 0.25 ms to Redis10 odczytów, świeży worker PHPpo kolei, 0,25 ms do Redisa2.5 ms2,5 ms10 round trips10 round tripów5.2 ms5,2 ms20 round trips: the tags' versions too20 round tripów: także wersje tagów3.2 ms3,2 ms10 round trips: the rules are in memory10 round tripów: reguły są w pamięci
left in Redisślad w Redisiea list per taglista na taga version key per tag, never expiresklucz wersji na tag, bez TTLone stream, 30 daysjeden stream, 30 dni

Cheap to forget, or cheap to read. The versioned store is both.Albo tanie zapominanie, albo tani odczyt. Wersjonowany store ma jedno i drugie.

measuredpomiary artigo-dev/versioned-cache · benchmarksartigo-dev/versioned-cache · benchmarki symfony/symfony #68050 symfony/cache 8.1.11 · Redis 8.10.1

stop 12 // of 15przystanek 12 // z 15
A lateSpóźniona deliverydostawa

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.

read morewięcej php-library · invalidation guardphp-library · strażnik unieważnień

the problem // a late deliveryproblem // spóźniona dostawa

A slow page, a fast editWolna strona, szybka edycja

  1. 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).
  2. 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.
  3. 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.
  4. 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

      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

token 9f2c6e1a kept 60 sżyje 60 s
  • 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.

A tag forgottenZapomniany tag

  • 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
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
NobodyNikt waitsnie 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.

read morewięcej RFC 5861 · stale-while-revalidate symfony/symfony #68052 artigo-dev/cache-stampede php-library · stale-while-revalidate

the problem // the waitproblem // czekanie

When a cached page expires, someone waitsGdy strona w cache wygasa, ktoś czeka

the fix // stale-while-revalidaterozwiązanie // stale-while-revalidate

Hand out the previous cached page, for a momentNa chwilę serwuj poprzednią wersję

php-library: per callphp-library: w wywołaniu

return $store->get('report',
    fn() => $db->report(),
    ttl: 300,
    stale: 60, staleIfError: 3600,
);

Symfony: per poolSymfony: na całą pulę

// once; get() unchanged
$pool = new StaleCache($inner, staleSeconds: 60,
    staleIfErrorSeconds: 3600, election: $lock);
$pool->setDeferrer($queue = new RefreshQueue());
$queue->flushAtShutdown(); // after the response
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
ForgetZapomnij softlymię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.

read morewięcej php-library · soft invalidationphp-library · miękkie unieważnienie symfony/symfony #68052

the problem // one edit, everywhereproblem // jedna edycja, wszędzie

One edit, 300 rebuildsJedna edycja, 300 stron do wygenerowania

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,
);
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

read morewięcej php-library · the two tiersphp-library · dwie warstwy php-library · RedisClusterVersioned symfony · ApcuAdapter: a pool of its ownsymfony · ApcuAdapter: osobna pula symfony · RedisAdapter, a cluster toosymfony · RedisAdapter, także klaster

stop 15 // of 15przystanek 15 // z 15
Back toPowrót do Symfony

The same ideas, for every Symfony application.Te same pomysły dla każdej aplikacji Symfony.

read morewięcej artigo-dev/versioned-cache artigo-dev/cache-stampede #68050 #68051 #68052 #68083

open source // artigo

Two packages, drop-inDwa pakiety, bez przeróbek

artigo/versioned-cache

  • A tag-aware Redis adapter for symfony/cache.Adapter Redisa z obsługą tagów dla symfony/cache.
  • Forgetting a tag: a handful of commands, for 3 cached pages or a million.Zapomnienie tagu: kilka poleceń, czy to 3 strony, czy milion.

artigo/cache-stampede

  • 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

Read them, comment, try the packages.Czytajcie, komentujcie, testujcie pakiety.

the road // what it taughtdroga // czego nas nauczyła

Fifteen stops, fifteen lessonsPiętnaście przystanków, piętnaście lekcji

  1. Cache what is expensive to compute.Trzymaj w cache to, co kosztowne do wygenerowania.
  2. A timer alone forgets too late, or too often.Sam zegar zapomina za późno albo za często.
  3. Tag what a cached page was built from.Taguj stronę tym, z czego ją wygenerowano.
  4. One memory per server is not one memory.Osobne pamięci serwerów to nie jedna pamięć.
  5. Give shared memory a limit: forget cached pages, never the lists.Wspólna pamięć z limitem: zapominaj strony, nigdy listy.
  6. Smaller cached pages fit more, if they decompress fast.Mniejszych stron wejdzie więcej, jeśli szybko się rozpakują.
  7. Redis serves one at a time: do big jobs in small bites.Redis robi jedno naraz: duże zadania tnij na małe kawałki.
  8. Send the job, not the steps: the data stays in Redis.Wysyłaj zadanie, nie kroki: dane zostają w Redisie.
  9. One rebuild per cached page, for every server.Jedno generowanie strony na wszystkie serwery.
  10. Every design that deletes pays for every page: remove the deleting.Kto usuwa, płaci za każdą stronę: przestań usuwać.
  11. Don't delete: decide on fetch.Nie kasuj: decyduj przy odczycie.
  12. A late save must know what happened since it started.Spóźniony zapis musi wiedzieć, co się stało, odkąd ruszył.
  13. Slightly old, for a moment, beats everyone waiting.Lepiej chwilę serwować starą wersję, niż kazać wszystkim czekać.
  14. An edit can be soft too: the old cached page for a moment, one rebuild.Edycja też może być miękka: stara strona przez chwilę, jedno generowanie.
  15. Give it back: the ideas belong where everyone can use them.Oddaj: niech z tych pomysłów korzysta każdy.
thank you // questions?dziękuję // pytania?
Remember.Pamiętaj.
Forget on time.Zapominaj w porę.

The deck, the demos and every number: github.com/artigo-devSlajdy, dema i wszystkie liczby: github.com/artigo-dev

artigo/versioned-cache · artigo/cache-stampede · ovos/php-library · codesafe: ovos.github.io/codesafe