Search code examples
amazon-web-servicesredis

Redis HINCRBY hash field -1 counter for decrementing only till 0 or non negative value


Counts in negative: redis.hincrby(User:${targetUser.id}, "followerCount", -1)

I want it to stop at 0


Solution

  • HINCRBY operation returns the new value after the increment operation.

    redis> HSET myhash field 5
    (integer) 1
    redis> HINCRBY myhash field 1
    (integer) 6
    redis> HINCRBY myhash field -1
    (integer) 5
    

    If your HINCRBY operation returns -1, that means the followerCount for this user was 0, and hence should not be decreased. So, you can fire a HSET to 0 to set it to zero. A better approach would be to have an redis transaction which will:

    • first check the value using HGET,
    • if it is more than zero, then do a HINCRBY with -1 increment
    • if it is zero, do nothing.