Search code examples
cachingazureredisazure-sql-databasesoftware-distribution

How can I check if redis cache table is empty?


I'm using a cache in an MVC application.

I want to check if the cache is empty (no data) then trigger a web job which will populate the cache tables data from database.

How can I check for empty data in specific table in redis cache?


Solution

  • I'm going to have to disagree with @bitoiu. Do not run the keys command as routine operations. Keys is not intended to be run that way - it should be used for debug operations only.

    Likewise, using INFO doesn't tell you if specific data is there, just that there is something there. If you have one and only one key there then sure that might seem to work - until you discover a job run went awry and stored an empty string or the wrong data. If you only intend to store a single key there might be better options for you.

    If you're going almost certainly to store data from your SQL DB you will be storing a query result not a full copy of the data. This result will need a unique key. The way to test for this in Redis is to simply query the key. If the key is empty, populate it. If it is a string use get (or exists). If it is a hash then query for the specific members you need.

    Another advantage of doing it this way is to avoid having a scheduled job doing it. Instead have the data-needing-code first query to from Redis. If data is there, use it, otherwise query the backend and populate the cache with the result as you also pass it to the client. Combine this with an expiration (where possible) and you get a form of liveness test included.

    This way you don't need yet more services or jobs running to do what your application would normally do in the first place. If you ever have to change the backend query code you'll appreciate there being one and only one source to change. Or if someone changes one codebase but not the other.