Lesson 6 of 9 · 24m
Serialization, Negative Caching, and Hot Keys
Choose payload formats deliberately, cache absence safely, and recognize hot-key behavior before it becomes an outage.
Caching an object is easy. Caching the right representation, at the right granularity, with safe absence semantics, is where the scars are. I have seen systems cache enormous ORM objects to save one query and then spend ten times the cost serializing, deserializing, and evicting them. A cache is not a trash compactor for bad data access.
Cache the representation you actually need
Store a compact DTO or rendered fragment, not a database row with every relationship attached:
{
"id": 1042,
"slug": "pro-plan",
"name": "Pro",
"price_cents": 4900,
"currency": "USD",
"version": 37
}If callers need only four fields, do not cache sixty. Smaller payloads reduce memory, network time, serialization cost, and accidental leakage of internal fields. Cache entries cross trust boundaries too; if the object includes internal cost or administrative metadata, every consumer receives it.
Serialization format is an operational choice
JSON is debuggable and interoperable. MessagePack or protobuf can be smaller and faster, but require stronger schema discipline. Language-native pickling is convenient and dangerous: format coupling, version fragility, and in some ecosystems unsafe deserialization. Prefer boring formats for shared infrastructure.
payload = json.dumps(dto, separators=(",", ":"), sort_keys=True).encode()
redis.set(key, payload, ex=300)Compress only when payload size justifies CPU cost. Tiny objects compressed individually usually waste time. Large rendered pages or reports may benefit.
Negative caching prevents repeat misses — carefully
If the database says 'no such product,' repeated requests can still hammer it. Store a short-lived negative marker:
if product is None:
redis.set(key, b"__missing__", ex=30)
return NoneNegative entries must use shorter TTLs than positive entries because creation is common: a user signs up, a product is imported, a DNS record appears. Also distinguish 'missing' from 'backend error.' Do not cache errors for minutes unless the business explicitly accepts that behavior.
Hot keys concentrate risk
A celebrity profile, flash-sale product, leaderboard, or homepage fragment can receive a disproportionate share of reads. Redis is fast, but one key is normally served by one logical path in your client and infrastructure. Hot keys also expire all at once.
Warning signs:
one key dominates command stats
CPU spikes on a single shard or node
network egress concentrated in one object
expiry causes synchronized database queriesReplication, local in-process caching, key splitting, or short-lived per-worker copies can help. Each adds consistency complexity. Measure before distributing complexity.
Local caches multiply memory and staleness
An in-process LRU can absorb enormous read volume:
cache = TTLCache(maxsize=10_000, ttl=5)But now you have one cache per process, each with independent freshness. That is fine for immutable configuration or tiny tolerance windows, poor for authorization state. Local caching is a consistency decision, not merely a performance trick.
Field notes
- Do not cache authorization failure as generic absence; attackers can exploit confusing negative states.
- Large values distort eviction behavior and network latency. Track size distribution, not only key count.
- Keep serialization versions explicit. A payload version field beats guessing by shape.
- Hot keys are often better solved by replication or denormalized read models than by 'more Redis.'
- A missing object and an empty collection are different facts. Do not collapse them into one marker.
Was this lesson helpful?