Skip to the content.

Distributed lock

What do we need the distributed lock for

From standalone to distributed locks

img.png

Lock = Resource + Concurrency Control + Ownership Display

Distributed lock needs to have:

Types of distributed lock

GC breaks distributed lock

The following code is broken when GC(Garbage collection) kicks in:

// 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();
    }
}

Fencing: Solve the GC breaks everything problem

Timing

Problems with bad timing

Solve the bad timing issue

Distributed locks of Alibaba cloud storage

Strict mutual exclusion

For standalone lock, it is easy for a process to hold the lock. But for distributed lock, the lock holder needs to tell the lock server it is still holding the lock. So that, we could guarantee the mutual exclusion in distributed lock.

In both Alibaba and Google Chubby, this is done by maintain a session with TTL between the lock holder and lock server.

How to keep the session alive in order to hold the lock

Ideally we want to renew the session lease when it is about to expire. If client has a local TTL, it could either estimate if there has enough time to perform critical operations, or know if it is about the time to renew the session lease.

How to keep the session on failover

This is the solution from Google’s chubby.

Summary

References