Core system concepts · Concept lesson
Caching
Use caches to reduce repeated work and latency while designing freshness, invalidation, stampede control, and failure behavior.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Compare cache-aside, read-through, and write-through patterns.
- Estimate hit ratio and recognize cache stampedes and key-cardinality risk.
- Define freshness, invalidation, and cache-outage behavior.
How caching works
A cache stores a reusable result closer to the caller or faster than its source. On a hit, the request avoids some origin work; on a miss, the system reads the source and may populate the cache. Cache-aside makes the application perform this sequence explicitly. Read-through hides retrieval behind a cache layer, while write-through updates the cache as part of a write path. Every cache introduces a freshness contract: data can expire by time, be invalidated after changes, or be served stale under a defined policy. The cache key must include every input that changes the result, including tenant or authorization scope where relevant. An incomplete key can leak data between callers; an overly detailed key creates unbounded cardinality. A cache is usually derived state, not the authority. Design for misses and cache loss because entries can evict, expire, or disappear. The cache should improve a measured bottleneck without becoming a hidden correctness dependency.
Requests a value under a defined access scope.
Returns a fresh matching entry or reports a miss.
Provides the value on a cache miss.
Defines TTL, invalidation, and stale behavior.
- Caller → Cache: lookup by complete key
- Cache → Caller: hit
- Cache → Authoritative source: miss
- Authoritative source → Cache: populate derived entry
- Freshness policy → Cache: expiry and invalidation rules
Worked example: read reduction
Assume an endpoint receives 1,000 reads per second. Without a cache, each request triggers one database lookup. If the measured cache hit ratio is 90%, expected origin lookups fall to 1,000 × (1 − 0.90) = 100 per second, before refreshes and retries. If a cached value has a TTL of 60 seconds and changes every 10 minutes on average, many reads may reuse it, but a user can observe stale data for up to the TTL unless invalidation or version checks shorten that window. Suppose the object is 4 KiB and there are 50,000 active keys: raw value payload is about 200,000 KiB, roughly 195 MiB, before key names, metadata, allocator overhead, and replicas. A single popular key could still receive hundreds of requests per second after expiry. Use request coalescing or a bounded refresh mechanism to prevent every caller from loading the same miss. Measure actual hit ratio, freshness, memory use, and origin load together.
Caching patterns
Cache-aside is easy to introduce around a read path, but the application must handle expiration, invalidation, and concurrent misses. Read-through centralizes loading behavior; write-through can keep cache and source aligned for successful writes but couples write latency to cache health. Write-behind acknowledges before durable source updates and therefore needs a carefully specified loss and replay model; it is not a drop-in optimization for important state. A content-addressed immutable cache can use long TTLs because a new version gets a new key. Local in-process caches reduce network cost but differ between instances; shared caches offer wider reuse but add a network dependency. CDN caches suit public or explicitly cacheable content. Choose the pattern based on mutability, source-of-truth semantics, and failure tolerance. A cache may also be unnecessary if a database index or query optimization solves the actual cost more simply.
Failure and recovery
Cache outages convert hits into origin traffic, which can overload the very service the cache protected. Expiration can produce a stampede, while broad invalidation can cause a simultaneous cold start. Use bounded concurrency, request coalescing, jittered expiration, stale-while-revalidate where correctness allows, and origin admission controls. These mechanisms reduce pressure but do not make a cache authoritative. Invalidation can fail after a database commit, leaving an old entry; a short TTL limits but does not eliminate the interval. Versioned keys, transactional outbox-driven invalidation, or read-through validation can improve behavior depending on the requirement. For user-specific data, scope keys safely and never rely on a shared cache entry without authorization context. Monitor hit ratio, eviction, memory, origin miss rate, and refresh failures. Recovery should degrade predictably: bypass or disable caching with controlled load, rather than allowing every request to flood the origin.
When not to cache
Do not cache data whose freshness requirement is stricter than the invalidation mechanism can provide. Avoid caching highly variable, rarely repeated queries if key storage and lookup cost exceed recomputation. Do not cache secrets or personal data without considering access scope, retention, encryption, and deletion requirements. A low hit ratio can add latency and another failure mode with little benefit. Caching a rapidly changing counter can create confusing behavior unless the display explicitly tolerates stale values. A cache is not a durable queue or database; entries may vanish at any time. Avoid layering several opaque caches without a way to identify which layer served an old result. If correctness depends on invalidating every copy at exactly the right time, reconsider whether the data belongs in a cache or needs a stronger source-backed read.
Senior followups
Ask what exactly is cached: raw records, computed views, authorization decisions, or rendered content? Which inputs define the key, and can a caller influence key count? What is the maximum stale interval, and how is it enforced during invalidation failure? Does a deployment change representation shape and require namespaced keys? How will the system behave if the cache is cold or unavailable at peak traffic? Can a popular key or synchronized TTL cause a hot spot? How much memory is needed after replication and overhead, and which eviction policy can remove useful data? Does a stale value create a safety, privacy, or financial risk? Senior review requires an explicit origin capacity plan for cache failure and a strategy for warming or gradually rebuilding entries. Hit ratio alone is not an objective if freshness and tail latency worsen.
Operational practice
Record cache hits, misses, load duration, eviction, and source errors with bounded key classes rather than raw keys. Observe freshness age and invalidation delay for important data. Test cache loss by disabling it in a controlled environment while monitoring origin saturation. Add a circuit breaker or bypass mode only with an origin load plan; uncontrolled bypass can worsen an incident. Use jitter so many keys do not expire at the same instant, and coalesce concurrent misses for popular values. Version key namespaces when serialization changes. Provide a way to purge narrowly and audit who can do it, since broad flushes can trigger stampedes. When investigating stale data, identify each cache layer and compare stored version to authoritative state. Operational documentation should say which features may degrade, what stale content is acceptable, and how to restore a healthy hit ratio gradually.
Terms in plain language
- Cache hit
- A request finds a usable representation in the cache and avoids fetching it from the origin.
- TTL
- Time to live: a maximum duration after which a cached entry expires or is no longer considered fresh.
- Cache stampede
- A burst of callers simultaneously recomputing or fetching the same missing or expired value.
- Invalidation
- A mechanism that marks or removes cached data so subsequent reads obtain a suitably current value.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Primary standard defining HTTP cache behavior and freshness.
Primary vendor documentation describing cache-aside reads and invalidation.