Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would Redis get to know if it has to return cached data or fresh data from DB

Say, I'm Fechting thousands or record using some long runing task from DB and caching it using Redis. Next day somebody have changed few records in DB.

Next time how redis would know that it has to return cached data or again have to revisit that all thousands of records in DB?

How this synchronisation achived?

like image 597
Swapnil Kotwal Avatar asked Mar 15 '18 12:03

Swapnil Kotwal


2 Answers

Redis has no idea whether the data in DB has been updated.

Normally, we use Redis to cache data as follows:

  1. Client checks if the data, e.g. key-value pair, exists in Redis.
  2. If the key exists, client gets the corresponding value from Redis.
  3. Otherwise, it gets data from DB, and sets it to Redis. Also client sets an expiration, say 5 minutes, for the key-value pair in Redis.
  4. Then any subsequent requests for the same key will be served by Redis. Although the data in Redis might be out-of-date.
  5. However, after 5 minutes, this key will be removed from Redis automatically.
  6. Go to step 1.

So in order to keep your data in Redis update-to-date, you can set a short expiration time. However, your DB has to serve lots of requests.

If you want to largely decrease requests to DB, you can set a large expiration time. So that, most of time, Redis can serve the requests with possible staled data.

You should consider carefully about the trade-off between performance and staled data.

like image 183
for_stack Avatar answered Oct 22 '22 23:10

for_stack


My solution is:

When you are updating, deleting or adding new data in database, you should delete all data in redis. In your get route, you should check if data exists. If not, you should store all data to redis from db.

like image 20
Adham Muzaffarov Avatar answered Oct 22 '22 22:10

Adham Muzaffarov