Caching
Why we should cache??
1) Reduce network calls. (Store data in cache and return that data to user instead to hit the DB)
2) Avoid repeated computations. (Suppose we want average age of employees, its a costly operation, we should store it in cache)
3) Reduce DB load.
4) Increase the response time.
Cache Policy - When I have to add data ad when we have to evict the data.
1) We can't store all the requests in Cache, we have to predict which requests we have to save and they can come again in future.
2) For eviction we can use any cache eviction policy according to our need.
Cache Eviction Algorithms
1) Least Recently Used (LRU)
2) Least Frequently Used (LFU)
3) First In First Out (FIFO) (Sliding Window)
LRU
- When the request is received by the server/app, the app checks for the data in the cache. If the data is there in the cache, it’s a cache hit and served from the cache.
- If the data is not available in the cache, then it’s a cache miss.
- The app fetches the data from the database and updates the cache with the fetched data.
In this strategy, the cache has a writer component that can write to database.
- The application receives request to write data to database.
- The application writes the data to the cache.
- The cache invokes the writer to write to database as well as update the cache.
The cache is configured with a loader component that loads data from the database.
- When the application receives the read request, it asks the cache for data associated with the key.
- If there is a cache hit, then the data is served from the cache.
- If there is a cache miss, then the cache invokes the loader that fetches the data from the database, updates the cache, and serves the fetched data.
- The next time there is a read request for the same data, it’s served from the cache.
- The app writes data to the cache and receives an immediate acknowledgement that the write is successful.
- The cache internally maintains a buffer to save the writes.
- The cache asynchronously writes the data from the buffer to the database at a later point in time.
Comments
Post a Comment