Cache — Why, When and How





Where to write:

Because cache is replacement for database for some queries, the cache should be a layer before the query. I recommend using Repository Design Pattern, making a cached layer and if the key isn’t exists, then making the query, store on cache and then return the data.

Cache keys:

You should use unique keys for each data you are pulling. The key must not be overwritten by any other part of code and should implement all the changed data. for example, when pulling user’s orders, we should use a key like ‘user_{id}_orders’, but if pulling user’s orders for Jan so using a key like ‘user_{id}_jan_orders’.

Cache time

You should decide how much time is this data is relevant. We should remember that cache storage is lower from database storage, therefor keep the data when it is relevant for some time and not forever.

Clear cache on changes

You should remember to delete the old data stored on cache service on some changes that reflect the reliability of the data.


I’ll create user repository that returns user by id
Then I’ll create another user repository, but a cached one that extends this user repository



Full Stack Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store