Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis INCR concurrency

I am using Redis' INCR to generate an ID for objects. And then use ZADD to add the object using the ID as key.

Do I need to worry about if there are multiple connections executing this same block of code? Say after id:12 if two connections connect at the same time and both add object using id:13, then one of them would be lost.

like image 876
spacemilkman Avatar asked May 21 '13 14:05

spacemilkman


People also ask

How does Redis handle concurrency?

RediSearch has a thread pool for running concurrent search queries. When a search request arrives, it gets to the handler, gets parsed on the main thread, and a request object is passed to the thread pool via a queue. The thread pool runs a query processing function in its own thread.

What is incr in Redis?

Redis INCR command is used to increment the integer value of a key by one. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that cannot be represented as an integer.

Is incr atomic in Redis?

The counter pattern is the most obvious thing you can do with Redis atomic increment operations. The idea is simply send an INCR command to Redis every time an operation occurs.

How does Redis handle multiple requests?

A Request/Response server can be implemented so that it is able to process new requests even if the client hasn't already read the old responses. This way it is possible to send multiple commands to the server without waiting for the replies at all, and finally read the replies in a single step.


2 Answers

Since redis is single threaded, this can never happen - only one client can make a change to the database at a time.

like image 89
Jonatan Hedborg Avatar answered Oct 20 '22 17:10

Jonatan Hedborg


As Jonatan Hedborg stated, Redis is single threaded so you never need to worry about two clients doing something at the same time. If, on the other hand, your worry is that you want to run the INCR and ZADD commands sequentially, and want to make sure no other commands are run in between them, you can use transactions, and be guaranteed your commands are run as a single unit with nothing in between.

like image 43
Eli Avatar answered Oct 20 '22 17:10

Eli