Browser docs

Caching

Intent

The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again.

Explanation

Real world example

A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each time a post is viewed becomes expensive and it’s a good idea to utilize caching here.

In plain words

Caching pattern keeps frequently needed data in fast-access storage to improve performance.

Wikipedia says:

In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests that can be served from the cache, the faster the system performs.

Programmatic Example

Let’s first look at the data layer of our application. The interesting classes are UserAccount which is a simple Java object containing the user account details, and DbManager interface which handles reading and writing of these objects to/from database.

 1@Data
 2@AllArgsConstructor
 3@ToString
 4@EqualsAndHashCode
 5public class UserAccount {
 6  private String userId;
 7  private String userName;
 8  private String additionalInfo;
 9}
10
11public interface DbManager {
12
13  void connect();
14  void disconnect();
15  
16  UserAccount readFromDb(String userId);
17  UserAccount writeToDb(UserAccount userAccount);
18  UserAccount updateDb(UserAccount userAccount);
19  UserAccount upsertDb(UserAccount userAccount);
20}

In the example, we are demonstrating various different caching policies

  • Write-through writes data to the cache and DB in a single transaction
  • Write-around writes data immediately into the DB instead of the cache
  • Write-behind writes data into the cache initially whilst the data is only written into the DB when the cache is full
  • Cache-aside pushes the responsibility of keeping the data synchronized in both data sources to the application itself
  • Read-through strategy is also included in the aforementioned strategies and it returns data from the cache to the caller if it exists, otherwise queries from DB and stores it into the cache for future use.

The cache implementation in LruCache is a hash table accompanied by a doubly linked-list. The linked-list helps in capturing and maintaining the LRU data in the cache. When data is queried (from the cache), added (to the cache), or updated, the data is moved to the front of the list to depict itself as the most-recently-used data. The LRU data is always at the end of the list.

 1@Slf4j
 2public class LruCache {
 3
 4  static class Node {
 5    String userId;
 6    UserAccount userAccount;
 7    Node previous;
 8    Node next;
 9
10    public Node(String userId, UserAccount userAccount) {
11      this.userId = userId;
12      this.userAccount = userAccount;
13    }
14  }
15  
16  /* ... omitted details ... */
17
18  public LruCache(int capacity) {
19    this.capacity = capacity;
20  }
21
22  public UserAccount get(String userId) {
23    if (cache.containsKey(userId)) {
24      var node = cache.get(userId);
25      remove(node);
26      setHead(node);
27      return node.userAccount;
28    }
29    return null;
30  }
31
32  public void set(String userId, UserAccount userAccount) {
33    if (cache.containsKey(userId)) {
34      var old = cache.get(userId);
35      old.userAccount = userAccount;
36      remove(old);
37      setHead(old);
38    } else {
39      var newNode = new Node(userId, userAccount);
40      if (cache.size() >= capacity) {
41        LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId);
42        cache.remove(end.userId); // remove LRU data from cache.
43        remove(end);
44        setHead(newNode);
45      } else {
46        setHead(newNode);
47      }
48      cache.put(userId, newNode);
49    }
50  }
51
52  public boolean contains(String userId) {
53    return cache.containsKey(userId);
54  }
55  
56  public void remove(Node node) { /* ... */ }
57  public void setHead(Node node) { /* ... */ }
58  public void invalidate(String userId) { /* ... */ }
59  public boolean isFull() { /* ... */ }
60  public UserAccount getLruData() { /* ... */ }
61  public void clear() { /* ... */ }
62  public List<UserAccount> getCacheDataInListForm() { /* ... */ }
63  public void setCapacity(int newCapacity) { /* ... */ }
64}

The next layer we are going to look at is CacheStore which implements the different caching strategies.

 1@Slf4j
 2public class CacheStore {
 3
 4  private static final int CAPACITY = 3;
 5  private static LruCache cache;
 6  private final DbManager dbManager;
 7
 8  /* ... details omitted ... */
 9
10  public UserAccount readThrough(final String userId) {
11    if (cache.contains(userId)) {
12      LOGGER.info("# Found in Cache!");
13      return cache.get(userId);
14    }
15    LOGGER.info("# Not found in cache! Go to DB!!");
16    UserAccount userAccount = dbManager.readFromDb(userId);
17    cache.set(userId, userAccount);
18    return userAccount;
19  }
20
21  public void writeThrough(final UserAccount userAccount) {
22    if (cache.contains(userAccount.getUserId())) {
23      dbManager.updateDb(userAccount);
24    } else {
25      dbManager.writeToDb(userAccount);
26    }
27    cache.set(userAccount.getUserId(), userAccount);
28  }
29
30  public void writeAround(final UserAccount userAccount) {
31    if (cache.contains(userAccount.getUserId())) {
32      dbManager.updateDb(userAccount);
33      // Cache data has been updated -- remove older
34      cache.invalidate(userAccount.getUserId());
35      // version from cache.
36    } else {
37      dbManager.writeToDb(userAccount);
38    }
39  }
40
41  public static void clearCache() {
42    if (cache != null) {
43      cache.clear();
44    }
45  }
46
47  public static void flushCache() {
48    LOGGER.info("# flushCache...");
49    Optional.ofNullable(cache)
50        .map(LruCache::getCacheDataInListForm)
51        .orElse(List.of())
52        .forEach(DbManager::updateDb);
53  }
54
55  /* ... omitted the implementation of other caching strategies ... */
56
57}

AppManager helps to bridge the gap in communication between the main class and the application’s back-end. DB connection is initialized through this class. The chosen caching strategy/policy is also initialized here. Before the cache can be used, the size of the cache has to be set. Depending on the chosen caching policy, AppManager will call the appropriate function in the CacheStore class.

 1@Slf4j
 2public final class AppManager {
 3
 4  private static CachingPolicy cachingPolicy;
 5  private final DbManager dbManager;
 6  private final CacheStore cacheStore;
 7
 8  private AppManager() {
 9  }
10
11  public void initDb() { /* ... */ }
12
13  public static void initCachingPolicy(CachingPolicy policy) { /* ... */ }
14
15  public static void initCacheCapacity(int capacity) { /* ... */ }
16
17  public UserAccount find(final String userId) {
18    LOGGER.info("Trying to find {} in cache", userId);
19    if (cachingPolicy == CachingPolicy.THROUGH
20            || cachingPolicy == CachingPolicy.AROUND) {
21      return cacheStore.readThrough(userId);
22    } else if (cachingPolicy == CachingPolicy.BEHIND) {
23      return cacheStore.readThroughWithWriteBackPolicy(userId);
24    } else if (cachingPolicy == CachingPolicy.ASIDE) {
25      return findAside(userId);
26    }
27    return null;
28  }
29
30  public void save(final UserAccount userAccount) {
31    LOGGER.info("Save record!");
32    if (cachingPolicy == CachingPolicy.THROUGH) {
33      cacheStore.writeThrough(userAccount);
34    } else if (cachingPolicy == CachingPolicy.AROUND) {
35      cacheStore.writeAround(userAccount);
36    } else if (cachingPolicy == CachingPolicy.BEHIND) {
37      cacheStore.writeBehind(userAccount);
38    } else if (cachingPolicy == CachingPolicy.ASIDE) {
39      saveAside(userAccount);
40    }
41  }
42
43  public static String printCacheContent() {
44    return CacheStore.print();
45  }
46
47  /* ... details omitted ... */
48}

Here is what we do in the main class of the application.

 1@Slf4j
 2public class App {
 3
 4  public static void main(final String[] args) {
 5    boolean isDbMongo = isDbMongo(args);
 6    if(isDbMongo){
 7      LOGGER.info("Using the Mongo database engine to run the application.");
 8    } else {
 9      LOGGER.info("Using the 'in Memory' database to run the application.");
10    }
11    App app = new App(isDbMongo);
12    app.useReadAndWriteThroughStrategy();
13    String splitLine = "==============================================";
14    LOGGER.info(splitLine);
15    app.useReadThroughAndWriteAroundStrategy();
16    LOGGER.info(splitLine);
17    app.useReadThroughAndWriteBehindStrategy();
18    LOGGER.info(splitLine);
19    app.useCacheAsideStategy();
20    LOGGER.info(splitLine);
21  }
22
23  public void useReadAndWriteThroughStrategy() {
24    LOGGER.info("# CachingPolicy.THROUGH");
25    appManager.initCachingPolicy(CachingPolicy.THROUGH);
26
27    var userAccount1 = new UserAccount("001", "John", "He is a boy.");
28
29    appManager.save(userAccount1);
30    LOGGER.info(appManager.printCacheContent());
31    appManager.find("001");
32    appManager.find("001");
33  }
34
35  public void useReadThroughAndWriteAroundStrategy() { /* ... */ }
36
37  public void useReadThroughAndWriteBehindStrategy() { /* ... */ }
38
39  public void useCacheAsideStategy() { /* ... */ }
40}

Class diagram

alt text

Applicability

Use the Caching pattern(s) when

  • Repetitious acquisition, initialization, and release of the same resource cause unnecessary performance overhead.

Credits