Maxim Yefremov
Maxim Yefremov

Reputation: 14165

redis high concurrency insertion

I try to store comments in redis database. My data sctructure:

When I do zadd first I get maximum Id from it, then plus 1 - it will be new Id.

The problem started when 2 comments are added at the same time. And they both can get the same Id and then in hash table one comment can be lost.

So how to compute newId without duplications on high concurrency?

Upvotes: 0

Views: 176

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Wrap your two step procedure in a Lua script and call that. Because redis is single-threaded, lua script invocations will be serialized ( = no race conditions).

Alternative

Or you could store comment id in a separate key that you can INCR. This way it should work even without wrapping both steps in a script.

Upvotes: 3

Related Questions