Hello my friends,
It's been a while since my last post. I wanted today to share what L2 caching in Magento is and what are two ways you can utilize it.
So what L2 caching is?
In really simple words to reduce network congestion and bandwidth usage between microservices, this mechanism is implemented using \Magento\Framework\Cache\Backend\RemoteSynchronizedCache class.
Magento stores the hashed data version in Redis, with the suffix ‘:hash’ appended to the regular key. In case of an outdated local cache, the data is transferred to the local machine with a cache adapter.
Magento or Devdocs gave really nice example on how to modify or replace the existing cache section in the app/etc/env.php file (https://devdocs.magento.com/guides/v2.4/config-guide/cache/two-level-cache.html), so basically it does what it does stores local backend to RAM, but what I want to share todate is that you can load balance between two Redis environments instead, let's say we can make one locally hosted and one on another node using well network.
'cache' => [ 'frontend' => [ 'default' => [ 'backend' => '\\Magento\\Framework\\Cache\\Backend\\RemoteSynchronizedCache', 'backend_options' => [ 'remote_backend' => '\\Magento\\Framework\\Cache\\Backend\\Redis', 'remote_backend_options' => [ 'persistent' => 0, 'server' => 'redis-somewhere-in-the-cloud', 'database' => '1', 'port' => '6379', 'password' => '', 'compress_data' => '1' ], 'local_backend' => '\\Magento\\Framework\\Cache\\Backend\\Redis', 'local_backend_options' => [ 'persistent' => 0, 'server' => '127.0.0.1', 'database' => '3', 'port' => '6379', 'password' => '', 'compress_data' => '1' ], 'use_stale_cache' => false ], 'frontend_options' => [ 'write_control' => false ], 'id_prefix' => 'd01_' ], 'page_cache' => [ 'id_prefix' => 'd01_', 'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis', 'backend_options' => [ 'server' => '127.0.0.1', 'database' => '2', 'port' => '6379', 'password' => '', 'compress_data' => '0', 'compression_lib' => '' ] ] ], 'allow_parallel_generation' => false ],
In my example using https://github.com/nemke82/magento2gitpod I've made a tests and indeed data is spread between two services.
db1:keys=148,expires=42,avgttl=786241446 <-- 1st Redis db3:keys=62,expires=21,avg_ttl=821121720 <-- Failover Redis environment
gitpod /workspace/magento2gitpod $ redis-cli info
Magento recommends using Redis for remote caching (\Magento\Framework\Cache\Backend\Redis) and CmCacheBackendFile for the local caching of data in shared memory, using 'localbackendoptions' => ['cachedir' => '/dev/shm/'], but as you can see we can use Redis remote or locally hosted instead and bring other benefits from it.
Hope this article helps. Good luck optimizing!