Cache — Why, When and How

Solomon Adir
2 min readJan 30, 2021

Introduction

Have you ever asked yourself, is there any way to make your system work fast when we need to take in mind that we pull data from any database server?

We have a solution for it, it called cache.

Why?

We use cache service because of its data organize structure. The data are stored with key to value structure (Hashmap). That is why the pulling data is faster, if you know the key, you are going straight to his value.

When?

This is an important question. First we need to understand that cache is a replacement for data pulled with queries, but it isn’t a live data. Therefore, we won’t make authentication with cache as authenticate username and password. We’ll use cache as replacement when we need to pull data several times but the data isn’t change on the several times we pull it, like getting user info data.

How?

This is the big question, how we supposed to use cache in our system. Here are some important principles that you should listen to.

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.

Example

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

Now on my code, I’ll use the cached repository. Then when I’ll try to pull the user data, it will first check on the cache service if there data on this id and if not it will query the database.

--

--

Solomon Adir
0 Followers

Backend developer and researches security weaknesses