Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best practice for list and set handling in Redis?

Tags:

redis

We are using Redis as a caching server, and often have to deal with caching list. When we cache simple objects we do a GET and Redis will return null if the object doesn't exist and we'll know that the object isn't cached and have to be loaded from database.

But how do we best handle the same for lists - an empty list can be a valid value. Do we need to call EXISTS to check if the list exists (but making the operation 2 calls instead of one) or does someone have a better idea how to handle this scenario?

/Thanks

like image 945
Micael Avatar asked Oct 28 '10 07:10

Micael


2 Answers

If you absolutely need to do that, when the list is created you can push a "sentinel" as first element that is never removed. In order to do this atomically you can use MULTI/EXEC/WATCH, but watch is only available in Redis 2.2 that is currently a preview (even if pretty stable, you can grab it from github master branch).

I think in your use case you may also want RPUSHX and LPUSHX, that will atomically push against a list only if it already exists.

Note that since Redis 2.2 to exist means to have at least 1 element for a list, as lists that will reach zero elements are automatically removed, for many good reasons ;)

like image 94
antirez Avatar answered Sep 21 '22 20:09

antirez


Unfortunately, list/set retrieval commands such as LRANGE and SMEMBERS do not seem to distinguish between an empty list/set and a non-existent list/set.

So if you absolutely need to distinguish between the two cases, I guess you'll need to do an EXISTS first. Try pipelining your commands for better performance. Most Redis client libraries support pipelining.

Or you might reconsider your caching strategy so that you don't need to distinguish them.

like image 44
kijin Avatar answered Sep 18 '22 20:09

kijin