Caching is one of the most widely used techniques in modern software
engineering. It can reduce response times, protect databases from
repetitive reads, lower infrastructure costs, and help applications
serve substantially more traffic with the same resources. Yet caching is
also an easy way to introduce hidden complexity. A cached value can
become stale, an eviction policy can remove useful data, a popular key
can overload the origin when it expires, and a cache outage can turn a
healthy application into a database incident.
The central engineering challenge is not how to store a value in Redis.
It is how to introduce a second representation of data without losing
control over correctness, availability, and operational behavior. This
chapter develops a systematic approach to caching in distributed
systems, from fundamental models to production design. It uses Java,
Spring Boot, and Redis for practical examples while keeping the
underlying principles broadly applicable.
1. Caching as an Architectural Trade-Off
1.1 Why applications become slow
A user request rarely performs a single operation. A backend request may
authenticate a user, load account data, query several tables, call an
inventory service, calculate permissions, assemble a response, and
serialize it. Its latency is influenced by every operation.
A useful approximation is:
[ T_{\text{request}{=tex}} = T_{\text{compute}{=tex}} +
T_{\text{database}{=tex}} + T_{\text{network}{=tex}} +
T_{\text{queue}{=tex}} + T_{\text{serialization}{=tex}} ]
This is not a complete physical model, but it helps identify where time
is spent. CPU-bound computation may be accelerated through better
algorithms or more compute capacity. Database latency may be reduced
through indexes, query optimization, or reduced contention. Network
latency may be improved by reducing round trips.
Caching addresses a different opportunity: repeated work. If many
requests need the same relatively stable information, the system can
retain a previously retrieved or computed result and reuse it.
Consider a product catalogue endpoint. A product description may be
requested thousands of times while changing only a few times per day.
Repeating the same joins and serialization work for every request is
wasteful. A cache stores the result for a limited period or until an
explicit invalidation event occurs.
1.2 The cache is not the source of truth
A cache is normally a secondary representation of data. The
authoritative system, often called the system of record, remains
responsible for durable correctness. A relational database may be the
system of record for product prices, while Redis stores temporary copies
of product summaries.
This distinction has important consequences:
- Cache contents may be lost without losing the underlying business
data. - Cache entries may be evicted before their configured expiration.
- A cache may temporarily contain an older version than the source.
- Application logic must define what happens when the cache is
unavailable. - A successful cache write does not necessarily mean that the
underlying business transaction is durable.
Treating a cache as a database without explicitly designing for
durability, consistency, and recovery is a category error. The cache is
an optimization layer unless the architecture deliberately assigns it a
stronger role.
1.3 The economics of caching
Caching is useful when the cost of obtaining a value repeatedly is
greater than the cost of maintaining and reading its cached
representation.
A simplified expected-cost model is:
[ C_{\text{without cache}{=tex}} = N
\cdot{=tex}C_{\text{origin}{=tex}} ]
[ C_{\text{with cache}{=tex}} =
C_{\text{cache operations}{=tex}} + N \cdot{=tex} \left{=tex}(H
\cdot{=tex}C_{\text{hit}{=tex}} + (1-H)
\cdot{=tex}C_{\text{origin}{=tex}}\right{=tex}) ]
Here, (N) is the number of requests, (H) is the cache hit ratio, and the
cost terms may represent latency, CPU, money, or a combination. The
model omits invalidation and operational costs, which can be
substantial.
A cache is not automatically beneficial. If data is rarely requested,
changes constantly, or is cheap to calculate, the cache may add more
complexity than value. Microsoft's cache guidance recommends evaluating
access frequency, data volatility, cache lifetime, and miss overhead
rather than caching indiscriminately:
https://learn.microsoft.com/en-us/azure/architecture/best-practices/caching.
1.4 The fundamental trade-off
Caching trades freshness and simplicity for speed and reduced origin
load. The design question is not simply whether stale data is possible.
It is how stale data affects the business operation.
A product description that is thirty seconds old may be acceptable. An
account balance used to authorize a transfer may not be. A dashboard
statistic can often tolerate eventual consistency; a stock reservation
decision may require an authoritative transaction.
The acceptable staleness window must be defined by the business
semantics of the data, not selected merely because a ten-minute TTL
looks convenient.
2. Cache Fundamentals and Performance Mathematics
2.1 Cache hit, cache miss, and hit ratio
A cache hit occurs when the requested item is present and usable. A
cache miss occurs when the item is absent, expired, evicted, or
otherwise unavailable. On a miss, the application normally retrieves the
value from the origin and may populate the cache.
[ \text{Hit Ratio}{=tex} =
\frac{\text{Cache Hits}}{\text{Cache Hits} + \text{Cache Misses}}{=tex}
]
A 95% hit ratio sounds impressive, but it is not a complete performance
metric. A cache may serve 95% of requests quickly while the remaining 5%
create severe latency spikes. A high hit ratio can also hide a few
expensive hot keys or an unhealthy origin path.
Measure hit ratio alongside latency percentiles, origin request volume,
cache errors, eviction rates, and the cost of misses.
2.2 Why averages are misleading
Suppose 99 requests complete in 5 ms and one request takes 1,000 ms. The
arithmetic mean is 14.95 ms, but one percent of users experienced a
one-second response. In production, latency distributions matter more
than averages.
Track at least:
- p50: the median request latency.
- p95: the latency below which 95% of requests complete.
- p99: the latency below which 99% of requests complete.
- Maximum latency, interpreted carefully because it is sensitive to
sample size.
A cache may improve p50 while making p99 worse if misses trigger
synchronized database work. A mature caching strategy optimizes the full
latency distribution, not just the happy path.
2.3 The hit ratio does not equal the latency improvement
Assume an origin read takes 40 ms, a cache hit takes 2 ms, and the hit
ratio is 90%. Ignoring queueing and other work, expected read latency
is:
[ E[T] = 0.9(2) + 0.1(40) = 5.8 \text{ ms}{=tex} ]
This is a substantial improvement over 40 ms. But if cache misses
trigger ten simultaneous origin reads for the same key, the system may
experience a very different outcome under load. Cache performance
depends on concurrency and workload shape, not only arithmetic averages.
2.4 Locality and skewed access patterns
Many workloads are not uniformly distributed. A small fraction of
records may account for a large fraction of reads. News articles,
popular products, frequently accessed user profiles, and configuration
values often exhibit this skew.
Caching is particularly effective when requests have temporal or
frequency locality:
- Temporal locality: recently accessed values are likely to be
accessed again soon. - Frequency locality: some values are requested much more often than
others. - Spatial locality: accessing one item makes nearby or related items
more likely to be requested.
The access distribution should be measured. A cache designed around
uniform traffic may perform poorly when a small number of keys dominate
production traffic.
3. Cache Topologies: Where the Data Lives
3.1 Client-side and in-process caching
An in-process cache stores data inside the memory of the application
instance. It avoids network communication with an external cache and can
provide extremely low lookup latency.
Examples include Caffeine in Java or a bounded concurrent map.
In-process caching is suitable for reference data, local computations,
and values that can tolerate per-instance variation.
However, each application instance has its own memory. If ten instances
cache the same customer record, there may be ten copies. Updating one
instance's cache does not automatically update the others. This creates
a consistency problem.
In-process caches also consume memory from the application heap or
process memory budget. Unbounded caches can cause memory pressure,
garbage-collection pauses, or out-of-memory failures. A local cache must
have explicit capacity and expiration behavior.
3.2 Distributed caching
A distributed cache is accessed over the network and shared by multiple
application instances. Redis is a common example.
+----------------------+
| Load Balancer |
+----------+-----------+
|
+--------------+--------------+
| | |
+-----v-----+ +-----v-----+ +-----v-----+
| App Node 1| | App Node 2| | App Node 3|
+-----+-----+ +-----+-----+ +-----+-----+
| | |
+--------------+--------------+
|
+-------v-------+
| Redis Cluster |
+-------+-------+
|
+-------v-------+
| Primary DB |
+---------------+
A shared cache avoids independent copies in each application process and
can provide a common view of cached values. It adds a network hop,
another service to operate, and a new failure dependency.
Distributed caching is not inherently more correct than local caching.
It changes the consistency and availability model. A shared cache may be
the right choice when several instances need common values, while a
local cache may be more efficient for immutable or slowly changing
reference data.
3.3 Multi-level caching
Some systems use more than one cache layer:
Request
|
v
L1: In-process cache
|
| miss
v
L2: Distributed cache (Redis)
|
| miss
v
L3: Database or external origin
The local layer is fast, while the distributed layer is shared. But each
layer introduces its own freshness and invalidation rules. If an L1
entry survives after an L2 update, one application instance may continue
returning an older value.
Multi-level caching should be introduced only when measured latency or
load justifies the extra coordination. A design with two caches is not
automatically twice as fast. It may simply have twice as many places
where stale data can hide.
3.4 Cache topology decision table
Topology Strengths Main risks Typical use
In-process Very low Per-instance Local reference
latency, no divergence, data
network hop memory pressure
Distributed Shared across Network Shared application
instances, dependency, data
centralized cache outage
capacity
Multi-level Fast local reads Complex High-volume,
plus shared invalidation and latency-sensitive
layer freshness systems
CDN / edge Reduces origin Propagation and Static assets and
traffic close to invalidation cacheable HTTP
users complexity responses
The right topology follows from workload measurements, freshness
requirements, and operational capability. It should not be chosen
because a particular technology is fashionable.
4. Core Caching Patterns
4.1 Cache-Aside (Lazy Loading)
Cache-aside is one of the most common application caching patterns. The
application checks the cache first. If the value is absent, it reads
from the source of truth, stores the result, and returns it.
Application Cache Database
| | |
|---- GET key -->| |
|<--- miss ------| |
|---------------------------------> |
|<---------------- result ----------|
|---- SET key -->| |
|<--- success ---| |
Pseudocode:
public Product findProduct(String id) {
Product cached = cache.get(id);
if (cached != null) {
return cached;
}
Product product = repository.findById(id)
.orElseThrow(ProductNotFoundException::new);
cache.put(id, product);
return product;
}
Advantages:
- Only requested data is loaded.
- The cache can be repopulated after eviction.
- The source of truth remains independent of the cache.
- The application can choose different policies for different data.
Disadvantages:
- The first request after a miss is slower.
- Concurrent misses may duplicate origin work.
- The application must handle invalidation and stale values.
- A cache outage may increase database traffic sharply.
Microsoft's Cache-Aside pattern guidance describes the lazy-loading
model and emphasizes cache lifetime, eviction, local-cache divergence,
and consistency:
https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside.
4.2 Read-Through
In a read-through design, the application asks the cache for data and
the cache layer is responsible for loading a missing value from the
backing store. The application does not explicitly implement the
miss-and-populate sequence.
The distinction is primarily about responsibility. The cache provider or
an adapter owns the loading behavior. This can simplify application
code, but it does not eliminate the need to define expiration,
consistency, error handling, and concurrency behavior.
4.3 Write-Through
With write-through, an update writes to the primary data store and the
cache as part of the same logical operation. The goal is to ensure that
subsequent cache reads see the updated value.
This can provide strong read-after-write behavior when implemented
carefully, but it increases write-path latency and creates a dual-write
problem: the database write may succeed while the cache update fails, or
vice versa.
A database transaction generally cannot atomically commit an ordinary
relational database update and a separate Redis update without a
distributed transaction protocol. Many systems therefore use a practical
sequence, retry strategy, or outbox-based event propagation rather than
claiming atomicity that does not exist.
4.4 Write-Behind (Write-Back)
With write-behind, the application writes to the cache first and the
cache asynchronously propagates changes to the durable store.
This can reduce write latency and absorb bursts, but it changes the
durability model. If the cache loses data before propagation, business
updates may be lost. Write-behind is appropriate only when the system
has explicit durability, replay, ordering, and recovery guarantees.
It should not be casually applied to financial records, inventory
reservations, or other operations where losing an acknowledged write is
unacceptable.
4.5 Refresh-Ahead
Refresh-ahead updates a cached value before it expires, often based on
access frequency or an explicit schedule. It can reduce miss latency for
popular data, but refresh work consumes resources even when the value is
no longer needed.
Refresh-ahead works best when the system can predict demand and the
origin can support refresh traffic. It must also avoid synchronized
refresh schedules that create a new stampede.
4.6 Choosing a pattern
Pattern Read behavior Write behavior Main trade-off
Cache-aside Application Usually Simple, but miss
checks and invalidate after races and
populates source update staleness
Read-through Cache loads on Separate write Cleaner reads,
miss policy provider coupling
Write-through Reads from cache Update source and Fresher reads,
cache more write
coordination
Write-behind Reads from cache Cache then Fast writes,
asynchronous durability
source update complexity
Refresh-ahead Cache serves Background Lower miss
while refresh refresh latency, extra
runs work
These patterns are not mutually exclusive. A system may use cache-aside
for product pages, write-through for a frequently read configuration
object, and no cache at all for a sensitive authorization decision.
5. Cache Invalidation and Data Consistency
5.1 Why invalidation is difficult
A cached value is a copy of information that can change elsewhere. Once
the source changes, the cache may no longer represent the current state.
Suppose a product's price changes from 100 to 120. The database commits
the new price, but Redis still contains 100. Users may see the old price
until the cache expires or is invalidated.
This is not merely a technical inconvenience. It is a consistency
decision. The system must specify how long the old value may be served,
which operations require fresh data, and what happens when invalidation
fails.
5.2 Time-to-live (TTL)
A TTL defines how long a cache entry remains eligible to be served. When
its lifetime expires, the cache treats the entry as expired and it may
be removed.
TTL is a safety mechanism, not a complete consistency strategy. A
60-second TTL means that stale data may be served for close to 60
seconds after a source update, depending on timing and implementation.
Choose TTL by asking:
- How quickly can the underlying value change?
- How costly is it to serve an older value?
- How expensive is the origin read?
- How often is the value reused?
- What happens if the cache entry expires during a traffic peak?
Different data classes should have different TTLs. Static country codes
may have a long lifetime. Product descriptions may have minutes.
Real-time account balances may not be appropriate for ordinary caching
at all.
5.3 Invalidate after a successful database update
For cache-aside, a common approach is to commit the source update and
then delete the cached entry.
@Transactional
public void updateProduct(Product product) {
repository.save(product);
// Invalidation is handled after transaction commit.
}
If the cache is invalidated before the database transaction commits,
another request may observe a cache miss, read the old database value,
and repopulate the cache with stale data.
A safer conceptual sequence is:
1. Update database row.
2. Commit database transaction.
3. Invalidate cache entry.
4. Next read repopulates from the committed source.
However, even this sequence has a failure window: the database may
commit and the process may crash before invalidation. The source is
correct, but the old cache value remains.
For stronger reliability, applications often publish an invalidation
event through a transactional outbox. The database transaction writes
both the business change and an outbox record. A separate publisher
delivers the event and retries until it is processed. This avoids
relying on an in-memory callback after commit, although event delivery
and cache invalidation are still asynchronous.
5.4 The stale repopulation race
Consider this sequence:
- Request A reads an old value from the database.
- Request B updates the database and invalidates the cache.
- Request A writes its old value into the now-empty cache.
The cache is stale again even though invalidation happened after the
update. This is a race between concurrent readers and writers.
Possible mitigations include versioned cache values, short TTLs, per-key
coordination during refresh, compare-and-set or atomic scripts,
event-driven invalidation combined with version checks, and bypassing
the cache for operations requiring strict freshness.
There is no universal solution. The appropriate mechanism depends on
write frequency, read volume, and the consequences of stale data.
5.5 Versioned cache keys
Instead of overwriting a single key, an application can include a
version in the key:
product:42:v17
When the product changes, the authoritative version advances. New
readers request product:42:v18, while the old value becomes
unreachable and eventually expires.
Versioned keys can prevent an older refresh from overwriting a newer
value, but the application must reliably obtain the current version. If
the version itself is cached without a consistency strategy, the problem
has merely moved.
5.6 Event-driven invalidation
In larger systems, the service that owns the data can publish a domain
event after a committed change:
ProductUpdated(productId=42, version=18)
Subscribers invalidate or refresh their local and distributed cache
entries. This supports multiple consumers and avoids coupling every
writer directly to every cache.
The design must account for duplicate events, delayed delivery,
reordering, and consumer restarts. Event handlers should be idempotent.
Version numbers or event sequence numbers help consumers reject obsolete
updates.
5.7 Consistency models in practice
Model Meaning Suitable examples
Strong / authoritative Read from the system Payment authorization,
read of record critical inventory
checks
Read-after-write A writer sees its Profile update
committed update on confirmation
subsequent reads
Eventual consistency Replicas converge Search index,
after propagation analytics,
delay recommendation data
Bounded staleness Old values may be Product catalogue,
served within a public content
defined time or
version bound
Stale-while-revalidate Serve an older News, public metadata,
acceptable value while non-critical
refreshing dashboards
The terms should be used precisely. A TTL does not guarantee bounded
staleness if the source replica itself is stale or if refreshes
repeatedly fail. A cache design needs to consider the entire data path.
6. Cache Stampedes, Thundering Herds and Hot Keys
6.1 The cache stampede problem
A cache stampede occurs when many concurrent requests miss the same key
and independently try to rebuild it. The cache stops protecting the
origin precisely when the origin receives a sudden burst of duplicate
work.
Imagine a popular product page that receives 500 requests per second.
Its cache entry expires. If every request queries the database, the
origin may suddenly receive hundreds of identical queries. The database
slows down, which increases request duration, which increases
concurrency, which can make the incident worse.
The cache did not merely fail to accelerate the system. Its expiration
behavior created synchronized work.
6.2 Request coalescing / single-flight
Request coalescing ensures that only one request performs the expensive
load for a given key while other requests wait for the same result.
Within one application process, a keyed future or lock can implement
this. Across multiple application instances, local locks are
insufficient because each instance can still start its own refresh. A
distributed lease or a cache-provider feature may be needed.
A simplified local Java example:
private final ConcurrentHashMap<String, CompletableFuture<Product>> inFlight =
new ConcurrentHashMap<>();
public Product loadProduct(String id) {
Product cached = cache.get(id);
if (cached != null) {
return cached;
}
CompletableFuture<Product> future = inFlight.computeIfAbsent(id, key ->
CompletableFuture.supplyAsync(() -> {
try {
Product product = repository.findById(key)
.orElseThrow(ProductNotFoundException::new);
cache.put(key, product);
return product;
} finally {
inFlight.remove(key);
}
}, executor)
);
return future.join();
}
This illustrates the idea, not a complete production implementation.
Real code must handle executor saturation, exceptions, cancellation,
timeouts, cache failures, and removal races. A distributed deployment
needs cross-instance coordination if the goal is one refresh globally.
6.3 Distributed locks and leases
A distributed lease grants one worker temporary ownership of a refresh
task. The lease should have a unique owner token, a short expiration
time, bounded waits, safe release that verifies ownership, a fallback if
the lease holder crashes, and protection against a worker continuing
after its lease expires.
A lock is not magic. Network pauses can cause a worker to believe it
still owns a lease after another worker has acquired it. For operations
that modify durable state, fencing tokens or version checks may be
necessary. For cache refresh, a version-aware write often provides a
simpler safety boundary.
6.4 TTL jitter
If thousands of entries are populated at the same time with the same
TTL, they may expire together. TTL jitter adds a random component to
expiration.
Duration baseTtl = Duration.ofMinutes(10);
long jitterSeconds = ThreadLocalRandom.current().nextLong(0, 120);
Duration effectiveTtl = baseTtl.plusSeconds(jitterSeconds);
This spreads expirations across different keys. It reduces synchronized
expiration waves, but it does not solve a hot-key stampede where one
very popular key expires and receives many concurrent requests. That
requires coalescing, early refresh, stale serving, or another per-key
mechanism.
6.5 Stale-while-revalidate
Stale-while-revalidate allows the application to serve a slightly old
value while one worker refreshes it in the background.
A common design stores two time boundaries:
- Fresh-until: after this time, refresh should begin.
- Stale-until: after this time, the value must no longer be served.
Fresh period Stale grace period Expired
|------------------|---------------------------|
Serve fresh Serve stale + refresh Must load origin
This pattern can preserve low latency during refresh, but it is only
safe when the business accepts stale values. It must never be used
blindly for decisions where an old value can authorize an invalid
transaction or misrepresent critical availability.
6.6 Probabilistic early expiration
Another technique allows requests to probabilistically trigger refresh
before the hard expiration time. This spreads refresh work rather than
waiting for a single expiration instant. Research on optimal
probabilistic cache-stampede prevention formalizes this approach:
https://cseweb.ucsd.edu/\~avattani/papers/cache_stampede.pdf.
6.7 Hot keys
A hot key is a cache entry that receives a disproportionately high
volume of requests. Even when the cache has a high overall hit ratio,
one hot key can overload a shard, create network concentration, or
become a bottleneck.
Potential strategies include local L1 caching for extremely popular,
safely cacheable values; replication or sharding strategies appropriate
to the cache platform; request coalescing; precomputed materialized
responses; key splitting for aggregations where semantics allow it; and
rate limiting or load shedding.
Key splitting is not universally valid. Duplicating an immutable
configuration value may be harmless; splitting a mutable counter
requires a correct aggregation model.
7. Redis as a Distributed Cache
7.1 Why Redis is commonly used
Redis provides in-memory data structures and network-accessible
operations with low latency. It supports strings, hashes, lists, sets,
sorted sets, streams, expiration, and other capabilities. These features
make it useful for cache entries, counters, rate limits, ephemeral
coordination, and other workloads.
Using Redis as a cache does not mean every application value should be
stored there. A cache should contain values that are worth reusing, have
a defined freshness policy, and can be reconstructed or safely recovered
if lost.
7.2 Key design and namespacing
A cache key is part of the application's data model. Poor key design
causes collisions, difficult invalidation, and operational confusion.
Prefer explicit, versionable names:
catalog:product:v2:42
customer:profile:v1:customer-781
pricing:region:de:product-42
Good keys should include the entity or query type, relevant tenant or
authorization scope, a schema/version marker when serialization changes,
and a predictable invalidation strategy. Avoid putting sensitive
personal information in plain text.
If a response depends on locale, currency, tenant, role, or feature
flags, those dimensions may need to be represented in the key. Otherwise
one caller can receive another caller's cached representation.
7.3 TTL and eviction are different mechanisms
TTL controls the lifetime of an entry. Eviction controls what happens
when the cache reaches its memory limit. A key may be evicted before its
TTL expires because memory is needed for other entries.
Redis supports policies such as allkeys-lru, allkeys-lfu,
volatile-lru, and noeviction. LRU approximates least-recently-used
behavior; LFU favors keys that are accessed frequently. The correct
policy depends on workload shape and whether all keys are disposable
cache entries. See the Redis eviction documentation:
https://redis.io/docs/latest/develop/reference/eviction/.
For a cache-only Redis instance, an all-keys policy may be appropriate
because any entry can be reconstructed. If the same Redis instance
contains non-cache data that must not be evicted, mixing workloads
requires careful policy design and often separate instances or databases
with clear operational boundaries.
7.4 Memory budgeting
Do not estimate cache capacity using only the serialized payload size.
Redis memory consumption also includes key names, object metadata,
allocator overhead, data-structure encoding, replication buffers, client
buffers, and operational headroom.
A practical process is:
- Measure representative key memory with Redis tooling.
- Sample realistic production-shaped data.
- Estimate key cardinality and growth.
- Reserve memory for fragmentation, buffers, replication, and
failover. - Load test eviction behavior.
- Alert before the system reaches sustained memory pressure.
The configured maxmemory limit is not necessarily the exact process
resident-memory ceiling. Redis needs memory for activities beyond the
dataset itself. See:
https://redis.io/docs/latest/develop/reference/eviction/.
7.5 Eviction policy selection
Policy Behavior When to consider it
allkeys-lru Evicts least recently General cache with
used keys temporal locality
allkeys-lfu Evicts least frequently Stable popularity skew
used keys
volatile-lru Evicts LRU keys that Mixed dataset where
have TTLs only expiring keys are
disposable
volatile-ttl Favors keys with TTL is intentionally
shorter remaining TTL used as an eviction
signal
noeviction Rejects writes that Workloads where silent
exceed memory limit eviction is
unacceptable
An eviction policy is not a substitute for capacity planning. If the
cache constantly evicts useful entries, the hit ratio falls and origin
load rises. Monitor evictions and correlate them with database traffic.
7.6 Redis availability and cache failure
A distributed cache can fail because of network partitions, node
restarts, failover, resource exhaustion, connection-pool saturation, or
application misconfiguration. The application must decide what happens
when Redis cannot be reached.
For reconstructible, non-critical values, a common strategy is to bypass
the cache and read from the source. But this creates a danger: if every
application instance falls back simultaneously, the database may be
overwhelmed.
A safe fallback design can include strict cache connection timeouts,
bounded retries, concurrency limits on origin fallback, rate limiting or
load shedding, a circuit breaker around the cache or origin path, stale
local values where safe, and explicit degraded-mode behavior.
Fail-open and fail-closed are business decisions. A public product
description may fail open to the database. An authorization cache outage
may require a fail-closed policy or a direct authoritative check. Never
choose the behavior globally without considering the data.
8. Implementing Redis Caching with Java and Spring Boot
8.1 Spring's cache abstraction
Spring provides a cache abstraction that separates application code from
a specific cache provider. Common annotations include:
@Cacheable: read from cache and populate on a miss.@CachePut: execute the method and update the cache with its
result.@CacheEvict: remove an entry or a whole cache.@Caching: combine multiple cache operations.
Spring Boot can auto-configure cache infrastructure when caching is
enabled and a supported provider is present. Without a specific
provider, the simple in-memory provider is useful for development but
should not be mistaken for a production distributed cache. See the
Spring Boot caching reference:
https://docs.spring.io/spring-boot/reference/io/caching.html and Spring
Framework annotation reference:
https://docs.spring.io/spring-framework/reference/integration/cache/annotations.html.
8.2 Dependencies
For a typical Spring Boot application, include the cache starter and
Spring Data Redis starter. Exact dependency versions should be managed
by the Spring Boot dependency management/BOM rather than copied from an
unrelated version matrix.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
8.3 Enable caching
@Configuration
@EnableCaching
public class CachingConfiguration {
}
In larger applications, it is often better to keep caching configuration
separate from the main application class. This also makes it easier to
disable or replace caching in tests.
8.4 Define cache behavior explicitly
A minimal configuration might set a default TTL and a key prefix. For
production, define cache-specific policies rather than applying one
global TTL to every type of data.
@Configuration
@EnableCaching
public class CacheConfiguration {
@Bean
RedisCacheManager cacheManager(
RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration defaults =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5))
.disableCachingNullValues()
.computePrefixWith(cacheName ->
"farschidnia:" + cacheName + ":");
Map<String, RedisCacheConfiguration> caches = Map.of(
"products", defaults.entryTtl(Duration.ofMinutes(10)),
"categories", defaults.entryTtl(Duration.ofHours(1)),
"publicProfiles", defaults.entryTtl(Duration.ofMinutes(3))
);
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaults)
.withInitialCacheConfigurations(caches)
.build();
}
}
This is an illustrative configuration. Serializer selection, key
conversion, Redis topology, TLS, credentials, connection timeouts, and
cache-specific TTLs must be configured for the actual deployment. If
cached objects are serialized, use a deliberate serialization format and
schema-evolution strategy. Do not deserialize untrusted data with unsafe
polymorphic typing.
8.5 Cache a read operation
@Service
public class ProductService {
private final ProductRepository repository;
public ProductService(ProductRepository repository) {
this.repository = repository;
}
@Cacheable(
cacheNames = "products",
key = "#productId",
unless = "#result == null"
)
public ProductDto findProduct(String productId) {
return repository.findById(productId)
.map(ProductDto::from)
.orElseThrow(ProductNotFoundException::new);
}
}
The method result is stored after a cache miss. Subsequent calls with
the same key can return the cached result without invoking the method.
A critical Spring detail: annotation-driven caching is commonly
implemented through proxies. Self-invocation from one method to another
method on the same object may bypass the proxy and therefore bypass the
caching advice. Keep cacheable operations on separately injected beans
or use an explicit cache API when proxy semantics are unsuitable.
8.6 Invalidate after updates
@Service
public class ProductCommandService {
private final ProductRepository repository;
public ProductCommandService(ProductRepository repository) {
this.repository = repository;
}
@Transactional
@CacheEvict(cacheNames = "products", key = "#product.id")
public Product update(Product product) {
return repository.save(product);
}
}
This example demonstrates the intent, but transaction ordering must be
verified for the actual Spring configuration and transaction manager. In
systems where correctness depends on invalidation only after commit, use
an after-commit event listener or a transactional outbox. An annotation
alone should not be treated as proof of atomic coordination between the
database and Redis.
8.7 Update the cache with @CachePut
@CachePut(cacheNames = "products", key = "#result.id")
public ProductDto updateProduct(UpdateProductCommand command) {
Product updated = repository.update(command);
return ProductDto.from(updated);
}
@CachePut always executes the method and stores its result. It is
different from @Cacheable, which may skip method execution on a hit.
Do not place both annotations on the same method without a carefully
reasoned use case.
8.8 Cache keys must include the full representation context
Suppose a product response varies by locale and currency. Caching only
by product ID is unsafe:
@Cacheable(cacheNames = "productViews", key = "#productId")
A better key includes the representation dimensions:
@Cacheable(
cacheNames = "productViews",
key = "#productId + ':' + #locale.toLanguageTag() + ':' + #currency"
)
public ProductView findProductView(
String productId,
Locale locale,
Currency currency) {
// Build localized and currency-aware representation.
}
The principle applies to tenant ID, authorization scope, feature flags,
API version, and any other input that changes the response.
8.9 Negative caching
Sometimes a lookup for a missing record is expensive and repeatedly
requested. Negative caching stores the fact that the item was not found
for a short period.
This can protect the database from repeated lookups for nonexistent IDs,
but it creates a risk: a record may be created while the negative entry
remains cached. Use short TTLs and explicit invalidation on creation. Be
careful not to expose whether a sensitive resource exists through cache
behavior.
9. Security, Privacy and Multi-Tenancy
9.1 Cache isolation is a security requirement
A cache key that omits tenant or user scope can leak data across
accounts. For example, if /profile/current is cached under a single
key, one user's response may be returned to another user.
The cache key must represent the security boundary of the data. For
personalized content, include the tenant and user identity or avoid
shared caching. Authorization decisions should normally be evaluated
against authoritative policy data or use a rigorously designed,
short-lived permission cache.
9.2 Sensitive data and retention
Do not cache secrets, credentials, payment data, or sensitive personal
information merely because the cache is fast. If sensitive data must be
cached, define encryption, access control, retention, audit, and
deletion behavior.
A cache can retain data after the source record has been deleted.
Privacy deletion workflows must therefore include caches, replicas,
search indexes, and derived data where applicable.
9.3 Cache poisoning and untrusted input
If an attacker can influence cache keys or cached values, they may cause
collisions, excessive key cardinality, or unsafe content to be served to
other users. Validate inputs, canonicalize keys, separate trust domains,
and avoid caching untrusted serialized objects.
9.4 HTTP caches and authorization
HTTP caching adds another layer: browser caches, reverse proxies, and
CDNs. Headers such as Cache-Control, Vary, and authorization-related
directives affect whether responses may be stored and reused. A backend
Redis cache and an HTTP shared cache have different trust boundaries. A
response safe for one authenticated user must not accidentally become
publicly reusable.
10. Caching Failure Modes and Anti-Patterns
10.1 Caching everything
Caching every repository method creates a large invalidation surface and
makes performance behavior difficult to understand. Cache only values
with measured reuse and a defined freshness policy.
10.2 One TTL for every object
A universal TTL ignores the fact that configuration, catalogue data,
user profiles, inventory, and permissions have different change rates
and correctness requirements. Use named cache policies and document why
each exists.
10.3 Unbounded local caches
An unbounded map can turn a performance optimization into a memory leak.
Set maximum size, expiration, and observability. Load test cardinality
growth.
10.4 Cache stampede without a plan
A high hit ratio does not protect the origin from synchronized misses.
Popular keys need explicit refresh coordination, jitter, or safe stale
serving.
10.5 Treating Redis as a durable database by accident
If losing a Redis key would permanently lose a business event, the
architecture is not using Redis merely as a cache. It is relying on
Redis for durability and must design persistence, replication, recovery,
backup, and acknowledgment semantics accordingly.
10.6 Silent fallback to the database
If Redis fails and all requests immediately fall back to the database,
the database can fail next. Fallback must be bounded by concurrency
controls, timeouts, rate limits, and capacity planning.
10.7 Incorrect cache keys
A key that omits locale, tenant, user, currency, or feature context can
return incorrect data. This is both a correctness and security defect.
10.8 Caching mutable objects by reference
In-process caches may return references to mutable objects. One caller
can modify the object and unintentionally change what later callers
receive. Prefer immutable DTOs or defensive copies.
10.9 Assuming a cache hit means a correct answer
A hit only means the cache found a value. It says nothing about whether
that value is fresh, authorized, correctly versioned, or semantically
appropriate for the caller.
11. Observability: How to Know Whether the Cache Helps
11.1 Core metrics
Metric Why it matters
Hit and miss count Shows reuse and miss behavior
Hit ratio by cache/namespace Identifies ineffective cache
regions
Lookup latency Measures cache performance itself
Origin reads caused by misses Shows database protection
Evictions Reveals memory pressure or poor
sizing
Memory usage and fragmentation Supports capacity planning
Key cardinality Detects unexpected growth
Expiration rate Helps identify synchronized expiry
Connection errors and timeouts Reveals dependency health
Refresh duration and failures Measures background refresh
reliability
Stale response count/age Makes freshness visible
Do not rely on one global hit ratio. A healthy product cache can hide a
failing permissions cache. Break metrics down by cache name, service,
operation, and carefully controlled key groups.
11.2 Trace cache behavior
Distributed tracing should make cache operations visible in the request
path. A trace can show whether latency came from a cache hit, a cache
miss, a Redis timeout, a database query, or a refresh lock wait.
Avoid placing raw user IDs, email addresses, or arbitrary cache keys
into high-cardinality metric labels. Use bounded dimensions and trace
attributes with appropriate privacy controls.
11.3 Measure the origin, not only Redis
The purpose of a cache is usually to improve the system as a whole.
Monitor database query rate, CPU, connection-pool saturation, lock
waits, and tail latency. A cache can look healthy while the origin is
still overloaded by misses or background refresh.
11.4 Define service-level objectives
A cache should support user-facing objectives rather than becoming an
objective in itself. Example targets might include p95 endpoint latency
below a defined threshold, a maximum origin read rate under expected
traffic, cache error rates below a defined level, a bounded stale-data
window for public catalogue data, and recovery behavior that does not
overwhelm the database during cache failure.
The exact values must come from the product's needs and measured
capacity. Arbitrary targets create dashboards, not reliability.
12. Testing Caching Systems
12.1 Unit tests
Test the application behavior around hits, misses, invalidation, null
results, and exceptions. Verify that cache keys include all
representation dimensions.
12.2 Integration tests
Run tests against the actual cache implementation where possible.
In-memory substitutes can hide serialization, TTL, eviction, and
connection behavior that only appears with Redis.
12.3 Concurrency tests
Test many simultaneous requests for the same missing key. Confirm that
request coalescing works, locks expire safely, and the origin is not
flooded.
12.4 Failure-injection tests
Simulate Redis unavailable at startup, Redis disconnecting during
requests, slow cache responses, cache timeouts and connection-pool
exhaustion, database slowdown during cache misses, eviction under memory
pressure, duplicate or delayed invalidation events, and application
restart while refresh work is in progress.
A cache strategy that works only when every dependency is healthy is not
a production strategy.
12.5 Load tests with realistic distributions
Uniform random keys are often unrealistic. Include hot keys, long-tail
keys, changing popularity, burst traffic, and synchronized expiration.
Measure p95 and p99 latency, origin QPS, memory usage, and recovery
after a cache flush.
13. A Worked Architecture: Product Catalogue
13.1 Requirements
Consider an e-commerce catalogue with the following characteristics:
- Product descriptions and category metadata are read frequently.
- Product content changes occasionally.
- Prices may change more often and have higher business impact.
- Inventory availability changes frequently.
- Multiple application instances serve requests.
- A stale description is acceptable for a short period.
- A stale price or inventory value must not authorize a transaction.
The first design decision is to separate data by semantics rather than
cache the entire product object as one indivisible value.
13.2 Data classification
Data Cache decision Freshness policy
Product description Cache Short bounded staleness
Category metadata Cache Longer TTL
Product image URL Cache Invalidate on content
update
Display price Carefully cache for Revalidate at checkout
browsing
Inventory count Avoid ordinary cache Read authoritative path
for reservation
User-specific discount Scope by user/segment Explicit policy and
or calculate live short lifetime
This separation prevents a low-risk field from dictating the consistency
model of a high-risk field.
13.3 Read path
GET /products/42
|
v
Product API
|
+---- Redis: product-description:42
| |
| +---- hit: return cached description
| |
| +---- miss
| |
| v
| Product DB
| |
| v
| Populate cache
|
+---- Price service: display price
|
+---- Inventory summary: explicitly marked as indicative
The endpoint may combine values from different consistency domains. Its
API contract should make that clear. A displayed inventory estimate is
not the same thing as a reservation guarantee.
13.4 Write path
When a product description changes:
- Commit the product update to the database.
- Record an outbox event in the same transaction.
- Publish
ProductDescriptionUpdated. - Invalidate or refresh the corresponding cache key.
- Record processing status and retry failed delivery.
- Let TTL provide a secondary upper bound on stale retention.
When inventory changes, the reservation operation uses the authoritative
inventory transaction rather than trusting a cached summary.
13.5 Degraded mode
If Redis becomes unavailable, the product-description endpoint may read
from the database, but only within an origin concurrency budget. If the
budget is exhausted, the service may serve a permitted stale local copy
or return a controlled error. Checkout and inventory reservation
continue through their authoritative path.
This design makes the cache an optimization instead of a single point of
business correctness.
14. Capacity Planning and Performance Engineering
14.1 Estimate request volume
Begin with measured traffic, not guesses. Determine requests per second,
key distribution, average object size, write rate, and expected hit
ratio. Model both normal traffic and peak traffic.
If the origin handles 20,000 reads per second and a cache achieves a 90%
hit ratio for that workload, the idealized miss rate is 2,000 reads per
second. But if a hot key expires and generates 5,000 concurrent misses,
the average calculation no longer describes the peak.
14.2 Estimate memory
A rough estimate is:
[ M_{\text{required}{=tex}} \approx{=tex}K
\cdot{=tex}(S_{\text{value}{=tex}} + S_{\text{key}{=tex}} +
S_{\text{overhead}{=tex}}) ]
where (K) is the number of cached entries. This estimate must be
validated with actual Redis memory measurements. Add operational
headroom for replication, client buffers, fragmentation, and growth.
14.3 Cache only what earns its place
For each candidate value, estimate read frequency, update frequency,
origin cost, serialized size, freshness tolerance, key cardinality,
invalidation complexity, and security sensitivity.
A large, rarely reused object can consume substantial memory for little
benefit. A small, frequently requested configuration object may be an
excellent candidate.
14.4 Benchmark the whole path
Compare at least three cases: origin only, cache hit, and cache miss
with population. Then test under concurrency and failure. A cache may
improve single-request latency but reduce throughput if serialization,
connection pools, or lock contention become bottlenecks.
15. An Engineering Decision Framework
Before introducing a cache, answer the following questions.
15.1 Data semantics
- What is the system of record?
- Is stale data acceptable?
- What is the maximum acceptable staleness?
- Does the value contain tenant-specific or user-specific information?
- Is the value safe to reconstruct after cache loss?
15.2 Workload
- How frequently is the value read?
- How frequently does it change?
- Is access skewed toward hot keys?
- What is the origin cost?
- What is the expected cache cardinality?
15.3 Consistency
- Is invalidation time-based, event-driven, or write-through?
- Can concurrent reads repopulate stale values?
- Are events duplicated or reordered?
- Is versioning required?
- Which operations must bypass the cache?
15.4 Reliability
- What happens if Redis is unavailable?
- Can the database handle fallback traffic?
- Is fallback concurrency bounded?
- What happens during synchronized expiration?
- How does the system recover after a full cache flush?
15.5 Operations
- Are hit ratio, misses, evictions, memory, and latency monitored?
- Are cache policies documented per data class?
- Are cache failures tested?
- Is there a runbook for cache flushes and failover?
- Can the cache be disabled safely?
If these questions have no clear answers, adding a cache is premature.
16. Production Readiness Checklist
Architecture and correctness
- The source of truth is explicitly identified.
- Every cached data class has a documented freshness requirement.
- Cache keys include tenant, locale, currency, and other relevant
dimensions. - Sensitive and authorization-related data has an explicit policy.
- Cache invalidation is designed for transaction and process
failure. - Stale repopulation races have been considered.
- High-impact operations use authoritative data where required.
Performance and capacity
- Cache hit and miss latency are measured.
- p95 and p99 endpoint latency are monitored.
- Cache cardinality and memory are bounded.
- TTLs are selected per data class.
- Eviction policy matches the workload.
- Hot keys and stampedes are addressed.
- Capacity includes operational headroom.
Reliability and operations
- Cache connection timeouts are bounded.
- Fallback traffic is concurrency-limited.
- Redis outage behavior is documented.
- Refresh and invalidation events are retryable and idempotent.
- Cache failure and recovery are tested.
- Dashboards and alerts cover evictions, errors, memory, and
origin load. - Cache flush procedures are understood and rehearsed.
17. HTTP Caching: The Protocol-Level Dimension
17.1 Application caches and HTTP caches solve different problems
A backend cache such as Redis is controlled by application code. HTTP
caching is governed by protocol semantics and may involve browsers,
operating-system caches, reverse proxies, API gateways, and content
delivery networks. Both reduce repeated work, but they operate at
different boundaries.
An application cache may store a database-derived Product object. An
HTTP cache may store the complete response representation for
GET /products/42. The latter can avoid a request reaching the
application at all. This can be substantially more efficient, but it
also means the response may be reused by an intermediary that does not
understand the application's internal authorization model.
HTTP caching must therefore be designed around the semantics of the
response, not simply around whether the endpoint is a GET request.
17.2 The role of Cache-Control
The Cache-Control response header communicates caching directives.
Common directives include:
max-age: the number of seconds for which a response is considered
fresh by a cache.s-maxage: a freshness lifetime specifically for shared caches.no-cache: a stored response must be revalidated before reuse. It
does not mean that storage is forbidden.no-store: caches must not store the response.private: the response is intended for a private cache, not a
shared cache.public: the response may be stored by shared caches, subject to
the other applicable rules.must-revalidate: once stale, a cache must not reuse the response
without successful validation, subject to protocol rules.stale-while-revalidate: permits serving a stale response for a
bounded period while revalidation occurs.stale-if-error: permits stale reuse under specified error
conditions.
These directives are not interchangeable. In particular, no-cache and
no-store have very different meanings. The authoritative semantics are
defined in HTTP caching specifications, notably RFC 9111:
https://www.rfc-editor.org/rfc/rfc9111.
17.3 Validators: ETag and Last-Modified
A cache does not always need to download a complete representation again
to discover whether it changed. HTTP validators support conditional
requests.
An origin can return an ETag, an opaque validator for a
representation:
HTTP/1.1 200 OK
ETag: "product-42-v18"
Cache-Control: public, max-age=60
Content-Type: application/json
When the response becomes stale, a client or intermediary can send:
GET /products/42 HTTP/1.1
If-None-Match: "product-42-v18"
If the representation has not changed, the origin can return:
HTTP/1.1 304 Not Modified
ETag: "product-42-v18"
The client can reuse its stored body. This reduces transfer size,
although the request still reaches the origin unless an intermediary can
satisfy it.
Last-Modified and If-Modified-Since provide a time-based validation
mechanism. Entity tags are generally more precise because timestamps can
have limited resolution and do not always represent content identity
reliably.
17.4 The Vary header and representation dimensions
A response may depend on request headers. For example, an endpoint may
return compressed content depending on Accept-Encoding, or localized
content depending on Accept-Language.
The Vary header tells caches which request headers influence the
representation:
Vary: Accept-Encoding, Accept-Language
If a response varies by a dimension but the cache does not account for
it, one caller can receive a representation generated for another
caller. This is conceptually the same defect as omitting locale from a
Redis key.
17.5 Authenticated responses and shared caches
Caching authenticated responses requires particular care. A response
containing user-specific data must not be accidentally stored and reused
by a shared cache for another user. private and no-store are often
appropriate for sensitive responses, but the exact policy depends on the
application and protocol requirements.
Do not infer that a response is safe for shared caching merely because
it is returned by a GET endpoint. A GET can still return personalized or
confidential information.
17.6 Choosing the right layer
Use browser or CDN caching for public, reusable representations such as
versioned static assets and public content. Use application caching for
database-derived or domain-specific values that need application-aware
keys and invalidation. Use both only when their freshness rules compose
correctly.
A request may pass through several independent caches. The effective
freshness behavior is determined by the entire chain, including origin
headers, intermediary configuration, and application-side cache policy.
18. Content Delivery Networks and Edge Caching
18.1 Why edge caching matters
A content delivery network (CDN) stores cacheable content at
geographically distributed edge locations. A user can retrieve a static
asset from a nearby edge rather than from the origin region. This
reduces network distance, origin bandwidth, and repeated work.
CDNs are especially useful for:
- Versioned JavaScript and CSS bundles.
- Images, fonts, and downloadable files.
- Public product imagery.
- Public documentation and editorial content.
- Carefully designed cacheable API responses.
A CDN does not automatically accelerate every dynamic request. If each
response is personalized, uncacheable, or varies on many request
dimensions, the edge hit ratio may be low.
18.2 Cache keys at the edge
A CDN cache key commonly includes the URL and may include selected query
parameters or request headers. Every dimension that changes the response
must be represented in the cache key or excluded from shared caching.
Overly broad cache keys create correctness and security defects. Overly
specific keys fragment the cache and reduce reuse. For example,
including an irrelevant tracking parameter can create a separate cache
entry for every campaign URL.
18.3 Invalidation and cache purging
CDNs often support purging by URL, tag, surrogate key, or namespace.
Purging can propagate asynchronously across edge locations. A successful
purge request does not always mean every edge has instantly stopped
serving the old representation.
Versioned asset names provide a robust alternative for immutable
content:
/app.8f3a91c2.js
/styles.3b2a7d10.css
When content changes, the build emits a new URL. The old object can
remain cached for a long time because clients requesting the new version
use a different key. This is often safer and more scalable than
repeatedly purging mutable asset URLs.
18.4 Edge caching is not a replacement for backend caching
A CDN can reduce traffic reaching the application, but cache misses
still need to be served by the origin. Backend caching can reduce the
cost of those misses and protect databases. A layered architecture may
therefore use CDN caching for public responses, Redis for domain data,
and a database as the source of truth.
Each layer must have an explicit cache key, freshness policy, and
invalidation strategy. Otherwise, one layer may continue serving stale
content after another layer has been updated.
19. Consistency Engineering: Race Conditions and Ordering
19.1 Why simple invalidation is not atomic
Consider a cache-aside application with a database and Redis. A
developer might assume that deleting a cache key after a database update
is enough. But the database and Redis are separate systems. Without a
distributed transaction, there is no single atomic commit covering both.
The following failure is possible:
Writer Database Redis
| | |
|---- UPDATE ---------->| |
|<--- COMMIT -----------| |
| | |
X process crashes | |
| old value remains
The database is correct, but the cache remains stale. A TTL bounds the
duration only if the entry expires and the refresh path reads
sufficiently fresh data.
19.2 The stale-fill race in detail
A more subtle race occurs when a reader starts before a writer:
Reader A Database Writer B Cache
| | | |
|---- SELECT --------->| | |
| | | |
| |<--- UPDATE --------| |
| |---- COMMIT ------->| |
| | |---- DELETE ------->|
|<--- old row ---------| | |
|------------------------------------------------ SET old value ->|
The invalidation succeeds, but the reader subsequently repopulates the
cache with an older value. This demonstrates why invalidation is a
concurrency problem, not merely a deletion operation.
19.3 Version checks
One mitigation is to attach a monotonically increasing version to the
source record and cached representation. A refresh may populate the
cache only if its version is not older than the version already stored.
Conceptually:
Database record: product 42, version 18
Cache entry: product 42, version 17
Incoming fill: product 42, version 16 -> reject
Incoming fill: product 42, version 18 -> accept
The comparison and write must be atomic. In Redis, this can be
implemented with a Lua script or another atomic operation. A plain GET
followed by SET is not sufficient because another writer can change the
value between those commands.
Versioning introduces its own requirements: versions must be generated
reliably, compared consistently, and associated with the correct entity
lifecycle. Deleting and recreating an entity must not accidentally reset
a version in a way that makes an old cache entry appear current.
19.4 The transactional outbox pattern
The outbox pattern addresses the gap between committing a database
update and publishing an event. The business transaction writes both the
domain change and an outbox row:
BEGIN;
UPDATE products
SET description = :description,
version = version + 1
WHERE id = :id;
INSERT INTO outbox_events (
event_id,
aggregate_type,
aggregate_id,
event_type,
payload,
created_at
) VALUES (
:event_id,
'Product',
:id,
'ProductUpdated',
:payload,
CURRENT_TIMESTAMP
);
COMMIT;
A separate publisher reads unpublished outbox rows and sends events to
the message broker. After successful publication, it marks the row as
published or records delivery state.
This design ensures that the intent to publish is committed with the
business update. It does not make event delivery exactly-once by itself.
Publishers may send duplicates after a crash, so consumers must be
idempotent. Event ordering may also require partitioning or version
checks.
19.5 Idempotent invalidation consumers
Deleting a cache key is naturally idempotent in the sense that deleting
an already absent key has the same intended result. More complex refresh
consumers must also handle duplicate events safely.
A consumer should be able to process the same ProductUpdated event
more than once without producing incorrect state. Event IDs can support
deduplication, while aggregate versions can prevent older events from
overwriting newer values.
19.6 Read-your-writes requirements
Some user experiences require a user to see their own update
immediately. For example, after editing a profile, the next read should
show the new name.
Possible approaches include:
- Return the committed update result directly rather than immediately
reading through a potentially stale cache. - Evict or update the relevant cache after commit.
- Use a version token so subsequent reads require at least that
version. - Route the follow-up read to an authoritative source for a bounded
period.
The right choice depends on the consistency contract. A user-facing
confirmation should not claim that a change is visible everywhere if
propagation is asynchronous.
20. Redis Deployment, Replication and Cluster Design
20.1 Standalone, primary-replica, and cluster deployments
A standalone Redis instance is operationally simple but can become a
single point of failure and a capacity limit. A primary-replica setup
can improve read availability and support failover, depending on the
deployment. Redis Cluster distributes keys across hash slots and
supports horizontal partitioning.
These deployment modes solve different problems:
- Replication primarily provides copies and failover options.
- Sharding distributes data and load across nodes.
- High availability coordinates detection and promotion after
failures. - Persistence affects recovery after process or host loss.
None of these features automatically makes cache data durable or
strongly consistent. The application must understand the semantics of
the chosen topology.
20.2 Replication lag and stale reads
In primary-replica deployments, writes generally go to the primary while
reads may be served by replicas. Replication is asynchronous in common
configurations, so a replica can temporarily lag behind the primary.
If the application writes a new value and immediately reads from a
lagging replica, it may observe an older value. This is a cache
consistency issue even if the application invalidated its own key
correctly.
For read-after-write requirements, use an appropriate read-routing
policy, version check, or authoritative path. Do not assume that a
successful primary write guarantees immediate visibility on every
replica.
20.3 Redis Cluster and key distribution
Redis Cluster divides the key space into hash slots. Keys are assigned
to slots and slots are distributed among cluster nodes. This allows
horizontal scaling, but it also means multi-key operations have
constraints: keys involved in certain atomic operations may need to
reside in the same hash slot.
Hash tags can force related keys into the same slot:
product:{42}:summary
product:{42}:price
product:{42}:inventory-view
The text inside braces is used for slot calculation. This can help when
an atomic operation must involve multiple related keys. However,
excessive use of one hash tag can create a hot slot and undermine
distribution.
20.4 Failover is not instantaneous
When a primary becomes unavailable, a cluster or managed service must
detect the failure and promote a replica or otherwise restore service.
During this interval, clients may see timeouts, connection resets, or
temporary write failures.
Applications should use bounded timeouts and retry policies appropriate
to the operation. Retrying every failed command indefinitely can worsen
an outage. Cache operations are often safe to retry selectively, but the
client still needs a deadline and an overall retry budget.
20.5 Persistence: RDB and AOF in context
Redis offers persistence mechanisms such as snapshotting (RDB) and
append-only file (AOF) logging. These can help restore data after
restart, but they do not mean that every cache entry must be durable or
that persistence removes all data-loss windows.
For a reconstructible cache, persistence may be less important than
rapid recovery and protection of the source database. For Redis used as
a primary store for acknowledged writes, persistence and replication
choices become much more consequential. The architecture must explicitly
state which data loss is acceptable.
20.6 Connection management
A distributed cache can be fast internally but slow from the
application's perspective if connection management is poor. Common
problems include:
- Creating a new connection for every operation.
- Too many concurrent connections.
- Small pools that queue requests.
- Pools so large that they overwhelm Redis.
- Long socket timeouts that occupy request threads.
- Blocking operations sharing a pool with latency-sensitive commands.
Use a supported client library, configure connection pools based on
measured concurrency, separate blocking workloads where appropriate, and
monitor pool wait time as well as Redis command latency.
21. Serialization, Schema Evolution and Data Contracts
21.1 A cache stores representations, not abstract objects
When an application writes a Java object to Redis, it must serialize
that object into bytes or text. The serialized representation is a data
contract between the writer and every reader that may later consume the
value.
A deployment can change a class while old cache entries remain. A new
application version may then be unable to deserialize values written by
the old version. This can cause runtime failures immediately after a
rolling deployment.
21.2 Choose a deliberate serialization format
Common choices include JSON, binary formats, and language-specific
serialization mechanisms. The choice should consider:
- Human readability and operational debugging.
- Payload size and serialization cost.
- Schema evolution support.
- Cross-language compatibility.
- Type safety and validation.
- Security properties of deserialization.
Language-native object serialization can couple cache contents tightly
to implementation details. For shared or long-lived cache entries, an
explicit schema is often easier to evolve.
21.3 Version the representation
A cache namespace or key can include a schema version:
product-summary:v3:42
When the representation changes incompatibly, the application can move
to a new namespace. Old entries expire naturally or can be removed
gradually.
This avoids requiring every new application instance to understand every
historical object format. The cost is a temporary cold cache during
migration.
21.4 Rolling deployments
During a rolling deployment, old and new application versions may run
simultaneously. If both read and write the same cache key with
incompatible formats, failures can occur even if each version works
independently.
Safer strategies include:
- Use backward-compatible schema changes where possible.
- Introduce a new cache namespace for incompatible representations.
- Deploy readers that can understand both old and new formats before
changing writers. - Avoid destructive cache flushes during peak traffic.
- Observe deserialization errors and miss rates during rollout.
21.5 Cache values should be bounded and intentional
Avoid caching entire ORM entities with lazy relationships, persistence
proxies, or large object graphs. Such objects may serialize
unexpectedly, trigger database access, or couple the cache to internal
persistence details.
Prefer explicit cache DTOs that contain only the fields needed by the
read path. This reduces payload size and makes the representation
contract clearer.
22. Advanced Spring Caching: Semantics and Practical Pitfalls
22.1 Proxy boundaries and self-invocation
Spring's annotation-based caching is usually applied through proxy
interception. A call that enters a bean through its proxy can be
intercepted. A method calling another method on this does not pass
through the proxy in the same way.
For example:
@Service
public class ProductService {
public ProductDto getProduct(String id) {
return loadProduct(id); // self-invocation
}
@Cacheable(cacheNames = "products", key = "#id")
public ProductDto loadProduct(String id) {
// Query repository.
}
}
Depending on proxy configuration, the internal call may bypass caching
advice. A cleaner design is to place the cacheable operation in a
separate injected bean or use CacheManager explicitly.
22.2 Method arguments and SpEL keys
Spring Expression Language (SpEL) can build keys from method arguments
and results. This is convenient, but key expressions should remain
readable and deterministic. If a key depends on an object whose
toString() implementation changes, cache identity may change
unexpectedly.
Prefer explicit stable identifiers and include all response dimensions.
For complex inputs, define a dedicated key object or key generator
rather than constructing a long expression that is difficult to test.
22.3 Null values and negative results
Some cache providers support cached null values; others do not or
require special configuration. Decide whether a not-found result should
be cached. If negative caching is enabled, choose a shorter TTL and
invalidate the negative entry when the record is created.
Do not confuse a null cache lookup (meaning no cache entry) with a
cached null value (meaning the origin result was null). The cache
abstraction may use internal wrappers to distinguish these states.
22.4 Synchronizing cache population
Spring's @Cacheable(sync = true) can request synchronized loading for
a cache operation, but its actual guarantees depend on the cache
provider and implementation. It should not automatically be interpreted
as a cluster-wide distributed lock. Verify provider semantics and test
concurrent misses across multiple application instances.
22.5 Cache eviction timing and transactions
Annotations such as @CacheEvict are convenient, but cache advice and
database transaction advice may have different ordering. If invalidation
must occur after a successful commit, make the ordering explicit and
test rollback behavior.
A robust alternative is to publish a domain event after commit or use an
outbox. The cache update is then eventually consistent, but the event
intent survives process failure.
22.6 Cache abstraction versus direct Redis operations
Use Spring's cache abstraction when the application needs conventional
method-result caching and should remain provider-neutral. Use
RedisTemplate or a dedicated Redis client when the design requires
atomic scripts, leases, sorted-set operations, explicit TTL management,
or custom data structures.
The abstraction is not a reason to force every Redis use case into
@Cacheable. Conversely, direct Redis commands should not be used for
simple method caching without a clear need, because they increase
implementation and testing responsibilities.
23. Quantitative Case Study: Estimating a Cache Design
23.1 Workload assumptions
Assume a catalogue service receives 12,000 read requests per second
during peak periods. Measurements show that:
- 70% of requests target the most popular 10% of products.
- An origin database read averages 18 ms under normal load.
- A Redis hit averages 1.2 ms from the application.
- A typical cached representation occupies 2.5 KB before Redis
overhead. - The catalogue has 2 million active products.
- Product descriptions change infrequently, while prices and inventory
change more often.
These numbers are illustrative. A real design must use production
measurements and include network, serialization, queueing, and database
contention.
23.2 Idealized origin reduction
If the cache achieves a 92% hit ratio, the idealized miss rate is:
[ 12{,}000 \times {=tex}(1 - 0.92) = 960
\text{ origin reads/second}{=tex} ]
The cache would avoid approximately 11,040 origin reads per second
during the measured period.
This does not mean the database load is reduced by exactly 92%. Some
misses may be more expensive than others, background refresh may add
reads, and other endpoints may continue querying the database. It is a
first-order estimate, not a capacity guarantee.
23.3 Idealized latency
Using the simplified model:
[ E[T] = 0.92(1.2) + 0.08(18) = 2.544 \text{ ms}{=tex} ]
The estimate suggests a substantial improvement for this read component.
But the 8% miss path may dominate tail latency. If the application needs
a p99 target, the miss path must be optimized and measured separately.
23.4 Memory estimate
If all 2 million product summaries were cached and each serialized value
were 2.5 KB, the raw value payload would be approximately:
[ 2{,}000{,}000 \times 2.5{=tex} \text{ KB}{=tex} = 5{,}000{,}000
\text{ KB}{=tex} ]
That is roughly 5 GB in decimal units before keys, Redis object
overhead, allocator fragmentation, replication, and buffers. The actual
memory requirement would be higher.
This estimate raises a design question: should every product be cached,
or should the cache hold only the working set? If a relatively small
fraction of products receives most reads, a bounded cache with an
appropriate eviction policy may achieve most of the benefit with much
less memory.
23.5 What the average hides
A 92% hit ratio can still hide a hot-key problem. Suppose one product is
promoted in a campaign and receives 4,000 requests per second. If its
entry expires, all requests may attempt to reload it at once.
The design therefore needs at least one of the following:
- A refresh-ahead policy for known high-traffic products.
- Per-key request coalescing.
- A stale-while-revalidate window for descriptions.
- A carefully bounded local L1 cache.
- Prewarming before a known campaign.
- Origin concurrency limits to protect the database.
The correct choice depends on the freshness requirement and the cost of
a miss.
23.6 Separate data by business semantics
Do not store the entire product page as one cache object if its fields
have different freshness requirements. A product description can be
served from a cache for several minutes, while a displayed price may
need a shorter policy and must be revalidated at checkout. Inventory
reservation should use an authoritative transactional operation.
This may create more keys, but it prevents the cache policy for low-risk
content from weakening the correctness of high-impact business
operations.
24. Operational Playbooks: What to Do When Caching Goes Wrong
24.1 Incident: Redis becomes unavailable
Symptoms may include cache timeouts, connection errors, elevated
endpoint latency, increased database QPS, and rising database
connection-pool utilization.
A disciplined response:
- Confirm whether the issue is Redis, the network, DNS, credentials,
TLS, or application connection management. - Check Redis health, CPU, memory, client connections, replication
state, and failover events. - Determine whether the application is failing open or failing closed.
- Verify that database fallback is bounded by concurrency and rate
limits. - Disable non-essential cache refresh jobs if they add load.
- Protect critical origin paths and shed non-essential work if
necessary. - Restore cache connectivity and observe recovery rather than flushing
the cache immediately. - Record whether the incident exposed an unsafe dependency on cache
availability.
A cache outage should not automatically become a database outage. If it
does, fallback capacity and load shedding were insufficient.
24.2 Incident: Database load spikes after a deployment
Possible causes include a changed cache key, a serialization
incompatibility, an accidentally disabled cache annotation, a namespace
version change, a broad eviction, or a TTL configuration error.
Investigate:
- Cache hit ratio before and after deployment.
- Key cardinality and namespace distribution.
- Deserialization exceptions.
- Redis evictions and memory pressure.
- Application version and cache key changes.
- Database query volume by endpoint.
Do not assume that the database suddenly became slower. The cache may
simply have stopped serving the workload.
24.3 Incident: Users see stale content
First determine which layer serves the stale value: browser, CDN,
reverse proxy, application-local cache, Redis, read replica, or
database.
Trace a specific request through the layers. Compare entity version or
update timestamp at the source and each cache layer. Check invalidation
event delivery, consumer lag, failed events, and TTL behavior.
A global cache flush may appear to fix the issue, but it can create a
stampede and hide the actual invalidation defect. Prefer targeted
invalidation or a versioned namespace change, with capacity protection
in place.
24.4 Incident: Redis memory is exhausted
Check memory usage, fragmentation, key cardinality, object size
distribution, eviction rate, and recent traffic changes. Determine
whether the issue is expected growth, a key leak, unexpectedly large
values, or a workload change.
Avoid immediately increasing memory without understanding the growth
pattern. If keys are being generated with unbounded user-controlled
dimensions, more memory only delays recurrence.
24.5 Cache flush procedure
A full cache flush can create a synchronized miss storm. Before
flushing:
- Estimate origin capacity without cache assistance.
- Identify critical and non-critical endpoints.
- Consider gradual namespace rotation instead of deleting everything
at once. - Prewarm a small set of known hot keys if appropriate.
- Enable origin concurrency limits and load shedding.
- Monitor database latency, connection pools, and cache repopulation.
- Keep a rollback path if the new cache namespace or deployment is
defective.
A cache flush is an operational event, not a harmless cleanup command.
25. Research Questions and Advanced Topics
25.1 Cache coherence and distributed shared memory
Computer architecture has studied cache coherence for decades. CPU
caches need protocols to keep multiple copies of memory lines coherent
across cores. Distributed application caches face a related problem, but
with much longer communication delays, partial failures, independently
deployed services, and business-level data semantics.
The analogy is useful but incomplete. A distributed cache rarely has a
universal hardware-like coherence protocol. Applications choose
invalidation, versioning, leases, event propagation, or bounded
staleness based on business requirements.
25.2 Cache replacement algorithms
LRU and LFU are approximations of future value based on past access.
They are not universally optimal. Workload characteristics such as
scan-heavy access, bursty popularity, and changing key popularity can
make one policy outperform another.
Modern cache systems may use approximations because exact LRU can be
expensive at scale. The important engineering question is not which
algorithm is theoretically elegant, but which policy performs well for
the measured workload and memory budget.
25.3 Admission versus eviction
Eviction decides which existing item should leave when space is needed.
Admission decides whether a newly requested item should enter the cache
at all.
This distinction matters for scan-heavy workloads. If a one-time scan
inserts millions of rarely reused records, it can evict genuinely
popular items. Admission policies can reduce cache pollution by
requiring evidence that a candidate is likely to be reused.
25.4 Cost-aware caching
Not all misses have equal cost. A value that requires a complex
aggregation across many tables may be more valuable to cache than a
cheap indexed lookup, even if both are requested equally often.
A more useful prioritization model considers frequency, origin cost,
object size, update rate, and freshness tolerance. Cache value is an
optimization problem under a memory budget, not simply a ranking by
request count.
25.5 The role of caches in system design
Caching should be considered alongside database indexing, query
optimization, materialized views, denormalization, read replicas,
asynchronous processing, and API design. Sometimes the correct fix is to
remove an expensive query or precompute a view rather than add a cache.
A cache can hide an inefficient query until traffic grows or the cache
is cold. The origin path should remain efficient enough to survive
expected misses and planned cache maintenance.
26. Conclusion: A Cache Is a Consistency Mechanism, Not Just a Performance Trick
Caching can make a system faster, cheaper, and more scalable. But those
benefits are not free. Every cached value introduces another
representation that can become stale, disappear, or behave differently
under load. Every invalidation mechanism creates ordering and failure
questions. Every cache outage changes the traffic pattern seen by the
system of record.
The strongest caching architectures begin with data semantics. They
classify values by freshness requirements, identify the authoritative
source, select an appropriate topology, and choose a pattern that fits
the workload. They use TTL as a bound rather than a substitute for
consistency, handle concurrent misses deliberately, configure memory and
eviction explicitly, and design fallback behavior so that a cache
failure does not become a database failure.
Redis and Spring Boot make implementation accessible. They do not make
the architectural decisions disappear. An annotation such as
@Cacheable can remove repetitive code, but it cannot decide whether
stale prices are acceptable, whether a user-specific response is safe to
share, or how a system should behave when Redis is unavailable.
The engineering objective is not the highest possible hit ratio. It is
the best overall system behavior: predictable latency, controlled origin
load, correct business decisions, bounded staleness, and graceful
degradation.
A well-designed cache is almost invisible to users. They experience a
responsive application. Operators see measurable resource savings.
Developers understand exactly when cached data may be stale and how the
system recovers when the cache fails. That is the standard worth aiming
for.
References and Further Reading
- Microsoft, Cache-Aside Pattern, Azure Architecture Center:
https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside - Microsoft, Caching Guidance, Azure Architecture Center:
https://learn.microsoft.com/en-us/azure/architecture/best-practices/caching - Redis, Key Eviction:
https://redis.io/docs/latest/develop/reference/eviction/ - Redis, Client-Side Caching Introduction:
https://redis.io/docs/latest/develop/clients/client-side-caching/ - Redis, Use Redis with the Spring Cache Abstraction:
https://redis.io/docs/latest/integrate/spring-framework-cache/cache/ - Spring Boot, Caching Reference:
https://docs.spring.io/spring-boot/reference/io/caching.html - Spring Framework, Declarative Annotation-based Caching:
https://docs.spring.io/spring-framework/reference/integration/cache/annotations.html - AWS Builder Center, Caching Challenges and Strategies:
https://builder.aws.com/content/3K9TeXp6strMiJ4vhakpRD7BQWO/caching-challenges-and-strategies - Vattani, A., Chierichetti, F., and Lowenstein, K., Optimal
Probabilistic Cache Stampede Prevention:
https://cseweb.ucsd.edu/\~avattani/papers/cache_stampede.pdf
Implementation note: Code samples are illustrative and should be
adapted to the exact Spring Boot, Spring Data Redis, Redis server,
serializer, transaction, and deployment versions used by a project.
Validate configuration and failure behavior in integration and load
tests before production deployment.




