Every time you open a amazon product or you refresh the same page, do you think that amazon sends a request to the database again. If millions of people are looking at the same product wouldn't that mean 1,000+ database queries and that's extremely expensive. So how do big companies avoid that? There's something called REDIS. REDIS is an in-memory cache, an in-memory cache simply means it stores data on RAM instead of disk cache cause RAM is much faster. REDIS can return data in just a few milliseconds but here's is the most interesting part REDIS doesn't just magically know what data to store and that's where a cache strategy known as a CACHE ASIDE comes in. A user request product 15 and the application ask REDISs, do you have product 15 REDIS says no. This is something known as CACHE MISS, simply means the requested data is not in the CACHE so the application goes to the database and finds product 15 it turns it to the application. Now here's the clever part before sending the product back to the user the application first stores a copy inside REDIS this is called POPULATING THE CACHE now REDIS remembers product 15 and finally the application sends back the product to the user a few seconds later another user requests product 15 again the application asks REDIS and this time REDIS replies product 15 is there. This is called CACHE HIT, it simply means that the requested data is in the cache so the application returns the product immediately and the database is never touched and that is why cache responses are so much faster.
Now let's imagine the product price changes from maybe 999 to 899 but remember the cache stills remember the former price. The cache contains stale data, Stale data simply means that the cache has outdated information. To fix this after updating the database the application deletes the product from REDIS and this is called CACHE INVALIDATION not because the data was bad but simply because it was incorrect data so now when another customer comes in and requests product 15, the application ask REDIS but remember the product was deleted so what will REDIS say, i don't have this product another cache miss so what does the application do, the application goes to the database because the product is unavailable here and then it goes to the database it finds the updated product 15 with the updated price so now it stores a copy in REDIS and then sends a response back to the user with the updated price. From that point on everybody receives the latest data directly from REDIS and remember REDIS is at the CACHE, CACHE aside is the cashing strategy. There are several caching strategies, CACHE aside is just one of the most common but it's not the only one.
Next time we'll explore different caching strategies and why CACHE aside is not used by some companies at all
Top comments (0)