Prevent Deadlock in Multi-Lock File Transfer
System DesignModel answerLast updated
Diagnose a deadlock in code that moves items between locked containers and implement fixes using lock ordering or try-lock strategies.
You're reviewing code for a file storage system where operations can transfer items between containers (folders, buckets, or accounts). Each container has its own lock to ensure consistency during modifications.
The current implementation sometimes hangs indefinitely when multiple operations run concurrently. Here's a simplified version of the problematic code:
import threading
class Container:
def __init__(self, container_id):
self.id = container_id
self.lock = threading.Lock()
self.contents = set()
def transfer(source, destination, item):
with source.lock:
with destination.lock:
source.contents.remove(item)
destination.contents.add(item)
Your task:
- Explain exactly when and why this code deadlocks. Describe the specific thread interleaving that causes the problem.
- Propose at least two different solutions that prevent the deadlock, including code changes.
- For each solution, discuss the trade-offs: performance impact, complexity, limitations, and when you'd choose it.
- Explain how you would confirm the deadlock is happening in a production environment.
Assume standard non-reentrant locks, moderate contention (dozens of concurrent operations), and that operations should be atomic and cannot leave containers in an inconsistent state.
Hints
Hint 1
Consider what happens when two threads call transfer with opposite source and destination arguments
Hint 2
Think about the four necessary conditions for deadlock and how breaking any one of them prevents the problem
Hint 3
Lock ordering is the standard solution, but it's not the only option
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Deadlock
The deadlock occurs when two threads execute transfers in opposite directions simultaneously:
Scenario:
- Thread T1 executes
transfer(ContainerA, ContainerB, item1) - Thread T2 executes
transfer(ContainerB, ContainerA, item2)
Timeline:
- T1 acquires
ContainerA.lock - T2 acquires
ContainerB.lock - T1 tries to acquire
ContainerB.lock(blocked by T2) - T2 tries to acquire
ContainerA.lock(blocked by T1)
Neither thread can proceed. The wait-for graph contains a cycle: T1→T2→T1.
This satisfies all four Coffman conditions required for deadlock:
- Mutual exclusion: locks cannot be shared
- Hold and wait: each thread holds one lock while waiting for another
- No preemption: threads cannot forcibly take locks
- Circular wait: the acquisition order creates a dependency cycle
There's also a second bug: transfer(A, A, item) will deadlock a single thread because the non-reentrant lock cannot be acquired twice.
Production diagnosis: Capture a thread dump using your language's diagnostic tools (jstack for Java, py-spy for Python, pprof for Go). You'll see threads blocked on lock acquisition, each holding the lock another thread needs.
Solution 1: Global Lock Ordering
Impose a total ordering on all locks and always acquire them in that order:
def transfer(source, destination, item):
# Handle same-container case
if source is destination:
return
# Acquire in consistent order based on container ID
first, second = (source, destination) if source.id < destination.id else (destination, source)
with first.lock:
with second.lock:
if item not in source.contents:
raise KeyError(f"Item {item} not in source")
source.contents.remove(item)
destination.contents.add(item)
Why it works: All threads acquire locks in ascending ID order. This eliminates circular wait—the dependency graph becomes acyclic by construction.
Trade-offs:
- Pros: Simple, efficient, no retries or backoff needed
- Cons: Requires knowing all needed locks upfront; the ordering key must be stable and unique (don't use Python's
id()on objects that might be recreated) - When to use: Default choice for operations with a fixed, known set of locks
Critical detail: For operations needing N locks, sort all identifiers first, then acquire in order. For hierarchical structures like nested folders, use "parent before child, then by ID" ordering.
Solution 2: Try-Lock with Exponential Backoff
Attempt lock acquisition without blocking, and retry with randomized delays on failure:
import random
import time
def transfer_with_retry(source, destination, item, max_attempts=50):
if source is destination:
return
for attempt in range(max_attempts):
# Try to acquire first lock with timeout
if source.lock.acquire(timeout=0.05):
try:
# Try second lock non-blocking
if destination.lock.acquire(blocking=False):
try:
if item not in source.contents:
raise KeyError(f"Item {item} not in source")
source.contents.remove(item)
destination.contents.add(item)
return
finally:
destination.lock.release()
finally:
source.lock.release()
# Exponential backoff with jitter to avoid livelock
delay = random.uniform(0, min(0.1, 0.001 * (2 ** attempt)))
time.sleep(delay)
raise TimeoutError("Failed to acquire locks after retries")
Why it works: Breaks "hold and wait" by releasing all locks when any acquisition fails, preventing circular dependencies.
Trade-offs:
- Pros: Works when locks must be discovered dynamically; no global ordering needed
- Cons: CPU waste from retries; potential starvation (one thread never succeeds); increased tail latency; randomized jitter is essential to prevent livelock
- When to use: Dynamic lock sets, hot-path lock discovery, or when global ordering isn't feasible
Solution 3: Change Lock Granularity
Option A: Single global lock
global_lock = threading.Lock()
def transfer(source, destination, item):
with global_lock:
source.contents.remove(item)
destination.contents.add(item)
Trivially prevents deadlock (only one lock exists) but serializes all operations. Acceptable only at low throughput.
Option B: Lock striping Hash containers to K stripe locks, acquire stripes in index order:
NUM_STRIPES = 64
stripe_locks = [threading.Lock() for _ in range(NUM_STRIPES)]
def transfer(source, destination, item):
stripe1 = hash(source.id) % NUM_STRIPES
stripe2 = hash(destination.id) % NUM_STRIPES
# Acquire in index order, deduplicating if same stripe
stripes = sorted(set([stripe1, stripe2]))
locks = [stripe_locks[s] for s in stripes]
with ExitStack() as stack:
for lock in locks:
stack.enter_context(lock)
source.contents.remove(item)
destination.contents.add(item)
Balances concurrency and memory: fewer locks than containers, ordering remains straightforward.
Solution 4: Timeout-Based Detection
Add timeout as a safety net:
def transfer(source, destination, item, timeout=5.0):
if not source.lock.acquire(timeout=timeout):
raise TimeoutError("Could not acquire source lock")
try:
if not destination.lock.acquire(timeout=timeout):
raise TimeoutError("Could not acquire destination lock")
try:
source.contents.remove(item)
destination.contents.add(item)
finally:
destination.lock.release()
finally:
source.lock.release()
Converts silent hangs into observable failures. Choosing the timeout is difficult: too short causes false positives under load, too long means long stalls. Best used alongside lock ordering as defense-in-depth.
Trade-off Summary
| Approach | Throughput | Complexity | Main Risk |
|---|---|---|---|
| Lock ordering | High | Low | Needs stable IDs, fixed lock set |
| Try-lock + backoff | Medium | Medium | Livelock, starvation, latency |
| Global lock | Low | Very low | Serialization bottleneck |
| Lock striping | Medium-high | Low | False sharing across stripes |
| Timeout detection | Medium | Medium | Tuning difficulty, requires cleanup |
Recommended Approach
Primary: Use lock ordering (Solution 1). It's simple, performs well, and eliminates deadlock by design.
Secondary: Add timeout-based detection (Solution 4) as a monitoring and safety mechanism to catch unexpected deadlocks from hidden lock acquisitions (callbacks, I/O during critical sections).
When ordering isn't viable: Use try-lock with backoff (Solution 2), but only if the operation set is truly dynamic and you can tolerate retry overhead.
Critical rule: Never call external code, perform I/O, or make RPC calls while holding locks. Extract needed data, release locks, then make the call. Many production deadlocks stem from callbacks that acquire their own locks while the caller holds one.