Skip to content

Redis Lock

In a distributed system where multiple processes or threads are accessing shared resources concurrently, it becomes crucial to maintain data consistency and avoid race conditions. Redis, a popular in-memory data store, offers a simple yet effective mechanism called “Redis Lock” or “Redlock” to address these challenges. Redis Lock, also known as Distributed Locking with Redis, is a technique used to coordinate access to shared resources in a distributed environment.

RedLock은 완벽하지 않다

공식 문서에 언급된 Martin Kleppmann이 분석한 문서에 따르면 RedLock 알고리즘에도 문제가 발생할 수 있다.

아래 코드는 Lock을 획득 후 파일에 데이터를 저장하는 코드이다.

// THIS CODE IS BROKEN
function writeData(filename, data) {
  var lock = lockService.acquireLock(filename);
  if (!lock) {
    throw 'Failed to acquire lock';
  }

  try {
    var file = storage.readFile(filename);
    var updated = updateContents(file, data);
    storage.writeFile(filename, updated);
  } finally {
    lock.release();
  }
}

위 코드에서 발생할 수 있는 문제를 시각화 한 다이어그램과 절차는 아래와 같다.

  1. 클라이언트 A가 마스터에서 잠금을 획득한다.
  2. 클라이언트 A에서 Stop-the-World GC로 인한 어플리케이션 코드 중지가 발생하고 그 사이에 잠금이 만료된다.
  3. 클라이언트 B가 분산락을 획득하고 파일에 데이터를 쓴다.
  4. 클라이언트 A가 GC가 끝난 후 파일에 데이터를 쓰면서 동시성 문제가 발생한다

RedLock_-_Stop-the-World_GC.png

일반적으로 GC는 매우 빠르게 수행되지만 Stop-the-World GC는 드물게 잠금이 만료될 정도로 지속될 수 있다. Martin Kleppmann의 문서를 보면 GC 말고도 네트워크 지연이나 timing 이슈에 따라 RedLock이 깨질 수 있음을 알 수 있다.

사견으로 그냥 etcdZooKeeper 같은거 쓰자.

See also

Favorite site