loading...

How is usually consistency maintained between DB and cache?

ngomandat profile image Ngo Man Dat ・1 min read

Say I have some documents in MongoDB and have cached a couple of fields in redis. If I were to update some value in both the DB and cache, I would like either both of them to succeed or both of them to fail. How is this problem generally handled?

If both the updates were to happen within MongoDB, I would use transactions. But, I presume that is not possible across two systems like MongoDB & redis.

Discussion

markdown guide
 

I think you can do it on the application level if you want. You can start a transaction of MongoDB in a session, and update data inside mongo, in the same context, update the redis cache too. If that's successful, commit the transaction, else rollback.

 

I would like either both of them to succeed or both of them to fail. How is this problem generally handled?

What do you mean?

I'd imagine the source of truth is MongoDB, and I'd imagine Redis is on top of MongoDB.

So, if the key has an expiration date, when it's expired you can ask MongoDB to give you the updated data.

During write you can write in MongoDB and invalidate the cached key so that the next read from Redis will fill the value from MongoDB.

Let me know if it makes sense or not :)