TrustworthySystems
TrustworthySystems

Reputation: 777

Is it possible to implement a read-modify-write cycle in Redis?

Trying to access a Redis Key from C# using StackExchange.Redis.Extensions.AspNetCore client library, the problem at hand is that this key must be change only by One client.

The key has a value of 0 and has to be changed to 1, but only the client that read the 0, when writing the 1 is the One that get the control.

Is the same semaphore schema implemented in many languages, but this is for multiple clients to get control for some resource until it is released by writing a 0 again.

The use case is multiple clients from different locations race to issue an atomic read-modify-write to the key writing a 1, but only One (the first) reads the 0 (or none if already a previous client has it) and the rest reads the modified 1.

Has anyone solve a problem like this using Redis, is there a way to solve it or a library that implement it.

Upvotes: 1

Views: 699

Answers (2)

Claude
Claude

Reputation: 117

https://stackoverflow.com/users/9012649/gawain solution is perfect most of the time and is a good use of the lua system. Effectively, a lua script executes in an atomic way (since redis is single threaded and handles 1 request at a time).

However, when the size of the data is significant (the redis request includes 2 copies) and/or the collision potential is important performance may be an issue. A solution may be to include some form of mutex in the data set and use the lua script to manage that small data piece. This work well if the value is a json object (rejson) and the mutex is some high level key.

Upvotes: 0

Gawain
Gawain

Reputation: 1092

You can use Lua script to implement "read and update".

Here is a sample for Lua:

if redis.call("get", KEYS[1]) == ARGV[1] then
    redis.call("set", KEYS[1], ARGV[2])
    return 1
else
    return 0
end

And you can use return value to determine if the client get control.

Upvotes: 3

Related Questions