How can I prevent race conditions with Redis?

I used only Redis as my database, and my client is ServiceStack.Redis. The fact is that if two simultaneous requests need to update one key, this may be a race condition. for instance

A:

  • int a = Get the key
  • MULTI
  • a = a - 100
  • Set key a
  • EXEC

IN:

  • int a = Get the key
  • MULTI
  • a = a - 100
  • Set key a
  • EXEC

if the initial “key” is 1000. If first A and B are serialized, the correct results for these two key operations will be 800. But if A and B occur at the same time. Before A can commit, operation B receives the value 1000 from the “key” and sets 900 to the “key”. This is not what I want. How can I prevent such race conditions from using CLOCK?

+6
source share
1 answer

You have to read the documents in Transactions in Redis , transactions in Redis essentially combine several operations, so they are performed as one atomic operation.

Since these are only batch processing operations, you cannot perform any reads in the context of a transaction. Any reading you need before you need to find it before the transaction begins. Then you can use Redis WATCH to view any keys that should not be changed before the transaction is completed, if the key was changed, the transaction will fail and no operations will be processed.

+5
source

Source: https://habr.com/ru/post/982482/


All Articles