skip to Main Content

I have a single number in redis which I want to increment counts of, however, I want each increment to expire and be removed after a TTL.

Essentially I want the behavior to be like so:

Time 1: Increment 5 (TTL 5), value is 5

Time 2: Increment 3 (TTL 5), value is 8

Time 6: Increment 5 expired, value becomes 3

Is this behavior possible?

2

Answers


    • You use GET singleNumber.
    • If the key exists you set a new value with the response (e.g. 5), and the increment (e.g. 3) with SET singleNumber 8 EX 5 where EX 5 says that it will expire in 5 seconds.
    • If the key didn’t exist, you set a new value (e.g. 3) with SET singleNumber 3 EX 5.

    If you don’t want to reset the TTL with each increment, you could use KEEPTTL option for the SET command.

    Login or Signup to reply.
  1. I think what you store in redis should be logs of operations. Then compute the final score with logs whose ttls are not reached.

    Since you can

    1. delete expired data more conveniently with sorted set,
    2. get all live data faster with sorted set,

    I would recommend using a sorted set like below:

    1. use Increment as the main key
    2. use timestamp of expiration time as the score in redis
    3. use [increment score]_[timestamp/uuid] as a member in set

    For example:
    Suppose the times are:

    Time1: 1696664893 (now)
    Time2: 1696664894
    Time6: 1696664898
    Time7: 1696664899
    
    zadd Increment 1696664898 5_sfdsafdsafdsa
    zadd Increment 1696664899 3_fdafdsafdsfda
    

    Get total score

    Suppose it is Time 7 now

    ZRANGEBYSCORE Increment 1696664899 +inf
    # return 3_fdafdsafdsfda, split the string, get total score of 3
    

    remove all expired data

    ZREMRANGEBYSCORE Increment -inf 1696664898
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search