SymfonyWorld Online 2020
100% online
30+ talks + workshops
Live + Replay watch talks later

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:

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

Comments

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).
Login with SymfonyConnect to post a comment