New in Symfony 5.2: Async cache recomputing
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:
- You can only use callables in the form
[$someService, 'someMethod']because PHP closures can’t be serialized. Moreover, for this to work, the service must be public or it must implement
CallbackInterfaceto be auto-tagged as
- The service must compute the value using just its cache key, which is the only context information included in the message.
New in Symfony 5.2: Async cache recomputing symfony.com/blog/new-in-symfony-5-2-async-cache-recomputingTweet this
Become a certified developer! Exams are online and available in all countries.Register Now