Concurrency Fundamentals
Sooner or later in a low-level design interview, your interviewer leans back and asks: "Now, what if many users do this at the same time?" Your parking lot, booking system or cache worked perfectly with one caller. With two callers at once, it may sell the same seat twice or lose money from an account, and nothing in the code looks wrong.
Some problems are about concurrency from the start: a rate limiter, a connection pool, a job scheduler, an async logger. Others add it as a follow-up. Either way, you need the same small toolbox and the judgment to pick the right tool. This post builds that from the ground up: what threads share, how a race actually loses data, the five tools that fix it, and the three kinds of questions interviewers ask, so you can recognize which tool each one needs.
💡 Why this matters in an interview: you are not expected to write lock-free data structures. You are expected to point at the shared state, explain exactly what goes wrong when two threads touch it, and protect it with the simplest correct tool.
Threads and Shared State
A thread is a single sequence of instructions running inside a program. A program (a process) can run many threads at once. On a machine with several CPU cores they truly run at the same moment; on one core the operating system switches between them many times a second. From your code's point of view the effect is the same: you can't predict which thread runs next or when it gets paused.
Why use threads at all? Two reasons. First, waiting: a web server spends most of its time waiting on the
network and the database, and while one request waits, another thread can serve a different request. Second,
parallelism: on a multi-core machine, CPU-heavy work split across threads finishes sooner. In LLD problems the
first reason is far more common. Many users call your BookingService at once, each on their own thread.
What makes threads useful, and dangerous, is what they share:
- Private to each thread: local variables and function arguments. Each thread has its own stack, so two
threads running the same function each get their own copy of
amount. - Shared by all threads: objects on the heap and global variables. If two threads hold a reference to the
same
Account, they are reading and writing the samebalancefield.
This gives the one rule everything else follows from: concurrency bugs need shared, mutable state. If data is not shared (each thread has its own) or not mutable (nobody writes it after creation), no thread can corrupt it. Every tool below is a way of controlling access to state that is both.
⚠️ Python's GIL doesn't save you: standard CPython has a Global Interpreter Lock, so only one thread runs Python bytecode at a time. But the interpreter can switch threads between any two bytecodes, and
balance += amountis several of them. Races still happen; they just happen less often, which makes them harder to catch. (Newer Python versions also offer an optional build without the GIL.)
Why Races Happen: A Lost Update
Here is a bank account that looks completely correct.
class Account:
def __init__(self, balance: int) -> None:
self.balance = balance
def deposit(self, amount: int) -> None:
self.balance += amount
self.balance += amount reads like one step, but the machine does three:
- Read the current
balancefrom memory. - Add
amountto it. - Write the result back to
balance.
If two threads deposit at the same time, their steps can interleave. Start with a balance of 100. Thread A deposits 50 and thread B deposits 20, so the balance should end at 170.
| Step | Thread A: deposit(50) | Thread B: deposit(20) | balance in memory |
|---|---|---|---|
| 1 | reads 100 | 100 | |
| 2 | reads 100 | 100 | |
| 3 | computes 150 | 100 | |
| 4 | computes 120 | 100 | |
| 5 | writes 150 | 150 | |
| 6 | writes 120 | 120 |
Thread B read the balance before A wrote its result, then overwrote A's write. A's deposit of 50 is gone. This is a lost update, and it is the classic read-modify-write race: any time a thread reads a value, computes a new one from it, and writes it back, another thread can slip in between.
The second shape of race is check-then-act. A movie theater sells its last seat:
class Showtime:
def __init__(self, seats_left: int) -> None:
self.seats_left = seats_left
def book(self) -> bool:
if self.seats_left > 0: # check
self.seats_left -= 1 # act
return True
return False
With one seat left, threads A and B both run the check, both see 1 > 0, and both book. Two customers hold
tickets for one seat, and seats_left is now -1. The check was true when it ran, but it was no longer true when
the thread acted on it.
Both bugs share one root cause: a sequence of steps that must happen as a unit (an atomic operation, meaning indivisible) is actually several steps another thread can interrupt. The part of the code that must not be interrupted is called the critical section. Fixing a race means making the critical section atomic.
There is also a quieter problem in languages like Java and C++: visibility. Without synchronization, the
compiler and CPU are allowed to keep a value in a register or cache, so a write by one thread may never become
visible to another. This loop may spin forever even after another thread sets running = false:
class Worker implements Runnable {
private boolean running = true; // add `volatile` to fix
public void stop() { running = false; }
public void run() {
while (running) { doWork(); } // may never see the update
}
}
Marking the field volatile tells Java that every read must see the latest write. Locks and atomics also
guarantee visibility, so if you use them consistently you rarely need volatile on its own.
The Toolbox
Five tools cover nearly every concurrency question in an LLD interview. Each one answers a different question.
Atomics
An atomic variable makes one read-modify-write on a single value indivisible. The hardware provides instructions like compare-and-swap (CAS: "set this to 151 only if it is still 150"), and the atomic classes wrap them. Java has a full set:
class PageViews {
private final AtomicLong views = new AtomicLong();
public long recordView() {
return views.incrementAndGet(); // read, add 1, write: one atomic step
}
}
Atomics are fast because they never put a thread to sleep. Their limit is that they protect one variable. If an invariant spans two fields ("balance changes and the transaction log gets a new row, together"), an atomic on each field doesn't help, because another thread can still see one updated and not the other. That needs a lock.
Python has no atomic integer in its standard library. Use a lock, which is the next tool.
Locks
A lock (or mutex, for "mutual exclusion") lets only one thread at a time into a critical section. A thread acquires the lock before the section and releases it after; any other thread that tries to acquire it waits until it is free. Here is the account and the showtime, fixed:
class Account:
def __init__(self, balance: int) -> None:
self.balance = balance
self._lock = threading.Lock()
def deposit(self, amount: int) -> None:
with self._lock: # released even if an exception is raised
self.balance += amount
class Showtime:
def __init__(self, seats_left: int) -> None:
self.seats_left = seats_left
self._lock = threading.Lock()
def book(self) -> bool:
with self._lock: # check and act happen together
if self.seats_left > 0:
self.seats_left -= 1
return True
return False
In Java, the simplest form is synchronized, which uses a lock built into every object. ReentrantLock does the
same job with extras like tryLock with a timeout; always release it in finally:
class Account {
private long balance;
public synchronized void deposit(long amount) { balance += amount; }
public synchronized long getBalance() { return balance; } // reads take the lock too
}
class Showtime {
private int seatsLeft;
private final ReentrantLock lock = new ReentrantLock();
public boolean book() {
lock.lock();
try {
if (seatsLeft == 0) return false;
seatsLeft--;
return true;
} finally {
lock.unlock();
}
}
}
A few rules make locks safe to use:
- One lock per piece of state, on every access. Say it in a comment or out loud: "
_lockguardsseats_left." Every read and write of that state takes that same lock. If one method usessynchronizedand another uses aReentrantLockon the same field, they hold two different locks and don't exclude each other. - Keep critical sections short. Do the computation outside, take the lock, update, release. Never do slow I/O (network calls, sending email) while holding a lock.
- Watch for deadlock. If thread A holds lock 1 and waits for lock 2 while thread B holds lock 2 and waits for lock 1, both wait forever. Taking locks in a fixed global order prevents it. See Deadlocks, Livelocks and Starvation.
Semaphores
A semaphore is a counter of permits. acquire takes a permit, waiting if none are left; release gives one
back. A lock lets one thread in; a semaphore lets up to N in. It answers "how many at once?", not "who may touch
this data?"
A typical use is capping how many threads call a slow external service at the same time:
class GeocodingClient:
def __init__(self, max_in_flight: int = 5) -> None:
self._permits = threading.BoundedSemaphore(max_in_flight)
def lookup(self, address: str) -> tuple[float, float]:
with self._permits: # at most 5 threads past this line
return self._call_remote_api(address)
class GeocodingClient {
private final Semaphore permits = new Semaphore(5);
public double[] lookup(String address) throws InterruptedException {
permits.acquire();
try {
return callRemoteApi(address);
} finally {
permits.release();
}
}
}
A semaphore only counts. If the threads it lets in share data (a list of free connections, for example), that
data still needs its own lock. BoundedSemaphore in Python raises an error if you release more times than you
acquired, which catches a common bug.
Condition Variables
Sometimes a thread must wait until something becomes true: a worker waits until there is a job, a buyer waits
until stock arrives. Checking in a loop (while not ready: pass) burns a CPU core. A condition variable lets
a thread sleep until another thread signals that the state has changed.
A condition variable always works together with a lock. The waiting thread holds the lock, checks the condition,
and calls wait, which releases the lock and sleeps in one atomic step. The other thread takes the same lock,
changes the state, and calls notify. Here is a tiny job inbox:
class JobInbox:
def __init__(self) -> None:
self._jobs: list[str] = []
self._cond = threading.Condition() # has its own lock inside
def submit(self, job: str) -> None:
with self._cond:
self._jobs.append(job)
self._cond.notify() # wake one waiting worker
def next_job(self) -> str:
with self._cond:
while not self._jobs: # while, not if
self._cond.wait() # releases the lock while asleep
return self._jobs.pop(0)
class JobInbox {
private final Deque<String> jobs = new ArrayDeque<>();
public synchronized void submit(String job) {
jobs.addLast(job);
notifyAll();
}
public synchronized String nextJob() throws InterruptedException {
while (jobs.isEmpty()) wait();
return jobs.removeFirst();
}
}
Two failure modes to name here:
- Missed signal: if a thread checks the condition without holding the lock, the other thread can add a job
and call
notifybetween the check and thewait. The notification goes to nobody, and the waiter sleeps forever. Checking and waiting under the same lock prevents it. - Spurious or stolen wakeup: a thread can wake up and find the condition false again, because the system woke
it without a reason or another thread grabbed the job first. That is why the check is a
whileloop, never anif.
Blocking Queues
A blocking queue is a thread-safe queue whose put waits when the queue is full and whose take waits when
it is empty. It is the lock and condition variables from the previous section, already written and tested for
you. It is the backbone of the producer-consumer pattern: some threads produce work, others consume it, and
the queue sits between them.
orders: queue.Queue[Order] = queue.Queue(maxsize=100)
def api_handler(order: Order) -> None: # producer
orders.put(order) # waits if 100 orders are already queued
def kitchen_worker() -> None: # consumer, run in several threads
while True:
order = orders.get() # waits until an order arrives
prepare(order)
orders.task_done()
BlockingQueue<Order> orders = new ArrayBlockingQueue<>(100);
orders.put(order); // producer: blocks while full
Order next = orders.take(); // consumer: blocks while empty
The bounded size matters. When consumers fall behind, producers slow down instead of filling memory. That is called backpressure. In an interview, prefer a blocking queue over a hand-written condition variable whenever the problem has the shape "some threads hand work to others." It is less code and far fewer ways to get it wrong.
Failure Modes to Name
Interviewers listen for precise words. "There might be a threading issue" earns little; "two threads can both pass the check and double-book the seat" earns a lot. These are the failure modes you should be able to name and fix:
| Failure mode | What goes wrong | Usual fix |
|---|---|---|
| Lost update | two read-modify-writes interleave and one write overwrites the other | a lock, or an atomic for a single value |
| Check-then-act | a thread acts on a check another thread has since made false | check and act under the same lock |
| Stale read (visibility) | a thread never sees another thread's write | locks, atomics or volatile |
| Deadlock | two threads each hold a lock the other needs, so both wait forever | take locks in one fixed order; tryLock with a timeout |
| Missed signal | a notify happens before the waiter starts waiting, so it sleeps forever | check the condition and wait under the same lock |
| Starvation | a thread waits indefinitely because others keep winning the lock | fair locks, or shorter critical sections |
The first three are correctness bugs that corrupt data. The last three make threads stop making progress. Both kinds are silent: no exception, no stack trace, just wrong numbers or a frozen program, often only under load. That is why you design them out up front instead of hoping to find them in testing.
Language Reference
The ideas are the same everywhere; the names differ. Use this table to translate.
| Tool | Java | Python | C++ | Go |
|---|---|---|---|---|
| Start a thread | Thread, ExecutorService |
threading.Thread, ThreadPoolExecutor |
std::thread, std::jthread (C++20) |
go f() (goroutine) |
| Lock | synchronized, ReentrantLock |
threading.Lock, RLock |
std::mutex with std::lock_guard |
sync.Mutex |
| Read-write lock | ReentrantReadWriteLock |
none built in | std::shared_mutex (C++17) |
sync.RWMutex |
| Atomic | AtomicInteger, AtomicLong, AtomicReference |
none (use a lock) | std::atomic<T> |
sync/atomic (atomic.Int64) |
| Semaphore | Semaphore |
threading.Semaphore, BoundedSemaphore |
std::counting_semaphore (C++20) |
buffered channel, or x/sync/semaphore |
| Condition variable | wait/notifyAll, Condition |
threading.Condition |
std::condition_variable |
sync.Cond (channels are more common) |
| Blocking queue | ArrayBlockingQueue, LinkedBlockingQueue |
queue.Queue |
none built in (mutex + condition variable) | channel (make(chan T, n)) |
| Wait for tasks to finish | CountDownLatch, Future.get |
Thread.join, concurrent.futures.wait |
join, std::latch (C++20) |
sync.WaitGroup |
| Visibility | volatile, locks, atomics |
locks | std::atomic, mutexes |
channels, mutexes, atomics |
Two notes on the table. In Go, the idiom is "share memory by communicating": instead of locking a shared map,
one goroutine owns the map and others send it requests over a channel. In C++, always lock through an RAII guard
(std::lock_guard, std::scoped_lock) so the mutex is released when the scope ends, the same way Python's with
and Java's finally do.
The Three Kinds of Concurrency Problems
Almost every concurrency question in an LLD interview falls into one of three kinds. Recognizing which one you have tells you which tool to reach for.
Correctness: Can Two Threads Corrupt Shared State?
The state is shared and mutable, and an invariant must hold: a balance never goes negative, a seat is sold once, a cache's map and its recency list agree. Threads don't need to wait for each other; they just must not step on each other.
- Tools: a lock around each critical section; atomics when the state is one counter or flag.
- Typical problems: Movie Ticket Booking (double booking), Digital Wallet (lost updates on transfers), a thread-safe LRU Cache, Inventory Management, Auction System (concurrent bids).
- Go deeper: Race Conditions, Locks and Atomics, Deadlocks, Livelocks and Starvation (transfers that lock two accounts), and Lock-Free Programming.
Coordination: Does One Thread Need to Wait for Another?
The threads have an order or a handoff: a consumer can't run until a producer has made something, a writer must flush before shutdown, step B starts after step A. The question is not "who may touch this?" but "when may this thread continue?"
- Tools: a blocking queue for handoffs; a condition variable for custom "wait until" rules; latches, futures
or
joinfor "wait until these tasks finish." - Typical problems: Logging Framework (async buffer and flush), Job Scheduler (worker pool), Web Crawler (workers pulling URLs), Message Queue (producers and consumers).
- Go deeper: Thread Coordination, Multithreading Patterns and Classic Concurrency Problems (print in order, bounded buffer).
Scarcity: Is There a Fixed Number of Something?
There are N of a resource (database connections, API calls per second, parallel downloads) and more threads than N want one. Threads beyond the limit must wait, be rejected, or time out.
- Tools: a semaphore with N permits; a bounded blocking queue that holds the N resources themselves;
tryAcquirewith a timeout when waiting forever is not acceptable. - Typical problems: Connection Pool (borrow and return connections), Rate Limiter (permits per time window), the semaphore-capped client above.
- Go deeper: Semaphores and Resource Pools.
Real problems often mix kinds. A connection pool is scarcity (N connections) plus correctness (the list of free connections must not be corrupted). Name each part and use the tool for it: "a semaphore of 10 permits for the limit, and a lock around the free list," or simply a blocking queue holding the 10 connections, which handles both.
Concurrency in an Interview
When concurrency comes up, walk through it in the same order every time.
- Find the shared mutable state. List the fields that more than one thread can write: "the spot map in
ParkingLotand each spot'svehiclefield." Everything else needs nothing. - State the invariant and the race. "A spot holds at most one vehicle. Two
parkcalls could both see spot 7 free and both take it: a check-then-act race." Naming the failure mode precisely is half the credit. - Classify it. Correctness, coordination or scarcity. That picks the tool.
- Start coarse. One lock on the orchestrator class, held for the whole operation, is correct and easy to reason about. Say so, then offer to refine.
- Refine only if asked. Per-level or per-spot locks for more parallelism, a read-write lock when reads dominate, atomics for counters. Each refinement brings new risks (deadlock with several locks), so mention them.
🎯 Interview tip: a single coarse lock you can defend beats fine-grained locking you can't. Interviewers mark down clever schemes with a hole far more than a simple lock with a clear explanation of its throughput limit.
A few things that reliably impress: keeping I/O outside critical sections, using while around every wait,
releasing locks in finally (or with), choosing a blocking queue instead of rolling your own, and being honest
about Python ("the GIL makes this race rarer, not impossible, so I still lock").
Summary
- Concurrency bugs need shared, mutable state. Locals are private to a thread; heap objects are shared.
- A lost update happens when read-modify-write steps interleave; check-then-act races act on a check that is no longer true. Both are fixed by making the critical section atomic.
- In Java and C++, unsynchronized writes may not even be visible to other threads; locks, atomics and
volatilefix that. - The toolbox: atomics for one variable, locks for critical sections, semaphores to cap how many, condition variables to wait until a condition holds, blocking queues for producer-consumer handoffs.
- Name the failure modes precisely: lost update, check-then-act, deadlock, missed signal.
- Classify every question as correctness (locks, atomics), coordination (queues, condition variables) or scarcity (semaphores, bounded pools), then start with the simplest correct tool and refine only when asked.