Caching Strategies
Purpose
A cache can reduce the arrival rate seen by an origin in L = λ × W: a hit consumes no origin
connection, planner or I/O. Batching, admission control and eliminating work can also reduce
origin demand, so caching is one option rather than a unique law. A stale, unbounded cache can
show excellent hit rate; correctness, memory and origin protection must be measured beside it.
Workflow
Inspect the target's Maven/Gradle release/toolchain, resolved Caffeine/Spring Data/Jackson
versions, runtime image and cache configuration before choosing APIs. No universal Java baseline
is declared here; the configuration reference states its example baseline. Preserve project
versions and do not enable preview features or upgrade dependencies to fit an example. If workload,
freshness requirements or measurements are absent, identify the gap and offer a conditional
decision and measurement plan rather than inventing a hit rate or safe TTL.
- Measure source cost and capacity (latency distribution, CPU/I/O and rate) before deciding.
Even a sub-millisecond lookup may matter at very high volume; latency alone is not the case.
- Measure the access distribution and estimate
h for the intended maximumSize.
- Model saved work and latency, not hit rate alone. Estimate origin work avoided by hit
distribution and compare
h·T_hit + (1-h)·T_miss (including queueing/load cost) with the
uncached distribution. Tail latency cannot be derived from averages.
- Bound it—by count or a measured weight proxy. Account for keys, values, node metadata,
allocator/GC headroom and concurrent load buffers; a weigher's logical bytes are not measured
heap retention. Validate with heap/allocation evidence under representative occupancy.
- Set a TTL from the business tolerance for stale data, and add jitter if entries are
created in bulk. Keep the longest jittered lifetime inside that tolerance, accounting for
source lag and load time. Access-based expiry does not bound the age of frequently read data.
- Define the invalidation strategy and write an automated test for it — propagation is
the part that silently stops working.
- Instrument outcomes: request-weighted and byte-weighted hit/miss, origin rate and load
latency/failures, eviction/admission, retained memory, stale-age/version and invalidation lag.
Rules
- For a simple cache-aside path,
E[T] ≈ h·T_hit + (1-h)·T_miss; miss cost includes cache lookup,
origin queueing/load and fill. Increasing hit rate has linear average benefit only if those
distributions stay fixed; near saturation, queueing can make the system nonlinear. Hit-rate
gain per byte depends on the observed popularity/size distribution, not a universal logarithm.
- A broken cache has better metrics than a correct one. No limit, no TTL and no
invalidation gives the best possible hit rate. This is why hit rate never travels alone.
- Avoid putting managed/mutable JPA entities in an application cache—the cache may retain aliases,
lazy proxies and persistence-context assumptions. Cache immutable projections/value snapshots
with an explicit version. A provider's second-level cache is a separate coordinated mechanism,
not evidence that arbitrary entity references are safe.
- In Spring's default proxy mode,
@Cacheable self-invocation via this bypasses interception.
AspectJ mode or direct programmatic caching differs. Test the deployed mode; extracting a
collaborator is often clearer than self-injection.
- Never cache an operation with a side effect.
@Cacheable on something that creates
means that on a hit the thing is not created and the cache asserts that it was.
For idempotency that must survive eviction, restart and retries, use a durable record with an
atomic relationship to the effect; a unique key alone does not supply that relationship.
Delegate the operation contract to idempotency.
- Stampede has several scopes: jitter desynchronizes bulk expiry; singleflight/
LoadingCache
coalesces per key only within its process/cache instance unless backed by distributed
coordination; refreshAfterWrite serves an old value while a hot-key refresh runs; staged
warm-up avoids a
global cold cache. Probabilistic early expiration reduces the spike, it does not remove
it — and the correct form is P = exp(−(expiry − now) / (β · δ)), with β in the
denominator and δ representing measured recomputation duration. Validate the algorithm and
clock/units rather than copying the equation without its assumptions: require positive β and
δ, consistent time units, and treat already expired entries as misses rather than probabilities
greater than one.
FLUSHALL in a deploy pipeline is a stampede generator. If the service needs the cache to
serve its load, the cache is an availability component, not a performance one. For a
format change, version the key prefix, but stage and rate-limit warming: switching every
caller to an empty namespace is also a cold-cache event. Budget old/new namespaces together.
- Spring Data Redis defaults
RedisTemplate/RedisCache to JDK serialization in current
documentation; override it explicitly. Prefer a typed schema/serializer. In Spring Data Redis
4, Jackson 3 uses JacksonJsonRedisSerializer<T> or GenericJacksonJsonRedisSerializer;
Jackson-2-named serializers are deprecated, and the old generic serializer enabled default
typing by default. Do not solve lost type information by enabling payload-selected classes
(java-serialization-hardening).
- Redis pub/sub is fire-and-forget. An L1 TTL limits local retention, not end-to-end staleness:
expiry may refill from an already stale L2 or origin replica. Derive the age budget across
layers, propagate versions/remaining freshness, or reload from a sufficiently fresh source.
Publish only after a successful commit,
but recognize that an
AFTER_COMMIT listener can crash before publishing. Use an outbox/CDC or
version-checked reads where bounded reliable invalidation is required.
- Cache-aside has races: an old slow read can fill after a newer write invalidates, resurrecting
stale data. A version field alone does not reject the old fill. Define the check against the
authoritative version or invalidation watermark, including absent entries and deletes.
Write-through/CDC still need ordering against concurrent fills; use a tolerated stale window
only when the consistency requirement permits it.
- A key is an authorization boundary. Include tenant, locale, entitlement/principal dimensions
that affect the result; canonicalize them; never let one tenant reuse another's cached response.
Avoid secrets/PII in keys because keys appear in metrics, logs and admin tools.
- Negative caching protects against penetration only with a short bounded TTL and input/cardinality
controls. Caching every attacker-chosen miss is itself an unbounded-memory attack.
Deliverable
For a design/review, return the cache/no-cache decision, measured inputs and assumptions, key/value
contract, memory/freshness bounds, invalidation race handling and origin-outage policy. State the
targeted tests and acceptance bounds. For an incident, report evidence, competing hypotheses and
the next discriminating measurement; do not label an untested hypothesis a confirmed fix.
Primary sources
References
- Configuring a cache — Caffeine and Spring
configuration with bounds, weight, jitter and stats; the Redis settings that matter; and
the near-cache (L1+L2) rules. Read when implementing or reviewing a cache.
- Cache incident triage — the symptom-to-cause table and
the metric set that makes each cause visible. Read when a cache-related incident is in
progress.
1---2name: caching-strategies3description: Deciding whether to cache, then doing it safely: saved origin work and latency, bounded size or weight, TTL and jitter, stampede and its four distinct scopes, cache-aside versus refreshAfterWrite, immutable DTOs rather than JPA entities, invalidation across instances, Redis serialisation, and why hit rate alone is a misleading metric. Use when a cache is being added or reviewed, when @Cacheable is called from within the same bean, when a cache has no size limit or no TTL, when entries are preloaded in bulk with one TTL, when hit rate is the only metric on the dashboard, when Old Gen keeps growing, when FLUSHALL appears in a deploy pipeline, or when instances disagree about a value. Does not cover the pool the cache protects (connection-pool-sizing), the queueing arithmetic (littles-law-and-queueing), or GC tuning for the resulting heap (jvm-gc-tuning).4---56# Caching Strategies78## Purpose910A cache can reduce the arrival rate seen by an origin in `L = λ × W`: a hit consumes no origin11connection, planner or I/O. Batching, admission control and eliminating work can also reduce12origin demand, so caching is one option rather than a unique law. A stale, unbounded cache can13show excellent hit rate; correctness, memory and origin protection must be measured beside it.1415## Workflow1617Inspect the target's Maven/Gradle release/toolchain, resolved Caffeine/Spring Data/Jackson18versions, runtime image and cache configuration before choosing APIs. No universal Java baseline19is declared here; the configuration reference states its example baseline. Preserve project20versions and do not enable preview features or upgrade dependencies to fit an example. If workload,21freshness requirements or measurements are absent, identify the gap and offer a conditional22decision and measurement plan rather than inventing a hit rate or safe TTL.23241. **Measure source cost and capacity** (latency distribution, CPU/I/O and rate) before deciding.25 Even a sub-millisecond lookup may matter at very high volume; latency alone is not the case.262. **Measure the access distribution** and estimate `h` for the intended `maximumSize`.273. **Model saved work and latency, not hit rate alone.** Estimate origin work avoided by hit28 distribution and compare `h·T_hit + (1-h)·T_miss` (including queueing/load cost) with the29 uncached distribution. Tail latency cannot be derived from averages.304. **Bound it**—by count or a measured weight proxy. Account for keys, values, node metadata,31 allocator/GC headroom and concurrent load buffers; a weigher's logical bytes are not measured32 heap retention. Validate with heap/allocation evidence under representative occupancy.335. **Set a TTL from the business tolerance for stale data**, and add jitter if entries are34 created in bulk. Keep the longest jittered lifetime inside that tolerance, accounting for35 source lag and load time. Access-based expiry does not bound the age of frequently read data.366. **Define the invalidation strategy and write an automated test for it** — propagation is37 the part that silently stops working.387. **Instrument outcomes**: request-weighted and byte-weighted hit/miss, origin rate and load39 latency/failures, eviction/admission, retained memory, stale-age/version and invalidation lag.4041## Rules4243- For a simple cache-aside path, `E[T] ≈ h·T_hit + (1-h)·T_miss`; miss cost includes cache lookup,44 origin queueing/load and fill. Increasing hit rate has linear average benefit only if those45 distributions stay fixed; near saturation, queueing can make the system nonlinear. Hit-rate46 gain per byte depends on the observed popularity/size distribution, not a universal logarithm.47- **A broken cache has better metrics than a correct one.** No limit, no TTL and no48 invalidation gives the best possible hit rate. This is why hit rate never travels alone.49- Avoid putting managed/mutable JPA entities in an application cache—the cache may retain aliases,50 lazy proxies and persistence-context assumptions. Cache immutable projections/value snapshots51 with an explicit version. A provider's second-level cache is a separate coordinated mechanism,52 not evidence that arbitrary entity references are safe.53- In Spring's default proxy mode, `@Cacheable` self-invocation via `this` bypasses interception.54 AspectJ mode or direct programmatic caching differs. Test the deployed mode; extracting a55 collaborator is often clearer than self-injection.56- Never cache an operation with a side effect. `@Cacheable` on something that _creates_57 means that on a hit the thing is not created and the cache asserts that it was.58 For idempotency that must survive eviction, restart and retries, use a durable record with an59 atomic relationship to the effect; a unique key alone does not supply that relationship.60 Delegate the operation contract to `idempotency`.61- Stampede has several scopes: jitter desynchronizes bulk expiry; singleflight/`LoadingCache`62 coalesces per key only within its process/cache instance unless backed by distributed63 coordination; `refreshAfterWrite` serves an old value while a hot-key refresh runs; staged64 warm-up avoids a65 global cold cache. Probabilistic early expiration reduces the spike, it does not remove66 it — and the correct form is `P = exp(−(expiry − now) / (β · δ))`, with β in the67 denominator and `δ` representing measured recomputation duration. Validate the algorithm and68 clock/units rather than copying the equation without its assumptions: require positive β and69 δ, consistent time units, and treat already expired entries as misses rather than probabilities70 greater than one.71- `FLUSHALL` in a deploy pipeline is a stampede generator. If the service needs the cache to72 serve its load, the cache is an **availability** component, not a performance one. For a73 format change, version the key prefix, but stage and rate-limit warming: switching every74 caller to an empty namespace is also a cold-cache event. Budget old/new namespaces together.75- Spring Data Redis defaults `RedisTemplate`/`RedisCache` to JDK serialization in current76 documentation; override it explicitly. Prefer a typed schema/serializer. In Spring Data Redis77 4, Jackson 3 uses `JacksonJsonRedisSerializer<T>` or `GenericJacksonJsonRedisSerializer`;78 Jackson-2-named serializers are deprecated, and the old generic serializer enabled default79 typing by default. Do not solve lost type information by enabling payload-selected classes80 (java-serialization-hardening).81- Redis pub/sub is fire-and-forget. An L1 TTL limits local retention, not end-to-end staleness:82 expiry may refill from an already stale L2 or origin replica. Derive the age budget across83 layers, propagate versions/remaining freshness, or reload from a sufficiently fresh source.84 Publish only after a successful commit,85 but recognize that an `AFTER_COMMIT` listener can crash before publishing. Use an outbox/CDC or86 version-checked reads where bounded reliable invalidation is required.87- Cache-aside has races: an old slow read can fill after a newer write invalidates, resurrecting88 stale data. A version field alone does not reject the old fill. Define the check against the89 authoritative version or invalidation watermark, including absent entries and deletes.90 Write-through/CDC still need ordering against concurrent fills; use a tolerated stale window91 only when the consistency requirement permits it.92- A key is an authorization boundary. Include tenant, locale, entitlement/principal dimensions93 that affect the result; canonicalize them; never let one tenant reuse another's cached response.94 Avoid secrets/PII in keys because keys appear in metrics, logs and admin tools.95- Negative caching protects against penetration only with a short bounded TTL and input/cardinality96 controls. Caching every attacker-chosen miss is itself an unbounded-memory attack.9798## Deliverable99100For a design/review, return the cache/no-cache decision, measured inputs and assumptions, key/value101contract, memory/freshness bounds, invalidation race handling and origin-outage policy. State the102targeted tests and acceptance bounds. For an incident, report evidence, competing hypotheses and103the next discriminating measurement; do not label an untested hypothesis a confirmed fix.104105## Primary sources106107- [Spring Data Redis object mapping and serializers](https://docs.spring.io/spring-data/redis/reference/redis/template.html)108- [Spring Data Redis 4 migration guide](https://docs.spring.io/spring-data/redis/reference/upgrading.html)109- [Caffeine refresh semantics](https://github.com/ben-manes/caffeine/wiki/Refresh)110- [Caffeine 3.2.2 API](https://www.javadoc.io/static/com.github.ben-manes.caffeine/caffeine/3.2.2/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html)111- [Redis Pub/Sub delivery](https://redis.io/docs/latest/develop/pubsub/)112- [Redis key eviction](https://redis.io/docs/latest/develop/reference/eviction/)113114## References115116- [Configuring a cache](references/configuring-a-cache.md) — Caffeine and Spring117 configuration with bounds, weight, jitter and stats; the Redis settings that matter; and118 the near-cache (L1+L2) rules. Read when implementing or reviewing a cache.119- [Cache incident triage](references/incident-triage.md) — the symptom-to-cause table and120 the metric set that makes each cause visible. Read when a cache-related incident is in121 progress.