Typorithm · hard

Distributed Locks

redis-lockredislocksetnxnx
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Distributed Locks

0%

Patterns

SET ... NX acquires a lock only if the key is absent, atomically, and an EX/PX expiry auto-releases a crashed holder. Storing a unique owner token lets a client safely DEL only its own lock — the single-node primitive behind Redlock.

A distributed lock built on Redis uses SET lock:job "owner1" NX EX 30. The NX flag means the SET succeeds only if the key does not already exist, so exactly one client can acquire the lock; the operation is atomic.

The EX (or PX, in milliseconds) expiry is essential: if the holder crashes without releasing, the lock auto-expires and another client can acquire it, avoiding a permanent deadlock. EXPIRE can extend the lease while work continues.

Storing a unique owner token as the value lets a client confirm ownership with GET and DEL only its own lock, never one that has expired and been re-acquired by someone else. This SET NX EX is the single-node primitive that the multi-node Redlock algorithm builds on.

01

SET ... NX acquires only if the key is absent (atomic).

02

EX/PX expiry auto-releases a crashed holder.

03

A unique owner token lets you DEL only your own lock.

SET lock:job "owner1" NX EX 30
GET lock:job
SET lock:job "owner1" NX PX 5000
EXPIRE lock:job 30
DEL lock:job

Read the implementation

Connect each part of the code to the concept before you type.

1. Acquire atomically

SET ... NX sets the key only if it is absent, atomically acquiring the lock, and EX 30 gives it a 30-second expiry.

SET lock:job "owner1" NX EX 30

2. Check the owner

GET reads the stored owner token so a client can verify it still holds the lock.

GET lock:job

3. Millisecond expiry

PX 5000 sets the same NX lock with a 5000-millisecond expiry for finer-grained timeouts.

SET lock:job "owner1" NX PX 5000

4. Extend the lease

EXPIRE refreshes the lock's TTL so a long-running holder can extend its lease before it lapses.

EXPIRE lock:job 30

5. Release the lock

DEL releases the lock; the owner token lets a client delete only the lock it owns.

DEL lock:job

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Distributed Locks: Lesson & Practice · Typorithm | ApplyDjinn