Search code examples
c#redisstackexchange.redis

How do you sync data stored in redis with what's in the database?


Provided I load a user data from my database to redis. Say 5 secs have gone by, and the user information in the database has been updated.

What's the best way to check if the data in redis is out of sync? Do you periodically call database and check if you have same data as what's stored in the database? or do you check when you are about to commit some data to the database?

I am using stackexchange.redis as client, if that makes any difference.


Solution

  • The answer to your question depends on software architecture and the style, your application works.

    If you have only one application with one component (the monolith-way), the data sync should happen within the application. The User is updated through the application, and the record is written to the database and in Redis.

    If you have multiple applications/components (the microservice-way), this get's a bit harder. One application updates the user information in the database, but the other applications do not know. So you either:

    • invalidate the data in Redis, so the next application fetching user details will firstly see, that there is nothing stored in Redis and then go to the database, fetch the record and store it into Redis
    • or: Use TTL (worst option ever).
    • If the records are written "somehow" into the database and you do not have control over that application, that's the worst case. I would go for TTL in this case.

    HTH, Mark