New in Symfony 5.2: Async cache recomputing
October 1, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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:
- 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 implementCallbackInterface
to be auto-tagged ascontainer.reversible
; - The service must compute the value using just its cache key, which is the only context information included in the message.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.