from env.php to compression
The Redis cache backend replaces Magento's default file based cache with an in memory store and removes one of the most common I/O bottlenecks in production shops. Understanding env.php, Cm_Cache_Backend_Redis and the related parameters for compression, database separation and cache tags lets you tune the cache backend for catalog size and traffic instead of relying on defaults.
Table of Contents
- 1. Why Redis as a cache backend
- 2. env.php basic structure of the cache section
- 3. Cm_Cache_Backend_Redis in detail
- 4. Database index separation in the cache backend
- 5. Compression: compress_data, compress_tags, compress_threshold
- 6. How Magento stores cache tags in Redis
- 7. Connection options: persistent, timeout, retry
- 8. Monitoring and debugging the cache backend
- 9. Redis cache backend versus the file system backend
- 10. Summary
- 11. FAQ
1. Why Redis as a cache backend
Magento's default cache stores serialized data as files on disk under var/cache. On every page request Magento reads dozens of cache entries, for example configuration, layout XML, block HTML and EAV attributes. On a single server with a fast SSD this barely shows up, but as soon as several web servers sit behind a load balancer the file based cache backend becomes a problem: each server keeps its own cache state, invalidations do not propagate across the fleet, and NFS mounts used as shared storage add latency instead of removing it.
A Redis cache backend solves this by moving the cache out of the file system into a central in memory store that all web servers access simultaneously. Reads sit well under one millisecond, writes are atomic, and invalidations take effect immediately on every node. Magento uses the backend class Cm_Cache_Backend_Redis for this, shipped as the Composer dependency colinmollenhour/cache-backend-redis, built specifically for Zend Framework compatible cache tags.
The prerequisite is the PHP extension redis (phpredis) or a compatible Predis fallback, plus a reachable Redis server from version 5.0 onward, with Redis 7.x recommended for Magento 2.4.8. The cache backend can be configured separately from session and full page cache storage, which in practice is almost always the right choice because the three roles have different access patterns and memory requirements.
2. env.php basic structure of the cache section
Configuration of the cache backend happens entirely in app/etc/env.php under the cache key. This section holds a frontend array of named cache frontends, where default acts as the fallback for every Magento cache type that has no explicit assignment. Each cache type, for example config, layout, block_html or full_page, can be assigned its own frontend if needed, which in practice is usually only done to separate the full page cache from the rest of the cache backend.
Inside a frontend entry, backend defines the PHP class Magento instantiates for that cache backend. For Redis it is Cm_Cache_Backend_Redis. The backend_options key takes an array with all connection and behavior parameters, explained in detail throughout this article. Optionally, frontend_options controls Zend cache frontend behavior such as automatic serialization, which for the Redis backend is usually left at Magento defaults.
<?php
// app/etc/env.php - cache section, Redis as default cache backend
return [
// ... other env.php keys omitted for brevity
'cache' => [
'frontend' => [
'default' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => '127.0.0.1',
'port' => '6379',
'database' => '0',
'password' => '',
'compress_data' => '1',
'compress_tags' => '1',
'compress_threshold' => '20480',
'compression_lib' => 'gzip',
],
],
'page_cache' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => '127.0.0.1',
'port' => '6379',
'database' => '1',
'compress_data' => '0',
],
],
],
],
];
3. Cm_Cache_Backend_Redis in detail
The class Cm_Cache_Backend_Redis implements the Zend cache backend interface and translates Zend cache operations such as save, load and clean into Redis commands. Unlike generic Redis cache adapters, this cache backend honors the tag based invalidation that Magento requires for the configuration and layout cache. Without this tag support, bin/magento cache:clean config would not work, because generic Redis clients have no concept of cache tags.
Internally the cache backend creates a main key with the prefix zc:k: for every cache entry, plus metadata keys for tags and expiration times. When storing an entry with tags, the backend additionally updates tag to id mappings as Redis sets, so clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG) can efficiently find every affected entry without scanning the entire keyspace. This data structure is the reason the Redis cache backend is significantly faster than a file based backend with directory scans when it comes to tag bound invalidation.
4. Database index separation in the cache backend
The database parameter inside the backend_options array selects one of the 16 logical Redis databases (index 0 through 15 by default) within the same Redis instance. If the cache backend uses the same index as session storage or the full page cache, every key ends up in the same namespace. A FLUSHDB that was only meant to clear the configuration cache can then accidentally wipe out active sessions as well.
Common practice is to assign the general cache backend index 0, the full page cache index 1, and session storage index 2. This separation costs nothing in terms of performance, because all indexes live inside the same Redis instance and the same process, but it significantly reduces operational risk. For very large installations with high session or cache volume, physically separating onto distinct Redis instances is also worthwhile, though that is a separate operational decision beyond simply choosing database indexes.
5. Compression: compress_data, compress_tags, compress_threshold
Large cache entries such as serialized layout XML or full block HTML can span several hundred kilobytes. Without compression this memory footprint multiplies quickly across thousands of entries in the cache backend. The compress_data parameter enables compression of the payload, while compress_tags separately controls whether tag metadata is compressed as well. Both values accept 0 or 1 as a string.
compress_threshold defines in bytes the size above which an entry is compressed at all, with a default of 20480 bytes, that is 20 kilobytes. Smaller entries are stored uncompressed because the CPU overhead of compression does not pay off for small values. compression_lib selects the algorithm: gzip is available everywhere and offers good compression ratios at moderate CPU cost, lzf and snappy are faster but compress less and require additional PHP extensions. For most Magento shops, gzip in the cache backend is the sensible default, because CPU on the web server is usually more abundant than RAM on the Redis server.
<?php
// app/etc/env.php - cache backend with tuned compression for large layouts
'cache' => [
'frontend' => [
'default' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => '127.0.0.1',
'port' => '6379',
'database' => '0',
'compress_data' => '1',
'compress_tags' => '1',
// Only compress entries larger than 8 KB to save CPU on small entries
'compress_threshold' => '8192',
'compression_lib' => 'gzip',
'automatic_cleaning_factor' => '0',
],
],
],
],
6. How Magento stores cache tags in Redis
Cache tags are the core concept that sets the Redis cache backend apart from a plain key value store. When Magento stores a block HTML entry, it attaches tags such as CATALOG_PRODUCT_123 or FPC. When a product changes, Magento calls clean(MATCHING_TAG, ['CATALOG_PRODUCT_123']), and the cache backend deletes exactly the entries carrying that tag without touching any other cache data.
In Redis this structure is visible directly through redis-cli: keys with the prefix zc:ta: contain sets of cache ids per tag, while zc:td: keys track ids that have already been removed. Running SMEMBERS zc:ta:CATALOG_PRODUCT_123 shows which cache entries are currently linked to a given tag, which is very helpful when debugging invalidation issues in the cache backend.
# Inspect cache backend keys and tag structures directly in Redis
redis-cli -n 0 KEYS "zc:k:*" | head -20
redis-cli -n 0 SMEMBERS "zc:ta:CATALOG_PRODUCT_123"
redis-cli -n 0 TTL "zc:k:CACHE_ENTRY_ID"
# Count total keys in the cache backend database
redis-cli -n 0 DBSIZE
# Check memory used specifically by the cache database
redis-cli -n 0 INFO keyspace
7. Connection options: persistent, timeout, retry
The persistent parameter in the cache backend enables persistent PHP FPM connections to Redis, identified by a freely chosen connection id string. This saves the TCP handshake on every request, but works reliably only with phpredis, not with Predis. In containerized environments with short lived PHP FPM processes, persistent usually helps little, while in classic long running worker setups it can save noticeable latency.
connect_retries defines how many times the cache backend retries a failed connection attempt before throwing an exception, with a default of 1. read_timeout limits, in seconds, how long Magento waits for a Redis response. Set too low, large cache reads abort under load; set too high, requests hang unnecessarily long during a Redis outage. A value between 2.5 and 10 seconds has proven reliable for production Magento installations.
<?php
// app/etc/env.php - cache backend connection tuning for long-running workers
'cache' => [
'frontend' => [
'default' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => '127.0.0.1',
'port' => '6379',
'database' => '0',
'persistent' => 'magento-cache-pool',
'connect_retries' => '2',
'read_timeout' => '5',
],
],
],
],
8. Monitoring and debugging the cache backend
bin/magento cache:status shows which cache types are active, but says nothing about the state of the Redis cache backend itself. For real diagnostics, redis-cli INFO is the entry point: the memory section shows used_memory_human and maxmemory_policy, the stats section shows keyspace_hits and keyspace_misses, whose ratio reflects the effective hit rate of the cache backend.
A low hit rate usually points to TTLs that are too short, a maxmemory limit that is too small with aggressive eviction, or frequent, broad invalidations. redis-cli --bigkeys finds oversized entries, which hint at missing compression or unusually large layout blocks. In production, MONITOR should only be used briefly and carefully, since it logs every single command and can itself become a load under high throughput.
# Core hit-rate and memory diagnostics for the cache backend
redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses"
redis-cli INFO memory | grep -E "used_memory_human|maxmemory_policy"
# Find oversized entries that may be missing compression
redis-cli --bigkeys
# Confirm which cache types are enabled at the application level
bin/magento cache:status
9. Redis cache backend versus the file system backend
The choice of cache backend affects latency, scalability and operational effort equally. For single server setups with low traffic the file based backend may be sufficient, for everything beyond that Redis is the technically superior choice.
| Criterion | File system backend | Redis cache backend | Impact |
|---|---|---|---|
| Read access | Disk I/O, several ms | In memory, under 1 ms | Significantly lower time to first byte |
| Multiple web servers | NFS or inconsistent cache | Central, consistent cache | No stale fragments on individual nodes |
| Tag invalidation | Directory scan | Set based lookups | Faster, more targeted cache cleanup |
| Operational effort | No extra service needed | Redis server to administer | Extra component, but manageable |
| Memory usage | Limited only by disk | RAM bound, compression possible | Sizing and maxmemory policy required |
In practice the decision for production shops is almost always clear cut: as soon as more than one web server is in use or scalability is on the horizon, a Redis cache backend is a prerequisite for reliable behavior. The only trade off is the additional operational effort for the Redis server itself, which is well manageable with standard monitoring.
10. Summary
The Redis cache backend in Magento is configured entirely through app/etc/env.php, using the backend class Cm_Cache_Backend_Redis and a backend_options array that controls server, port, database index, compression and connection behavior. Separating roles by database index prevents collisions between cache, session and full page cache. Compression with compress_data, compress_tags and compress_threshold noticeably reduces memory footprint for large layout and block entries.
Anyone who configures the cache backend correctly benefits from millisecond read access, a consistent cache state across multiple web servers, and efficient, tag based invalidation that deletes only the entries actually affected. Monitoring through redis-cli INFO and regularly checking the hit rate are the foundation for keeping the cache backend healthy over time.
Redis Cache Backend in Magento - The Essentials at a Glance
Backend class
Cm_Cache_Backend_Redis registered in app/etc/env.php under cache.frontend.default.backend.
Database separation
A dedicated database index for cache, session and full page cache prevents key collisions.
Compression
compress_data, compress_tags and compress_threshold reduce RAM usage for large entries.
Monitoring
Check redis-cli INFO, --bigkeys and the hit rate regularly instead of relying on defaults.