Contributed by
Nicolas Grekas
in #30572.
A cache stampede is a type of cascading failure that can occur when caching mechanisms come under very high load. Symfony Cache component provides built-in protection against stampedes via “probabilistic early expiration”.
With this approach, each process accessing the cached value makes a decision about recomputing the value or not. This is a pure probabilistic decision where the probability increases as the cache value expiration gets closer.
In Symfony 5.2 we’ve improved this feature to allow you to recompute the cache
value asynchronously by sending it to a message bus (using the Messenger component).
First, add the new early_expiration_message_bus
option to your cache pool and
define the name of the bus where the message will be sent:
1 2 3 4 5 6 | # config/packages/cache.yaml
framework:
cache:
pools:
test.cache:
early_expiration_message_bus: messenger.default_bus
|
Then, route the new EarlyExpirationMessage
message to one of your transports:
1 2 3 4 5 | # config/packages/messenger.yaml
framework:
messenger:
routing:
'Symfony\Component\Cache\Messenger\EarlyExpirationMessage': amqp
|
That’s it. Symfony will now start sending messages whenever a cache value needs recomputing. Start your workers to consume those messages and get the work done. There’s two things to keep in mind when using this feature:
[$someService, 'somePublicMethod']
because PHP closures can’t be serialized (and thus cannot be sent through the bus);What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...