Applications use a cache to optimize repeated access to information held in a data store. However, it is usually impractical to expect that cached data will always be completely consistent with the data in the data store. Applications should implement a strategy that helps to ensure that the data in the cache is up to date as far as possible, but can also detect and handle situations that arise when the data in the cache has become stale.
An application retrieves data by referencing the cache. If the data is not in the cache, it is transparently retrieved from the data store and added to the cache. Any modifications to data held in the cache are automatically written back to the data store
An application can emulate the functionality of read-through caching by implementing the cache-aside strategy.
Using the Cache-Aside pattern to store data in the cache
If an application updates information, it can emulate the write-through strategy as follows:
When the item is next required, using the cache-aside strategy will cause the updated data to be retrieved from the data store and added back into the cache.
Lifetime of Cached Data. Many caches implement an expiration policy that causes data to be invalidated and removed from the cache if it is not accessed for a specified period.
Evicting Data. Most caches have only a limited size compared to the data store from where the data originates, and they will evict data if necessary. Most caches adopt a least-recently-used policy for selecting items to evict, but this may be customizable.
Priming the Cache. Many solutions prepopulate the cache with the data that an application is likely to need as part of the startup processing.
Consistency. Implementing the Cache-Aside pattern does not guarantee consistency between the data store and the cache.
Local (In-Memory) Caching. A cache could be local to an application instance and stored in-memory. Cache-aside can be useful in this environment if an application repeatedly accesses the same data. However, a local cache is private and so different application instances could each have a copy of the same cached data. This data could quickly become inconsistent between caches, so it may be necessary to expire data held in a private cache and refresh it more frequently.
Use this pattern when:
This pattern might not be suitable: