A group of high-traffic content sites I work on share one Yii2 codebase and one production Redis node for page and query caching. Over time the keyspace grew to 13.97 GiB, and memory pressure meant evictions. Every eviction was a cache miss, and every miss was a MySQL round trip that should never have happened.
After adding transparent zlib compression the same keyspace measured ~1.56 GiB, an 8.96× reduction, with no downtime and no flag day.
Compress inside the serializer, not in the callers
Yii's cache component lets you swap the serializer pair. Instead of serialize() and unserialize() we plug in a codec with encode() and decode().
That placement is the whole design. Every app — web, API, backend, console — picks it up from one place, RedisCache::init(), so there is no config file that can be forgotten on one class of server. Nobody calling the cache has to know compression exists.
One rule drives everything else: reads must always understand both formats. A value written before the rollout and a compressed value written after it both have to decode, on every host, throughout.
An envelope you can recognise
Compressed values get a 4-byte header.
byte 0 0xC7 magic — never the first byte of PHP serialize() output
byte 1 0x01 compressor id: 1 = zlib
byte 2-3 0x0000 reserved: dictionary id
<payload> gzcompress(serialize([$value, $dependency]), level)PHP's serialize() output always starts with a type letter: a, O, s, i, d, b, N. So 0xC7 can never collide with a legacy value, which is why that byte and not a prettier one. decode() checks byte 0, and magic means decompress while anything else falls through to plain unserialize().
Byte 1 is the part I would not skip. Adding zstd later becomes a new compressor id rather than a migration, because values from both codecs decode side by side forever.
public function decode(string $raw): mixed
{
if ($raw === '' || $raw[0] !== self::MAGIC) {
return unserialize($raw); // legacy, uncompressed
}
$payload = substr($raw, 4);
return unserialize(gzuncompress($payload));
}Below about 512 bytes the envelope and zlib framing stop paying for themselves, so CACHE_CODEC_MIN_SIZE leaves small values as plain serialize() output.
Level 6, not level 1
The instinct is to reach for level 1 for speed. On a read-heavy cache that is backwards, and this was the measurement that changed how I think about it.
Higher levels produce less data to inflate, so decoding is faster:
| zlib level | decode time |
|---|---|
| 1 | ~71 µs |
| 6 | ~37 µs |
Level 1 is worse on ratio and worse on the hot path, which is an unusual thing for a tuning knob to manage. We use 6 and never go below 3.
Why it got faster rather than slower
Three reasons, in increasing order of how much they mattered.
Decode costs less than the network. Shrinking a 44 KB value to roughly 3 KB saves about 338 µs on the wire at 1 Gbps, against about 37 µs of decode. You are trading an expensive resource for a cheap one.
Redis does less work. Compression runs in PHP, on app servers that scale horizontally, while Redis's single thread just moves fewer bytes in writeToClient. The work moved to the tier where adding capacity is a config change.
And the evictions stopped, which is the one that actually paid. With the keyspace at a ninth of its size the memory pressure disappeared, the hit rate rose, and every recovered hit is a database query that never happens. The CPU arithmetic above is a rounding error next to that.
Rolling it out
Compression is controlled by a percentage dial, CACHE_CODEC_WRITE_PCT, and the order of the steps is the only thing protecting you.
Preflight, read-only. A console script samples real values with SCAN and GET, checks for magic-byte collisions, and reports the ratio and CPU cost on your actual data rather than on a benchmark. Proceed only on PREFLIGHT PASSED.
Readers only, WRITE_PCT=0. encode() returns byte-for-byte what Yii wrote before, so this release changes nothing observable. Deploy everywhere and bake for 24 hours. Every host must be on this release before the next step, because an old host cannot read a compressed value, and that is the one failure mode here that looks like data loss.
Ramp writes at 1%, 10%, 50%, 100%, watching the codec stats and Redis used_memory between each.
Rollback is setting the dial back to 0. Compressed values stay readable and age out naturally, so there is no un-migration to write and no window where the system is half converted in a way that matters.
What I would carry to the next one
Four things generalised past Redis and past PHP.
Put the transformation where every reader gets it, and ship readers before writers. That ordering is not a nicety; it is the difference between a rollout and an incident.
Make formats self-describing. A magic byte and a version byte cost four bytes and buy you every future migration for free.
Measure on real production values before choosing levels or thresholds, because the level 6 result above is the opposite of the obvious answer and a synthetic benchmark would have agreed with the obvious answer.
And on a memory-bound cache, the hit-rate gain dwarfs the CPU cost. If you are weighing microseconds of decode against evictions, you are weighing the wrong two things.
The same before-and-after discipline applies on the front end, where the levers differ and the method does not: Next.js performance.