Cache-Aside is a common pattern in modern cloud applications. This is a very simple and a straight forward one. The followings are the characteristics of the pattern.
- When an application needs data, first it looks in the cache.
- If the data available in the cache, then application will use the data from the cache, otherwise data is retrieved from the data store and the cache entry will be updated.
- When the application writes the data, first it writes to the data store and invalidates the cache.
How to handle the lookups and other properties and events of the cache are independent, meaning the patters does not enforce any rules on that. These diagrams summarize the idea.
- Application checks the cache for the data, if the data in the cache it gets it from the cache.
- If the data is not available in the cache application looks for the data in the data store.
- Then the application updates the cache with the retrieved data.
- Application writes the data to the data store.
- Sends the invalidate request to the cache.
Implementation
Project : https://github.com/thuru/CloudPatterns/tree/master/CloudPatterns/CacheAsidePatternWebTemplate
The above project has an implementation of this pattern.
Data objects implement an interface ICacheable and an abstract class CacheProvider<ICacheable> has the abstract implementation of the cache provider. You can implement any cache provider by extending CacheProvider<ICacheable>. GitHub sample contains code for the Azure Redis and AWS Elastic Cache implementations.
Implementation of ICacheable : https://github.com/thuru/CloudPatterns/blob/master/CloudPatterns/CacheAsidePatternWebTemplate/Cache/ICacheable.cs
Implementation of CacheProvider<ICacheable>: https://github.com/thuru/CloudPatterns/blob/master/CloudPatterns/CacheAsidePatternWebTemplate/Cache/CacheProvider.cs
Implementation of AzureRedisCacheProvider : https://github.com/thuru/CloudPatterns/blob/master/CloudPatterns/CacheAsidePatternWebTemplate/Cache/AzureRedisCacheProvider.cs
The template also includes Cache Priming in Global.asax. This could be used to prime your cache (loading the mostly accessed data in the application start)
Pingback: Advanced Caching Techniques | Thuru's Blog