KatInterview

Prevent Deadlock in Multi-Lock File Transfer

System DesignModel answer
MediumModel answerSystem Designconcurrencydeadlocklocking

Last 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:

  1. Explain exactly when and why this code deadlocks. Describe the specific thread interleaving that causes the problem.
  2. Propose at least two different solutions that prevent the deadlock, including code changes.
  3. For each solution, discuss the trade-offs: performance impact, complexity, limitations, and when you'd choose it.
  4. 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