Skip to content
Optimal Lab

System Design · interactive

Distributed locks

A lock across machines needs a timeout, or a crashed holder would keep it forever. But a holder that merely pauses doesn't know its time ran out. Watch two clients both believe they hold the lock.

Lock held by

client 1

Storage holds

empty

  1. t=0sclient 1Takes the lock for 10 s.

Takes the lock for 10 s.

Protection

t = 0 s

Step 1 of 4

  1. 1

    Take the lock with a lease

    The lock service grants it for 10 seconds. If the holder crashes, the lock frees itself.

    SET lock client1 NX PX 10000

  2. 2

    A pause outlives the lease

    GC pauses, a slow disk, a laptop lid closing: the client can't notice time passing while it's frozen.

    Frozen from t=1 s to t=16 s; the lease ends at t=10 s.

  3. 3

    Two clients think they hold it

    Client 2 takes the lock legitimately. Client 1 wakes up and carries on as if nothing happened.

    The lock service did nothing wrong. Time-based locks can't stop this alone.

  4. 4

    Fencing tokens: storage checks the number

    Every grant comes with a number that only goes up. Storage remembers the highest it has seen and rejects anything lower.

    Keep stepping.

In production

Tools and technologies

Lock services give you leases; correctness under pauses needs fencing at the storage.

Not tied to one language — use these names when you search docs or design a system.