Sub topic 13
Handling concurrent misses with sync=true
This chapter assumes you can use @Cacheable, know how cache keys are built, and have a cache provider such as Caffeine or Redis configured. You should also know that Spring applies caching through a proxy. Here you will see what happens when many threads miss the same key at once, how sync = true addresses it, and where it stops helping.
The problem: a cache stampede
A cache miss on a cold or just-expired key is cheap for one caller. It is expensive when many callers arrive together. Suppose a popular exchange rate expires and 200 requests ask for it in the same moment. Each request checks the cache, finds nothing, and runs the slow method. The database or remote service receives 200 identical calls, which is the load the cache was meant to prevent. This pattern is called a cache stampede (also a thundering herd).
By default @Cacheable does not prevent this. The sequence is "look up, and if absent, call the method, then store the result". That sequence is not atomic across threads, so several threads can all pass the "absent" check before any of them stores a value.
Turning on synchronization
Set sync = true on @Cacheable:
package com.example.shop;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ExchangeRateService {
private final AtomicInteger loads = new AtomicInteger();
@Cacheable(cacheNames = "rates", key = "#currency", sync = true)
public String rateFor(String currency) {
loads.incrementAndGet();
try {
Thread.sleep(300); // simulate a slow remote call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
return currency + ":1.08";
}
public int loadCount() {
return loads.get();
}
}With this flag, the caching interceptor stops using the separate "get, then put" steps. It calls the cache's get(key, Callable) method and passes the method invocation as the loader. The cache implementation decides how to run the loader safely. A thread that finds the key missing runs the loader. Other threads asking for the same key block until the value is stored, then return it.
What happens inside the provider
The guarantee comes from the cache library, so its strength varies by provider.
| Provider | How `get(key, loader)` synchronizes | Scope of the guarantee |
|---|---|---|
| Caffeine | Uses the library's atomic per-key compute, so only one loader runs for a key | One JVM |
| `ConcurrentMapCache` (default) | Uses an atomic compute on a `ConcurrentHashMap` | One JVM |
| Redis (`RedisCache`) | Takes a lock inside the `RedisCache` object in the application | One JVM, not across instances |
The Redis row is the one that surprises people. If you run five instances of your service behind a load balancer, sync = true allows one load per instance at most. Instances do not coordinate with each other. Five loads is far better than 200, but it is not one. For a strict single load across a cluster you need a distributed lock or a different design. The Spring annotation does not provide one.
Verifying the behavior with a test
A concurrency test releases many threads at once against a cleared cache and counts how often the loader ran. This test uses the service above and needs @EnableCaching on the application class, as in the earlier chapters.
package com.example.shop;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
@SpringBootTest
class ExchangeRateServiceSyncTest {
@Autowired
ExchangeRateService service;
@Autowired
CacheManager cacheManager;
@Test
void concurrentMissesLoadOnce() throws Exception {
cacheManager.getCache("rates").clear();
int before = service.loadCount();
int threads = 20;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
List<Future<String>> results = new ArrayList<>();
for (int i = 0; i < threads; i++) {
results.add(pool.submit(() -> {
start.await();
return service.rateFor("EUR");
}));
}
start.countDown();
for (Future<String> result : results) {
assertThat(result.get()).isEqualTo("EUR:1.08");
}
pool.shutdown();
assertThat(service.loadCount() - before).isEqualTo(1);
}
}Remove sync = true and run the test again. With a 300 ms loader and 20 threads released together, the count will normally be well above 1. Because this depends on timing, it shows the trend and is not a guaranteed failure.
Restrictions on sync=true
Synchronized loading changes how the interceptor runs, so Spring limits what you can combine with it. Spring checks these rules when it validates the cache operations, and a violation throws an IllegalStateException at startup.
- One cache only.
cacheNamesmust name a single cache. - No other cache operations on the method. You cannot stack
@CachePutor@CacheEvicton a method that usessync = true. - No
unless. The condition is evaluated against the result after the method returns, and a synchronized load stores the value inside the loader. This conflicts with theunless = "#result == null"pattern used earlier in this tutorial. Dropunlesson synchronized methods. conditionis allowed. It is evaluated before the lookup, so it still works. If it is false, the call skips the cache and the synchronization.
Check the Javadoc of your Spring Framework version, because these rules have been refined across releases.
Costs of synchronization
Blocking is the price. Waiting threads hold a request thread, and if the loader is slow or hangs, every caller for that key hangs with it. Three habits reduce the risk:
- Give the loader its own timeout. Set connect and read timeouts on the HTTP client or query so a stuck load fails and releases the waiters.
- Keep the loader small. Synchronization is per key in Caffeine, so loads of different keys proceed in parallel. In Redis the lock is on the cache object, so a slow load of one key can delay loads of other keys in the same cache on that instance. Splitting very slow data into its own named cache limits this.
- Don't add
sync = trueeverywhere. For cheap methods the blocking adds more cost than the duplicate calls it prevents. Use it where a miss is expensive and many callers ask for the same key.
Other defenses against stampedes
sync = true handles misses on a single instance. It does not remove the other causes of a stampede.
- Synchronized expiry. If you warm a thousand keys at startup with the same TTL, they all expire together. Add random jitter to expirations, or warm the keys gradually.
- Refresh before expiry. Caffeine's
refreshAfterWritereloads a hot entry in the background while callers keep receiving the old value. Spring's annotation-driven setup does not expose this directly, so it needs aLoadingCacheconfigured in code. - Cross-instance coordination. If one load per cluster matters, use a distributed lock such as one built on Redis, or put a rate limit in front of the backing service.
Summary table
| Setting | Concurrent misses on one key | Notes |
|---|---|---|
| `@Cacheable` | Each thread may run the method | Default behavior, no blocking |
| `@Cacheable(sync = true)` | One load per JVM, others wait | One cache, no `unless`, no combined operations |
| `sync = true` with Redis on N instances | Up to N loads | The lock is not shared between instances |
Exercise
A service runs on four instances using a Redis-backed cache. A method is annotated with @Cacheable(cacheNames = "rates", sync = true). A hot key expires and 100 requests arrive at the same moment, spread evenly across the instances. How many times can the underlying method run, and why?
Show answer
Up to four times, one per instance. With Redis, sync = true locks inside the RedisCache object in each JVM, so each instance lets one thread load while its other threads wait. The instances do not coordinate with each other. Strict single loading across the cluster needs a distributed lock.
Exercise
You add sync = true to a method that already has @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null", sync = true). What happens when the application starts, and how do you fix it?
Show answer
Spring rejects the configuration with an IllegalStateException, because a sync = true operation does not support unless. Remove unless. Then make sure the method never returns null, or that your cache provider handles null values, since the null check can no longer be done through the annotation.