3

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

Frank
  • 977
  • 3
  • 14
  • 35
  • What do you mean by "redis crash"? – Guy Korland Nov 24 '20 at 11:23
  • @GuyKorland I mean between `Incr` command and `expire` command, redis doesn't work maybe caused by redis cluster issues, network issues and so on, that will make key expire time be forever – Frank Nov 25 '20 at 03:37

1 Answers1

3

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.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117