Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 5.2: Async cache recomputing

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:

# config/packages/cache.yaml
                early_expiration_message_bus: messenger.default_bus

Then, route the new EarlyExpirationMessage message to one of your transports:

# config/packages/messenger.yaml
            '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 CallbackInterface to be auto-tagged as container.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.


Is this feature available in symfony 4.4?
@Mikhail no, because Symfony only adds new features to unreleased versions (5.2 in this case). Already published versions (e.g. 4.4 and 5.1) only get bug fixes. When 5.2 is released (at the end of November 2020) it will only get bug fixes (and new features will go to Symfony 5.3).

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.