This is the 7th day of my participation in the August Text Challenge.More challenges in August

Let me briefly explain my understanding of these three cache read and write strategies.

In addition, each of the three cache read and write strategies has its own advantages and disadvantages, and there is no optimal one. Therefore, we need to choose a more suitable one based on specific business scenarios.

Personal ability is limited. If there is anything that needs to be added/improved/modified, please feel free to point it out in the comments section and make progress together! — Love your Guide brother

Cache Aside Pattern

Cache Aside Pattern is a Cache read/write Pattern that we usually use. It is suitable for scenarios with a lot of read requests.

In Cache Aside Pattern, the server needs to maintain both the DB and the Cache, and the result is based on the DB.

Let’s take a look at the cache read and write steps in this policy pattern.

Write:

  • To update the DB
  • Then delete the cache directly.

I’ve drawn a little diagram to help you understand what I’m doing.

Read:

  • Reads data from the cache and returns it
  • If the data cannot be read from cache, it is read from DB and returned
  • The data is then stored in the cache.

I drew a simple picture to help you understand the steps of reading.

It’s not enough for you to just know the above, we need to understand how it works.

For example, the interviewer may ask, “Can I delete the cache before updating the DB?”

Answer: That’s definitely not possible! Because this may cause database (DB) and Cache data inconsistency problem. Why is that? For example, if request 1 writes data A first and request 2 reads data A later, data inconsistency is likely to occur. The process can be simply described as:

Request 1: delete data from cache (A); request 2: update data from DB (A);

When you answer this question, the interviewer will probably follow up with the following question: “Is it ok to update the DATABASE and then delete the cache while writing data?”

Answer: It is theoretically possible to have data inconsistencies, but it is very unlikely because the cache writes much faster than the database!

For example, request 1 reads data A first, request 2 writes data A later, and data A is not in the cache may also cause data inconsistency problems. The process can be simply described as:

Request 1 reads data from DB (A) and writes data to database (B). Request 2 writes data to cache (A).