A local synchronized cache loader and Redis writer settings do not automatically create one cross-instance computation.
Spring Redis cache writer: compound operations and replica stampedes
Name the race
During a catalog refresh, six replicas miss the same key. Each may call the catalog database before any replica writes its result. A synchronized loader may coordinate callers inside one process, but it is not a distributed single-flight guarantee. Spring Data Redis's usual non-locking cache writer also allows multi-command put-if-absent and clear sequences to overlap. Its optional locking writer locks a cache region, not one key, so a busy cache can serialize unrelated work.
Choose the real consistency requirement
For an expensive but repeatable read, accept bounded duplicate work and size the backing service for a burst. Add TTL jitter or prewarming where a synchronized expiry causes load spikes. For a correctness-critical mutation, a cache is the wrong lock; use a database uniqueness or transaction rule. Versioned keys and targeted eviction reduce wide clears.
Bound a clear
A region clear can scan many keys. The default KEYS-based strategy can stall a large Redis keyspace; an SCAN-based batch strategy is available with a compatible driver, including Lettuce. Measure clear duration and Redis latency on realistic cardinality before using it in a request path. This lesson does not claim a measured cache-cluster result.
Implementation sketch
RedisCacheManager manager = RedisCacheManager.builder(
RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory))
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(47)))
.build();Cost and verification
Duplicate loads scale with concurrent misses. A cache-wide writer lock trades that race for latency across unrelated keys; bulk clear cost grows with keyspace size and Redis scan behavior.
Common Mistakes
- Do not treat sync=true as a distributed mutex across replicas.
- Do not use cache locks as a substitute for a database invariant.
- Do not run unmeasured region-wide clears on a large shared Redis instance.
Read next
Spring @Cacheable sync: collapse a local same-key cache miss, Spring cache eviction: invalidate the same tenant key used by the read, Spring Redis cache key schema: tenant, prefix and rollout version, Spring Session Redis across replicas: shared login state has a Redis failure boundary.
