preface

As a backend developer, when it comes to Redis or caching, whether it’s in the workplace or in an interview, the absolute no-no is cache penetration. This article focuses on why cache penetration occurs. This article uses Redis as an example of caching, the rest of the intermediate valence, the solution idea is the same, individual apis may not be consistent.

The reasons causing

The first case of cache penetration, Redis must be used as a cache, not as a database, if the data is used, there is no such problem.

Here’s an example of a nuggets raffle.

Let’s assume that the data from the crowd prize can be placed in the cache to reduce database stress. This data is returned from the cached list if the user requests it.

There is a problem with this. Since it is a cache, it must have an expiration date. At this time, there happens to be a large amount of traffic to request this interface, then there is no cache at this time, and finally it will request the database to obtain data, so this phenomenon is called cache penetration.

The solution

So at this point one might think, well, since the problem is due to expiration time. Well, I guess it’s okay not to give him an expiration date. If this is the case in business, that is fine. However, there is a problem, if the background data is updated, how to update the cache in Redis. Also, if the cache is too large, is it taking up too much Redis space? This method is not recommended.

So how do you do that? Let’s start with a picture

The general logic of the business goes like this. We just need to make a few changes to the business code in this section.

I have posted the points to be changed in the picture, and explained them in detail.

  1. The first step is to get the data from Redis
  2. Step 2 If I get null in redis, I’m doing setnx(lock, true)
    • First of all, let’s talk about what setnx means, set if not exists.
    • Someone has already searched the database, so you can wait there. I’ll put it back in when I find it.
  3. The third step is to query the database, put it in cache, cancel the lock setting, and then return to the front end.

Topics extend

Here is an interactive question, which I mentioned in the article above, if the database is updated, how to update the cache to ensure consistency.

Welcome to the comments section if you have a good solution. This article is relatively simple, so let’s do it first.

All saw this, don’t point a praise to walk again 🤪