What are different cache write strategy?
What is Write-through cache strategy?
In this strategy, data is first written to the cache and then to the database. Response is sent back to client only when data is written to both cache and database.
- Risk of data loss is minimum as write operation must be done twice before returning success to the client.
- Data is consistent between cache and storage as same data is written to cache and database.
- This scheme ensures that nothing will get lost in case of a crash, power failure, or other system disruptions.
- When paired with read-through caches, we get all the benefits of read-through and we also get data consistency guarantee, freeing us from using cache invalidation techniques.
- Higher latency for write operations as data is written twice to cache and database.
Example: DynamoDB Accelerator (DAX) is a good example of read-through and write-through cache. It sits inline with DynamoDB and your application. Reads and writes to DynamoDB can be done through DAX.
What is Write-Around cache strategy?
As per this strategy, data is written directly to the database instead of the cache.
- Reduce the cache being flooded with data that will not be re-read.
- Read request for recently written data will create a “cache miss” and must be read from slower back-end storage (database), and can cause higher latency.
What is Write-Back cache strategy?
In this strategy, data is written to cache only and call is returned to client.
Data from cache is written to database after some time based on configuration (after specific objects are collected in cache to be written or specific time interval).
- Low latency and high throughput for write operations.
- Risk of data loss in case of a crash or other adverse event because the only copy of the written data is in the cache.
How to take care of situation where data is updated in database but cache is not updated?
In such cases, developers use TTL (time to live) with cache. Cache continues to serve stale data until TTL expires