Search code examples
redisredis-cluster

how to make sure counter atomic by using redis incr command


I'm using redis incr as our request counter as I researched incr is a atomic and thread-safe, now I wanna add expire time for each key but seems this process is not thread-safe, for example, redis crash only after incr done and before Expire command running, the basic pseudocode is as below:

value := redisClient.getValue(key)
if value > common.ChatConfig.SendMsgRetryCfg.RetryCount {
      return error
}
value, err := redisClient.Incr(key).Result()
if err == nil {
    redisClient.Expire(key, 24*time.Hour)
}

I wanna know how to change my codes and make the process be atomic and thread-safe? thank u


Solution

  • To make the two commands "atomic" use a Redis transaction or a Lua script. This will be thread-safe and fault-tolerant, as any changes will be persisted only after all commands (in the tx/script) had finished.