Compress Less, Move Faster: Optimizing Redis and Valkey Payloads in Docker Microservices
Vikram Sengupta
Engineering Team
Index(6 sections)
At 02:17 UTC, a 12 GiB cache container reported 8.8 GiB of logical Redis memory and 11.4 GiB of resident memory. A replica reconnect pushed replication traffic beyond 1.6 Gb/s. Five minutes later, the container crossed its cgroup limit and was killed before the configured eviction policy could stabilize it.
Compressing every JSON value with gzip appeared to fix the memory problem. It cut used_memory by 54%, but application CPU rose from 58% to 91%. Event-loop lag at p99 increased from 14 ms to 63 ms, and cache operation p99 moved from 11 ms to 38 ms. Cache timeouts were interpreted as misses, producing a database stampede and measurable row-lock contention.
The cache had become smaller and the system had become less reliable.
When Cache Compression Becomes a Systems Trade-Off
Compression must be evaluated across the entire request path: serialization, codec execution, Docker networking, cache allocation, replication, persistence, and fallback database load.
The workload that drove this design had:
- Four application replicas, each limited to two vCPUs.
- 256 concurrent requests per replica.
- An 80/20 GET-to-SET mix and a 92% cache hit rate.
- Serialized payloads ranging from 300 bytes to 128 KiB.
- A p50 payload of 780 bytes, p75 of 3.8 KiB, and p95 of 31 KiB.
- Fifteen-minute TTLs with substantial object reuse.
- A Valkey primary and replica connected through a Docker bridge network.
The resulting data path looked like this:
Our acceptance criteria were explicit:
- No more than a 10% cache-operation p99 regression.
- Application CPU below 70% with negligible cgroup throttling.
- At least 35% dataset-memory reduction for compressed classes.
- At least 25% network-byte reduction.
- No material change in hit rate, decode failures, or database fallback volume.
A constrained baseline is more useful than an unconstrained laptop test:
services:
valkey:
image: valkey/valkey:8.0.2-alpine
command: ["valkey-server", "/etc/valkey/valkey.conf"]
cpus: "4.0"
mem_limit: 12g
ulimits:
nofile:
soft: 65535
hard: 65535
volumes:
- ./valkey.conf:/etc/valkey/valkey.conf:ro
healthcheck:
test: ["CMD", "valkey-cli", "ping"]
interval: 2s
timeout: 1s
retries: 20
networks: [cachebench]
networks:
cachebench:
name: cachebenchdocker compose up -d
docker run --rm --network cachebench \
redislabs/memtier_benchmark:2.1.2 \
--server valkey \
--protocol redis \
--threads 4 \
--clients 64 \
--ratio 1:4 \
--pipeline 1 \
--key-pattern R:R \
--key-maximum 250000 \
--data-size 4096 \
--test-time 300 \
--run-count 3 \
--print-percentiles 50,95,99,99.9This memtier_benchmark run establishes saturation and transport cost. It does not provide a truthful compression benchmark because fixed synthetic values rarely match production entropy.
Designing an Adaptive Compression Envelope
Small values should usually remain uncompressed. Key metadata, allocator bins, and the envelope itself can exceed any savings. Already-compressed images, encrypted fields, and high-entropy identifiers may also become larger after compression.
On an 8 KiB production-shaped JSON corpus, the codec trade-off looked like this:
| Codec profile | Stored/original ratio | Encode p50 | Decode p50 | Operational fit |
|---|---|---|---|---|
| LZ4 fast | 0.53 | 8 µs | 4 µs | CPU-constrained services |
| Zstandard level 1 | 0.36 | 24 µs | 9 µs | Balanced default |
| gzip level 1 | 0.41 | 67 µs | 22 µs | Compatibility-driven systems |
| Brotli quality 4 | 0.31 | 214 µs | 39 µs | Cold, rarely decoded blobs |
These numbers are hardware- and corpus-specific. Zstandard level 1 won because Brotli’s additional density did not compensate for its tail-latency cost, while LZ4 left too much memory and bandwidth on the table.
A cache value also needs a format contract. The following TypeScript implementation uses a 16-byte envelope containing magic bytes, envelope version, codec, schema version, original size, and CRC32C. It limits codec concurrency, rejects oversized values, stores raw data when compression saves less than 15%, and fails open to raw storage when the encoder is saturated.
import { compress, decompress } from "@mongodb-js/zstd";
import { calculate as crc32c } from "fast-crc32c";
import pLimit from "p-limit";
const MAGIC = Buffer.from("KSC1", "ascii");
const HEADER_BYTES = 16;
enum Codec {
Raw = 0,
Zstd = 1,
}
export interface EnvelopeOptions {
thresholdBytes: number;
minSavingsRatio: number;
maxValueBytes: number;
codecConcurrency: number;
maxQueued: number;
zstdLevel: number;
onEncodeFailure?: (error: unknown) => void;
}
export class EnvelopeError extends Error {}
export class CodecOverloadedError extends Error {}
export class AdaptiveEnvelope {
private readonly gate: ReturnType<typeof pLimit>;
constructor(private readonly options: EnvelopeOptions) {
if (
options.thresholdBytes < 0 ||
options.maxValueBytes > 0xffffffff ||
options.thresholdBytes > options.maxValueBytes ||
options.minSavingsRatio < 0 ||
options.minSavingsRatio >= 1 ||
options.codecConcurrency < 1 ||
options.maxQueued < 0
) {
throw new RangeError("Invalid adaptive-envelope configuration");
}
this.gate = pLimit(options.codecConcurrency);
}
isEnvelope(value: Buffer): boolean {
return value.length >= MAGIC.length &&
value.subarray(0, MAGIC.length).equals(MAGIC);
}
async encode(plain: Buffer, schemaVersion: number): Promise<Buffer> {
this.validateInput(plain, schemaVersion);
if (plain.length < this.options.thresholdBytes || this.overloaded()) {
return this.pack(Codec.Raw, schemaVersion, plain, plain);
}
try {
const compressed = Buffer.from(
await this.gate(() => compress(plain, this.options.zstdLevel)),
);
const compressedBytes = compressed.length + HEADER_BYTES;
const rawBytes = plain.length + HEADER_BYTES;
if (
compressedBytes >
rawBytes * (1 - this.options.minSavingsRatio)
) {
return this.pack(Codec.Raw, schemaVersion, plain, plain);
}
return this.pack(Codec.Zstd, schemaVersion, plain, compressed);
} catch (error) {
this.options.onEncodeFailure?.(error);
return this.pack(Codec.Raw, schemaVersion, plain, plain);
}
}
async decode(stored: Buffer, expectedSchema?: number): Promise<Buffer> {
if (
stored.length < HEADER_BYTES ||
stored.length > this.options.maxValueBytes + HEADER_BYTES ||
!this.isEnvelope(stored)
) {
throw new EnvelopeError("Invalid cache envelope");
}
const envelopeVersion = stored.readUInt8(4);
const codec = stored.readUInt8(5);
const schemaVersion = stored.readUInt16BE(6);
const originalBytes = stored.readUInt32BE(8);
const expectedCrc = stored.readUInt32BE(12);
const payload = stored.subarray(HEADER_BYTES);
if (envelopeVersion !== 1) {
throw new EnvelopeError(`Unsupported envelope version: ${envelopeVersion}`);
}
if (expectedSchema !== undefined && schemaVersion !== expectedSchema) {
throw new EnvelopeError(`Unexpected schema version: ${schemaVersion}`);
}
if (originalBytes > this.options.maxValueBytes) {
throw new EnvelopeError("Decoded value exceeds configured limit");
}
let plain: Buffer;
if (codec === Codec.Raw) {
plain = payload;
} else if (codec === Codec.Zstd) {
if (this.overloaded()) {
throw new CodecOverloadedError("Decoder queue is saturated");
}
plain = Buffer.from(await this.gate(() => decompress(payload)));
} else {
throw new EnvelopeError(`Unknown codec: ${codec}`);
}
if (
plain.length !== originalBytes ||
(crc32c(plain) >>> 0) !== expectedCrc
) {
throw new EnvelopeError("Length or CRC validation failed");
}
return plain;
}
private overloaded(): boolean {
return this.gate.activeCount >= this.options.codecConcurrency &&
this.gate.pendingCount >= this.options.maxQueued;
}
private validateInput(value: Buffer, schemaVersion: number): void {
if (value.length > this.options.maxValueBytes) {
throw new RangeError("Cache value exceeds configured limit");
}
if (!Number.isInteger(schemaVersion) || schemaVersion < 0 || schemaVersion > 0xffff) {
throw new RangeError("Schema version must fit in uint16");
}
}
private pack(
codec: Codec,
schemaVersion: number,
plain: Buffer,
payload: Buffer,
): Buffer {
const output = Buffer.allocUnsafe(HEADER_BYTES + payload.length);
MAGIC.copy(output, 0);
output.writeUInt8(1, 4);
output.writeUInt8(codec, 5);
output.writeUInt16BE(schemaVersion, 6);
output.writeUInt32BE(plain.length, 8);
output.writeUInt32BE(crc32c(plain) >>> 0, 12);
payload.copy(output, HEADER_BYTES);
return output;
}
}CRC32C detects corruption and format bugs; it does not provide authenticity. Cache ACLs and TLS remain mandatory. For untrusted multi-tenant payloads, use a Zstandard binding with a hard decoder memory limit or isolate decoding in memory-limited workers.
Benchmarking Inside Docker Without Lying to Yourself
Docker CPU quotas introduce periodic throttling. Average CPU can show 62% while requests queue during exhausted quota periods. Track container_cpu_cfs_throttled_seconds_total, not only utilization.
A defensible benchmark also controls:
- Image digests, CPU quotas, memory limits, and host placement.
- Docker bridge versus host networking.
- Dataset entropy and payload-size distribution.
- Codec warm-up and native-library initialization.
- TTL expiration churn and realistic hit rates.
- Original, compressed, and simultaneously allocated buffers.
- Serialization, codec, and Redis command latency separately.
Closed-loop load generators hide stalls because they stop issuing work while previous requests are blocked. We used an open-loop, constant-arrival driver with HDR histograms. When all workers were busy, the request was recorded as an SLO failure rather than silently delaying the next arrival.
The cache client also needs backpressure. Node Redis clients multiplex commands over a socket, but that does not make an unbounded command queue safe. The following repository limits in-flight operations, retries only idempotent commands within a latency budget, uses immutable revision keys, and records each stage independently.
import { createHash } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";
import { metrics } from "@opentelemetry/api";
import Redis from "ioredis";
import pLimit from "p-limit";
import { AdaptiveEnvelope } from "./adaptive-envelope.js";
const meter = metrics.getMeter("cache-value-path");
const stageLatency = meter.createHistogram("cache_stage_duration_seconds", {
unit: "s",
});
const payloadBytes = meter.createCounter("cache_payload_bytes", {
unit: "By",
});
const decodeFailures = meter.createCounter("cache_decode_failures");
const transientCodes = new Set([
"ECONNRESET",
"ETIMEDOUT",
"EPIPE",
"NR_CLOSED",
]);
function isTransient(error: unknown): boolean {
const candidate = error as { code?: string; message?: string };
return transientCodes.has(candidate.code ?? "") ||
/READONLY|TRYAGAIN|CLUSTERDOWN/.test(candidate.message ?? "");
}
async function retryIdempotent<T>(
operation: () => Promise<T>,
budgetMs = 40,
): Promise<T> {
const deadline = performance.now() + budgetMs;
let backoffMs = 4;
for (let attempt = 0; ; attempt++) {
try {
return await operation();
} catch (error) {
if (attempt >= 2 || !isTransient(error)) {
throw error;
}
const delayMs = Math.random() * backoffMs;
if (performance.now() + delayMs >= deadline) {
throw error;
}
await sleep(delayMs);
backoffMs = Math.min(backoffMs * 2, 20);
}
}
}
async function timed<T>(
stage: string,
operation: () => Promise<T>,
): Promise<T> {
const started = performance.now();
try {
return await operation();
} finally {
stageLatency.record((performance.now() - started) / 1000, { stage });
}
}
export class RevisionCache {
private readonly commands = pLimit(512);
constructor(
private readonly redis: Redis,
private readonly envelope: AdaptiveEnvelope,
) {}
async putJson<T>(
namespace: string,
entityId: string,
revision: string,
value: T,
ttlSeconds: number,
envelopeWrites: boolean,
schemaVersion: number,
): Promise<string> {
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
throw new RangeError("TTL must be a positive integer");
}
const tag = createHash("sha256")
.update(entityId)
.digest("hex")
.slice(0, 16);
const key = `${namespace}:{${tag}}:rev:${revision}`;
const serializationStarted = performance.now();
const json = JSON.stringify(value);
if (json === undefined) {
throw new TypeError("Value is not JSON serializable");
}
const plain = Buffer.from(json, "utf8");
stageLatency.record(
(performance.now() - serializationStarted) / 1000,
{ stage: "serialize" },
);
const stored = envelopeWrites
? await timed("encode", () => this.envelope.encode(plain, schemaVersion))
: plain;
payloadBytes.add(plain.length, { representation: "original" });
payloadBytes.add(stored.length, { representation: "stored" });
await timed("redis_set", () =>
this.call(() =>
this.redis.set(key, stored, "EX", ttlSeconds, "NX")
)
);
// A null NX response means the immutable revision already exists.
return key;
}
async getJson<T>(
key: string,
schemaVersion: number,
validate: (input: unknown) => T,
): Promise<T | null> {
const stored = await timed("redis_get", () =>
this.call(() => this.redis.getBuffer(key))
);
if (stored === null) {
return null;
}
let plain = stored;
if (this.envelope.isEnvelope(stored)) {
try {
plain = await timed("decode", () =>
this.envelope.decode(stored, schemaVersion)
);
} catch (error) {
decodeFailures.add(1);
throw error;
}
}
return validate(JSON.parse(plain.toString("utf8")));
}
private async call<T>(operation: () => Promise<T>): Promise<T> {
if (this.commands.pendingCount >= 1024) {
throw new Error("Cache command queue is saturated");
}
return this.commands(() => retryIdempotent(operation));
}
}The NX retry is safe because revision keys are immutable. Applying the same retry policy to a mutable cache key can allow a delayed request to overwrite a newer value. Blocking commands and Pub/Sub also require dedicated connections; adding dozens of general-purpose sockets only increases server buffers and failover load.
Tuning Valkey and Redis for Compressed Objects
A 12 GiB container should not receive a 12 GiB maxmemory setting. Replication buffers, allocator fragmentation, client output buffers, persistence forks, and copy-on-write pages exist outside the evictable dataset.
A reasonable cache-oriented starting point was:
maxmemory 8gb
maxmemory-policy allkeys-lfu
maxmemory-samples 10
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-server-del yes
activedefrag yes
active-defrag-ignore-bytes 256mb
active-defrag-threshold-lower 10
active-defrag-cycle-min 5
active-defrag-cycle-max 25
client-output-buffer-limit normal 128mb 32mb 15
client-output-buffer-limit replica 512mb 128mb 60
client-output-buffer-limit pubsub 64mb 16mb 30
repl-backlog-size 256mb
# Appropriate only when the instance is a disposable cache.
appendonly no
save ""Use allkeys-lfu only when every key is disposable. volatile-lfu can still reach OOM if non-expiring keys consume the instance. Authoritative state belongs in a separate deployment with persistence and a deliberate noeviction policy.
Inspect allocator reality rather than summing serialized payload sizes:
redis-cli -u "$CACHE_URL" INFO memory
redis-cli -u "$CACHE_URL" MEMORY STATS
redis-cli -u "$CACHE_URL" MEMORY USAGE 'order:{a81f}:rev:901' SAMPLES 0
redis-cli -u "$CACHE_URL" INFO replication
redis-cli -u "$CACHE_URL" INFO persistenceCompression savings do not map linearly to RSS. A value must cross a jemalloc size-class boundary before its allocation shrinks. Keys, dictionaries, expirations, and object headers remain unchanged. For tiny values, these fixed costs dominate.
Compressed values do reduce primary-to-replica traffic and AOF command size because replicas receive the same opaque bytes. RDB or AOF rewrite compression will provide little additional gain on an already-compressed blob. During BGSAVE, write-heavy workloads can still duplicate dirty pages through copy-on-write, so container headroom remains necessary.
Deep pipelines deserve similar caution. Returning 512 compressed 32 KiB objects may be manageable; returning their uncompressed equivalents can create a 16 MiB response burst per client. Bound pipeline depth based on byte volume rather than command count.
Production Results and the Decision Framework
We ran three 30-minute samples after a ten-minute warm-up on an AMD EPYC host using Docker Engine 27, Node.js 22, Valkey 8.0.2, four two-vCPU application containers, and one four-vCPU Valkey container. Each test loaded 250,000 values from a production-shaped JSON corpus.
P99 was measured at a fixed per-size arrival rate. “SLO ceiling” is the highest throughput that maintained p99 below 20 ms with fewer than 0.1% failures.
| Payload | Mode | Median stored bytes | Valkey memory | App CPU | Network | End-to-end p99 | SLO ceiling |
|---|---|---|---|---|---|---|---|
| 512 B | Raw | 512 B | 181 MiB | 3.0 cores | 56 MiB/s | 3.2 ms | 128k ops/s |
| 512 B | Adaptive | 528 B | 185 MiB | 3.1 cores | 58 MiB/s | 3.3 ms | 126k ops/s |
| 4 KiB | Raw | 4,096 B | 1.12 GiB | 3.3 cores | 247 MiB/s | 5.8 ms | 96k ops/s |
| 4 KiB | Zstd adaptive | 1,470 B | 430 MiB | 4.7 cores | 91 MiB/s | 6.4 ms | 91k ops/s |
| 32 KiB | Raw | 32,768 B | 7.82 GiB | 3.5 cores | 620 MiB/s | 17.8 ms | 29k ops/s |
| 32 KiB | Zstd adaptive | 7,860 B | 2.04 GiB | 5.9 cores | 159 MiB/s | 13.9 ms | 37k ops/s |
Three conclusions survived repeated runs:
- Below 2 KiB, compression was counterproductive. Even the raw envelope added measurable memory and network overhead.
- Around 4 KiB, compression traded CPU and throughput for memory. This was acceptable only when memory pressure or eviction misses were the dominant cost.
- Above 8–16 KiB, network savings improved p99. Docker bridge copies and socket transfer had become more expensive than Zstandard decoding.
The actual break-even relationship is:
encode cost + (reads × decode cost)
<
(reads × network savings)
+ replication savings
+ avoided eviction and database-miss costRead amplification matters. Encoding occurs once per write, while decoding occurs on every hit. Conversely, fitting more hot keys in memory may prevent database queries whose lock and I/O costs dwarf codec time.
Rollout selection should be deterministic so the same keys remain in the canary population:
import { createHash } from "node:crypto";
export interface CompressionRollout {
enabled: boolean;
percentage: number;
}
export function shouldWriteEnvelope(
cacheKey: string,
rollout: CompressionRollout,
): boolean {
if (!rollout.enabled) return false;
if (rollout.percentage < 0 || rollout.percentage > 100) {
throw new RangeError("Rollout percentage must be between 0 and 100");
}
const bucket = createHash("sha256")
.update(cacheKey)
.digest()
.readUInt32BE(0) % 10_000;
return bucket < rollout.percentage * 100;
}Readers must support both formats before the first compressed writer is enabled. Useful canary queries include:
# Fraction of bytes removed
1 -
sum(rate(cache_payload_bytes_total{representation="stored"}[5m]))
/
sum(rate(cache_payload_bytes_total{representation="original"}[5m]))
# Decode failures per GET
sum(rate(cache_decode_failures_total[5m]))
/
clamp_min(
sum(rate(cache_stage_duration_seconds_count{stage="redis_get"}[5m])),
1
)
# Codec and cache-path p99
histogram_quantile(
0.99,
sum by (le, stage) (
rate(cache_stage_duration_seconds_bucket[5m])
)
)
# Application CPU relative to allocated cores
sum(rate(container_cpu_usage_seconds_total{service="app"}[5m]))
/
sum(container_cpu_limit_cores{service="app"})We halted rollout if cache p99 increased by more than 10% for ten minutes, CPU throttling exceeded 2%, decode failures exceeded one per million reads, or database fallback volume increased by one percentage point.
Rolling writers back does not remove existing compressed entries. Keep dual-format readers deployed for at least the maximum TTL, replica recovery window, and persistence retention period. Decode failures should not immediately become unrestricted database misses; coalesce concurrent loads per key and rate-limit fallback traffic to prevent lock storms.
Production Checklist
- Measure payload percentiles and entropy before choosing a codec.
- Start with a 2 KiB threshold and 15% minimum savings, then benchmark your corpus.
- Prefer Zstandard level 1 for balanced cache traffic; use LZ4 when CPU is the hard constraint.
- Never run synchronous compression on a Node.js request event loop.
- Bound codec concurrency, command concurrency, queue length, and maximum decoded size.
- Use immutable revision keys or compare-and-set semantics before retrying writes.
- Keep blocking commands and Pub/Sub on dedicated connections.
- Size
maxmemorybelow the container limit; reserve space for fragmentation, replication, and fork-time copy-on-write. - Compare
MEMORY USAGE,used_memory_dataset, RSS, andmem_not_counted_for_evict. - Benchmark through the same Docker network topology used in production.
- Use open-loop load generation and report p50, p95, p99, throttling, and rejected work.
- Deploy dual-format readers before canary writers.
- Preserve decoder support through the complete TTL and recovery window.
- Treat codec overload as controlled backpressure, not an invitation to create unlimited database misses.
- Ship a decoder CLI for incident response; opaque cache bytes without tooling are an operational liability.
- Roll out only when memory, bandwidth, or avoided eviction cost exceeds the added CPU and p99 latency.
Compression earns its place when it removes a measured bottleneck from the complete system. If it merely moves pressure from Valkey memory to application CPU—or from network transfer to database fallback—the correct threshold is higher, and sometimes the correct codec is Raw.
Share This Article
More Engineering Architecture Playbooks
Deep dives and blueprints from our senior engineering team
Alpine Linux Security Advisory: OpenSSH-server password authentication bypass
Organizations should treat the advisory as an identity-boundary incident until package inventory, SSH configuration, network exposure, and access records establish otherwise. The paper will translate verified Alpine guidance into a production-safe workflow covering exposure analysis, containment, upgrades, validation, threat hunting, and recovery.
vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters
This whitepaper explains how vLLM uses PagedAttention and block-based KV cache management to decouple request growth from contiguous GPU-memory allocation. It translates those mechanics into a production architecture for NVIDIA H100 clusters, covering scheduling, topology, capacity governance, observability, resilience, and safe multi-tenant operations without relying on unsupported benchmark claims.
Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability
CVE-2024-27834 should be handled as a trust-boundary issue rather than a routine endpoint update because improper authentication can undermine assumptions about who or what is permitted to access protected resources. The paper will translate vendor-confirmed facts into an operational response spanning asset discovery, risk-based containment, controlled patch deployment, post-update verification, and executive governance without speculating beyond published evidence.