Search code examples
redisrace-condition

Redis : How to prevent this race condition


I have a hash in redis in which one the field has value as stringified array, whenever user register for an event,

  1. Fetch this stringified array from redis
  2. Parse in backend and add the user's username in the array
  3. stringify the array and store back to hash

There is a potential race condition possibility here if two users register at close enough time.

Race condition could be like this that the both users get the same stringified array from redis and then they modify, and only one update will happen as one will be overwritten by other.

Is there a way to prevent this race condition like transactions in SQL. I have read about multi, but it does not allow to do computation between commands on server.

Or storing stringifying array and storing as hash field is a bad idea, and I should use a normal list for this on redis.


Solution

  • The solution is to use atomic operations where you can. You have several options:

    • use real Redis lists that support handy commands such as LPUSH
    • do everything inside a Lua script (they are atomic by definition)
    • use Redis transactions and the WATCH command to track changes

    The typical WATCH usage involves attempting to execute the transaction until it succeeds. You can do this with a simple loop, however it's possible that your connector has a special convenience method exactly for that.