Sergey Prytkov
Sergey Prytkov

Reputation: 177

Conditionally manipulate hash in StackExchange.Redis relying on some synchronization

I'm using redis backed with some underlying persistent storage, so when cache request misses, logic is about to fetch data from backed storage and pass it to client storing it in cache as well. When some simultaneous requests for missed key happens I do want to permit only one request to reach persistent storage and do the job, while other will lock or have been subscribed for key changes and return to caller with values fetched from cache.

Upvotes: 0

Views: 388

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

One possible approach could be adding a string key with expiration (see EXPIRE command) whenever the cache needs to be populated called whatever:lock (change whatever with something meaningful to your project) and expire it in 4-5 minutes.

All requests to the cache should check if whatever:lock is present:

  • If it's not present, then the whole process adds the whole locking key and tries to populate the cache.
  • If it's present, the whole process will poll the cache until the locking key doesn't exist anymore, and it will get the data from the cache.

Both SET and EXPIRE should be issued as part of a MULTI command to be sure that expiration is set atomically along with the key creation.

You can use SETNX for this too. Check Redis official doc about this command, where it says that it can be used to create locks.

Upvotes: 1

Related Questions