1

In our multi module project, we have different cache present in different modules. And we fill all these caches on server startup in @PostConstruct. Now some cache depends on some other cache which may present in different modules. So it requires that some cache should be filled before the caches that depends on that cache. 1. How we can do this in Spring? Any design pattern I can leverage? 2. If a cache gets updated how we can propogate this updated change to those caches that depends on updated cache in real time?

module 1---
    Cachce1

module 2--
    Cache2

module 3--
    Cache3

class Cache1 {
  private ConcurrentMap<> cache; 
  @PostConstruct() {
    cache = filleCache();
  }
}
class Cache2 {
  @Autowired
  private Cache1 cache1;
  private ConcurrentMap<> cache; 
  @PostConstruct() {
    cache = cache1;
  }
}
class Cache3 {
  @Autowired
  private Cache2 cache2;
  private ConcurrentMap<> cache; 
  @PostConstruct() {
    cache = cache2;
  }
}
Avinash Kharche
  • 411
  • 9
  • 25

1 Answers1

0

Dependencies: The initialization order is usually done correctly by the DI framework. So Cache2 post construct is run after Cache1 is completely initialized. If you cache only a full set of data in a CuncurrentMap you could use memoization instead, see https://dzone.com/articles/need-micro-caching-memoization

Avoid cache stacking. Sometimes its simpler to avoid caching in intermediate layers. A simple approach is to cache where the data comes in, e.g. the persistence layer, and then cache where the data goes out, e.g. response snippets or complete responses. Since the complete data is cached in the top-most cache anyways, the intermediate caches might not get any hits either.

This heavily depends on the kind of data and how often its used on the next layer.

how we can propagate this updated change?

You have a range of options. In case module1 knows about its dependencies you can call a reload of module2 and 3. If module1 code should not depend on its clients, then use a event listener pattern. Depending where your data comes from, there are already existing mechanisms. Look for Spring Data events, Change Data Capture capabilities of your database, Triggers of your database or persistence layer.

You can keep things simple by using an expiry on the cache entry and simply update/reload your data after a period of time. However, expiry and cache stacking is a problem by itself. In case you use a fixed expiry of 5 minutes, the effective expiry adds up each layer. So for three layers, data maybe refreshed after 5 or 15 minutes. To avoid this, we propagate a point of time when expiry should happen together with the data through the caching layers.

cruftex
  • 5,545
  • 2
  • 20
  • 36