Lesson 12 of 12 Concurrency and Interviews

Thread Safety and an LLD Interview Checklist

Race conditions, locks and producer-consumer queues for low-level design, plus a 45-minute LLD interview plan and a checklist for reviewing your design.

40-50 min intermediate 0/12 lessons done
Course contents Lesson 12 of 12 · 0 done
On this page (9 sections)
  1. What you will learn
  2. A race you can reproduce
  3. Three ways to be safe
  4. A 45-minute LLD interview plan
  5. Review checklist
  6. Where to go next
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will learn

  • What a race condition looks like and three ways to prevent one.
  • Producer-consumer with a blocking queue.
  • How to structure a 45-minute LLD interview, and a checklist to review any design.

A race you can reproduce

"""Thread-safety basics for LLD: a race condition and three fixes."""
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from queue import Queue


class UnsafeCounter:
    def __init__(self):
        self.value = 0

    def increment(self):
        current = self.value  # read
        current += 1          # modify
        time.sleep(0)         # a pause (I/O, a log line...) lets other threads run
        self.value = current  # write: another thread may have written in between


class LockedCounter:
    def __init__(self):
        self.value = 0
        self._lock = threading.Lock()

    def increment(self):
        with self._lock:  # read-modify-write happens as one step
            self.value += 1


def hammer(counter, threads=8, per_thread=2_000):
    def work():
        for _ in range(per_thread):
            counter.increment()
    with ThreadPoolExecutor(threads) as pool:
        for _ in range(threads):
            pool.submit(work)
    return counter.value


class BoundedBuffer:
    """Producer-consumer with a thread-safe queue: no explicit locks needed."""

    def __init__(self, size):
        self.q = Queue(maxsize=size)  # put() blocks when full, get() when empty

    def produce(self, items):
        for item in items:
            self.q.put(item)
        self.q.put(None)  # sentinel: no more items

    def consume(self, out):
        while (item := self.q.get()) is not None:
            out.append(item * item)


if __name__ == "__main__":
    print("expected:", 8 * 2_000)
    print("unsafe:  ", hammer(UnsafeCounter()))
    print("locked:  ", hammer(LockedCounter()))

    buf, squares = BoundedBuffer(size=3), []
    consumer = threading.Thread(target=buf.consume, args=(squares,))
    consumer.start()
    buf.produce(range(1, 6))
    consumer.join()
    print("squares:", squares)

Output from one run (the unsafe number changes every run):

expected: 16000
unsafe:   2030
locked:   16000
squares: [1, 4, 9, 16, 25]

UnsafeCounter.increment reads, modifies, then writes. The time.sleep(0) stands in for any work between read and write; it lets another thread run, read the same old value, and overwrite the first thread’s update. Most increments are lost. Without that pause the window is tiny and the race may not show up in a quick test, which is exactly why races are dangerous: code can pass tests and still be wrong.

Three ways to be safe

  1. Locks (LockedCounter): make the read-modify-write one critical section. Keep critical sections short and never call slow external services while holding a lock.
  2. Confinement and message passing (BoundedBuffer): only one thread owns the data; others communicate through a thread-safe queue. Queue.put blocks when full (back-pressure) and get blocks when empty.
  3. Immutability and atomic operations: immutable objects can be shared freely. Java offers AtomicInteger.incrementAndGet() and ConcurrentHashMap.merge(); databases offer conditional updates.

Concurrency bugs to name in interviews:

  • Deadlock: two threads each hold a lock the other needs. Prevent by always acquiring locks in a fixed order, or using timeouts.
  • Check-then-act: if seat.free: seat.book() is unsafe unless both steps are inside one lock (see the ticket booking lesson).
  • Starvation: a thread never gets the resource; fair locks or queues help.

For more practice, the concurrency question list collects common problems (bounded buffer, readers-writers, dining philosophers, print in order).

A 45-minute LLD interview plan

MinutesWhat to do
0–5Clarify requirements and scope; list use cases; say what’s out of scope.
5–12Identify classes and relationships; sketch a class diagram.
12–15Point out what varies; name the interfaces/patterns you’ll use and why.
15–35Write the core flow in code: entities, the main service, one strategy.
35–42Edge cases, invalid states, concurrency.
42–45Extensions and trade-offs.

Review checklist

  • Can I describe each class’s responsibility in one sentence?
  • Are varying behaviours behind interfaces and injected?
  • Are lifecycles modelled explicitly (enum + transitions or State pattern)?
  • Do invalid operations raise clear domain errors?
  • Are check-then-act sequences atomic?
  • Is the core flow runnable and tested with a small scenario?
  • Did I avoid patterns that add no value?

Where to go next

  • Practise prompts from the LLD sheet: library system, splitwise, snake and ladder, logging framework, rate limiter class.
  • Learn how these components fit into distributed systems in the System Design course.
  • Sharpen the data structures behind LLD problems with the DSA patterns guide.

Key takeaways

  • Read-modify-write on shared data is a race unless it’s atomic; races often hide in tests.
  • Use locks, confinement with queues, or immutability/atomics, and keep critical sections short.
  • Prevent deadlocks with a consistent lock order.
  • In interviews, budget time: requirements, classes, patterns, code, edge cases, extensions.

Exercises

  1. Remove time.sleep(0) from UnsafeCounter, run it ten times and record the results. What does that tell you about testing for races?
  2. Add two consumers to BoundedBuffer and make sure both stop cleanly.
  3. Write two functions that lock two accounts in opposite orders to transfer money, show the deadlock, then fix it with ordered locking.

Quiz

  1. Why can self.value += 1 lose updates across threads?
  2. What does a bounded queue give you besides thread safety?
  3. How do you prevent deadlock when a method needs two locks?
Show answers
  1. It’s a read, an add and a write; another thread can write between the read and the write, and one update overwrites the other.
  2. Back-pressure: producers block when consumers fall behind, so memory doesn’t grow without limit.
  3. Always acquire locks in the same global order (for example by account id), or use timeouts and retry.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).