Distributed locking with Redis

Source: Google Images

Distributed locking in brief

Using Redis as distributed locking mechanism

  • Create a unique key for the resource
  • Acquire lock on that key using redis
  • Perform our operations
  • Release the lock for that key
  • Application instance
  • Any thread in the case multi-threaded environment (see Java/JVM)
  • Any other manual query/command from terminal

Locking a key

boolean acquireLock(key, value){
result = execute(SETNX, key, value)
if(result == "OK"){
log("acquired lock by client %s for key %s",value, key)
return true
log("couldn't acquire, retry after some time")
return false;

Releasing a lock on key

void releaseLock(key, client){
value = execute(GET, key)
if(client==value && value!=null)
execute(DEL, key)
log("error while releasing lock for key %s",key)
key = generateKeys(){
return 'specialUUID'
value = 'client_name' // thread name or app name
performOperation()// sleep for 2 seconds or network call
releaseLock(key, value)
  • Deadlock free locking — as we are using ttl, which will automatically release the lock after some time
  • Eliminated infinite wait
  • If a client dies after locking, other clients need to for a duration of TTL to acquire the lock — will not cause any harm though.
  • If a client takes too long to process, during which the key expires, other clients can acquire lock and process simultaneously causing race conditions.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store