StackExchange Redis - StringSet vs SetAdd and expiries

RPM1984 picture RPM1984 · Apr 9, 2015 · Viewed 10.4k times · Source

In StackExchange.Redis, the STRING operations allow for expiry to be set, e.g:

    Task<bool> StringSetAsync(
RedisKey key, 
RedisValue value, 
TimeSpan? expiry = null, 
When when = When.Always, 
CommandFlags flags = CommandFlags.None);

Why is it that the SET operation does not?

    Task<long> SetAddAsync(
RedisKey key, 
RedisValue[] values, 
CommandFlags flags = CommandFlags.None);

Basically, here's what i want to achieve:

Given a List<T>, add items to a Redis Set (either create, or add to existing) with an expiry of 1 hour.

How do i do it? Or should i be serializing the List<T> then use StringSet?

I want to use SET functions like SREM and add single items to the existing SET (instead of rewriting the entire SET), which is why i'm trying not to use STRING.

Any advice?

Answer

Marc Gravell picture Marc Gravell · Apr 9, 2015

For the first question (why do string operations have optional expirations when the set operations do not): that is simply because that is what the redis operations expose: SET (in particular with the EX and PX modifiers) and SETEX are the string operations here that allow expiration to be set. The set operation SADD exposes no such parameter. One part of this is probably to avoid confusion that the expiration would apply to the element, when in fact the expiration would apply to the entire key (i.e. the entire set).

Your best bet, then, is to set the expiration explicitly; at the redis level, this is via EXPIRE, EXPIREAT, PEXPIRE or PEXPIREAT; or on IDatabase in SE.Redis: KeyExpire or KeyExpireAsync. This must be done after the set exists; if the set is large and you are sending multiple batches and want to ensure the timeout is set even if it chokes near the end, you might want to sent the expiration after the first batch.