Interview prep notes

linkjobai revised this gist 5 days ago · bc60fc3

1 file changed, 36 insertions

distlock.md (file created)
@@ -0,0 +1,36 @@
1 + # System Design Interview: Distributed Locks, Leases and Fencing Tokens
2 +
3 + "How would you make sure only one worker processes this job?" is a common follow-up. A good answer covers leases and why a lock alone isn't enough.
4 +
5 + ## The naive Redis lock
6 +
7 + ```
8 + SET lock:job42 <random-token> NX PX 30000
9 + ```
10 +
11 + - `NX` only sets the key if it doesn't exist; `PX` gives it a 30 s expiry so a crashed holder doesn't block forever.
12 + - Release with a script that deletes the key **only if** the value is still your token, so you never delete someone else's lock.
13 +
14 + ## Why expiry creates a problem
15 +
16 + Suppose worker A gets the lock, then pauses (GC, network stall) for 40 s. The lock expires, worker B acquires it, and then A wakes up and writes anyway. Both think they hold the lock.
17 +
18 + ## Fencing tokens
19 +
20 + Have the lock service hand out a number that increases with every acquisition (A gets 33, B gets 34). Every write to the protected resource includes the token, and the resource rejects any token lower than the highest it has seen. A's late write with 33 is refused.
21 +
22 + This requires the storage layer to check tokens, which is the point interviewers want you to notice: correctness comes from the resource, not just the lock.
23 +
24 + ## Choosing a lock service
25 +
26 + - **Single Redis**: fast, fine for efficiency locks (avoiding duplicate work) where an occasional double run is harmless.
27 + - **Redlock** (majority of independent Redis nodes): debated; depends on timing assumptions.
28 + - **ZooKeeper / etcd**: consensus-based; use ephemeral nodes or leases tied to a session, and their revision numbers work as fencing tokens. Prefer these for correctness locks.
29 + - **Database row lock** or a conditional update on a `version` column is often enough and is the simplest answer.
30 +
31 + ## Interview tip
32 +
33 + Ask whether the lock is for efficiency or correctness before picking a design.
34 +
35 + ---
36 + *Disclosure: I work on [Linkjob AI](https://www.linkjob.ai/), real-time interview help.*