Concurrency in Low-Level Design Interviews
Many low-level design interviews end with the same twist: "Now two thousand users hit this at once. Is your design still correct?" This lesson is for software engineers preparing for that moment. It shows the bugs concurrency introduces, the tools that fix them, and how to talk about the trade-offs. The examples are in Java because it has real threads and a standard concurrency library; the ideas carry over to any language with shared memory.
If you have not read it yet, start with Low-Level Design Interviews: Modeling a System in Code. This lesson assumes you already have classes on the board and now need to make them safe.
When concurrency enters the interview
The interviewer rarely says "concurrency" up front. Listen for these signals instead:
A shared count: available parking spots, remaining stock, tokens in a rate limiter.
A limited resource many people want: seats for a show, a locker, a meeting room.
A cache or registry read by many threads and updated by a few.
Work handed between parts of the system: orders placed by one component and processed by another.
When you see one of these, say so before you are asked: "Bookings can arrive concurrently, so I will make the seat assignment atomic." Raising it yourself is a strong signal; being caught out by it is a weak one.
The core bug: check, then act
Almost every concurrency bug in an interview is the same shape. A thread checks a condition, then acts on it, and another thread changes the world in between.
class Show {
private final Set<String> bookedSeats = new HashSet<>();
// Broken: two threads can both see the seat as free, then both book it.
boolean book(String seatId) {
if (bookedSeats.contains(seatId)) {
return false;
}
bookedSeats.add(seatId);
return true;
}
}Walk the interviewer through the interleaving out loud: thread A checks seat C7 and finds it free; thread B checks C7 and finds it free; both add it and both return true. Two customers now hold one seat. HashSet is also not safe for concurrent modification at all, so the set itself can be corrupted.
There are two ways to fix it, and naming both shows judgment.
Make the check and the act one atomic step. Concurrent collections offer operations that do this for you:
class Show {
private final Set<String> bookedSeats = ConcurrentHashMap.newKeySet();
boolean book(String seatId) {
// add() returns false if the seat was already present; check and act are one step.
return bookedSeats.add(seatId);
}
}Or guard the whole sequence with a lock, which you need as soon as the logic spans more than one call.
Locks and critical sections
A mutex (in Java, synchronized or a ReentrantLock) lets one thread at a time run a block of code, the critical section. Everything that reads or writes the shared state must hold the same lock, or the lock protects nothing.
class ParkingLot {
private final Deque<Spot> freeSpots = new ArrayDeque<>();
private final ReentrantLock lock = new ReentrantLock();
Optional<Spot> assignSpot() {
lock.lock();
try {
return Optional.ofNullable(freeSpots.pollFirst());
} finally {
lock.unlock(); // always in finally, or an exception leaves the lock held forever
}
}
}Two rules keep locks from becoming the bottleneck:
Keep the critical section small. Compute prices, format receipts and send notifications outside the lock. Hold it only while touching shared state.
Lock at the right granularity. One lock for the whole parking lot is simple and correct; one lock per floor lets cars park on different floors in parallel. Start coarse, then say where you would split it if contention became a problem.
Atomic variables and compare-and-set
For a single number, a lock is heavier than necessary. Atomic classes use the processor's compare-and-set (CAS) instruction: "set this to the new value only if it still equals what I read".
class PermitPool {
private final AtomicInteger available;
PermitPool(int permits) {
this.available = new AtomicInteger(permits);
}
boolean tryAcquire() {
while (true) {
int current = available.get();
if (current == 0) {
return false;
}
if (available.compareAndSet(current, current - 1)) {
return true;
}
// Another thread changed the count between get() and compareAndSet(): retry.
}
}
void release() {
available.incrementAndGet();
}
}This is lock-free: no thread ever blocks, and a thread that loses the race simply retries. It works well for counters and simple rate limiters. It does not scale to invariants across several variables; for those, use a lock. In a real codebase you would reach for java.util.concurrent.Semaphore here, and it is worth saying so after showing you understand what it does.
Read-write locks
When reads vastly outnumber writes, a read-write lock lets many readers in at once while writers get exclusive access.
class ConfigCache {
private final Map<String, String> values = new HashMap<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
String get(String key) {
lock.readLock().lock();
try {
return values.get(key);
} finally {
lock.readLock().unlock();
}
}
void put(String key, String value) {
lock.writeLock().lock();
try {
values.put(key, value);
} finally {
lock.writeLock().unlock();
}
}
}Two cautions earn points. First, for a single map, ConcurrentHashMap is simpler and faster; a read-write lock pays off when a read must see several fields consistently. Second, make sure your "reads" really are reads. In an LRU cache, get moves the entry to the front of the recency list, which is a write. Putting get under a read lock would let two threads reorder the list at once and corrupt it. That is a favorite follow-up on the LRU cache problem.
Deadlock and lock ordering
Deadlock needs four conditions at once: exclusive locks, a thread holding one lock while waiting for another, no way to take a lock away, and a cycle of waiting threads. Break any one and deadlock cannot happen. In interviews, the practical fix is breaking the cycle with a global lock order.
The classic setup is booking several seats at once, all or nothing. If customer A locks seat C7 then waits for C8, while customer B locks C8 then waits for C7, both wait forever. Always acquiring locks in the same order (here, sorted by seat id) makes the cycle impossible:
class Show {
private final Map<String, ReentrantLock> seatLocks = new ConcurrentHashMap<>();
private final Map<String, String> customerBySeat = new ConcurrentHashMap<>();
boolean bookAll(List<String> seatIds, String customerId) {
List<String> ordered = new ArrayList<>(seatIds);
Collections.sort(ordered); // one global order: no cycle, so no deadlock
List<ReentrantLock> held = new ArrayList<>();
try {
for (String seatId : ordered) {
ReentrantLock lock = seatLocks.computeIfAbsent(seatId, id -> new ReentrantLock());
lock.lock();
held.add(lock);
}
for (String seatId : ordered) {
if (customerBySeat.containsKey(seatId)) {
return false; // all or nothing
}
}
for (String seatId : ordered) {
customerBySeat.put(seatId, customerId);
}
return true;
} finally {
for (int i = held.size() - 1; i >= 0; i--) {
held.get(i).unlock();
}
}
}
}Other options worth naming: tryLock with a timeout, which backs off instead of waiting forever, and a single coarse lock per show, which removes deadlock entirely at the cost of parallelism.
Producer and consumer
When one part of the system creates work and another processes it, put a bounded blocking queue between them:
BlockingQueue<Order> pending = new ArrayBlockingQueue<>(1_000);
// Producer: blocks when the queue is full, which slows intake instead of exhausting memory.
pending.put(order);
// Consumer: blocks when the queue is empty instead of spinning.
Order next = pending.take();The bound is the point. An unbounded queue hides overload until the process runs out of memory; a bounded one applies backpressure. Say what happens when it is full: block, drop, or reject with an error, and which fits the product.
Thread-safe singletons
If your design has a single shared instance (an id generator, a dispatcher), the lazy-initialization race is a standard question. The holder idiom is safe because the JVM initializes a class exactly once:
final class IdGenerator {
private IdGenerator() {}
private static final class Holder {
static final IdGenerator INSTANCE = new IdGenerator();
}
static IdGenerator getInstance() {
return Holder.INSTANCE;
}
}If you write double-checked locking instead, the field must be volatile; without it another thread can see a partly constructed object. Better still, mention that passing the instance in through the constructor avoids the global entirely and makes the class testable.
Follow-ups to expect
"Where exactly is the race?" Point at the line between the check and the act, and describe the interleaving.
"Why a lock and not an atomic?" Atomics protect one variable; your invariant spans several.
"What if this runs on three servers?" In-process locks stop at the process boundary. The fix moves to the database: a unique constraint on (show, seat), a conditional update, or a row lock. This is where low-level design meets system design.
"How would you test it?" Run many threads against the method in a loop and assert the invariant (no seat sold twice, count never negative). Note that passing tests do not prove absence of races; reasoning about the critical sections does.
What changes with seniority
A junior candidate should spot the check-then-act race and fix it with a lock. A mid-level candidate should choose between a lock, an atomic and a concurrent collection, and keep critical sections small. A senior candidate should also discuss granularity, deadlock avoidance, what happens across processes, and the cost of each choice under contention.
Mistakes that cost points
Locking only the write. Readers of the same state need the lock too, or they can see half-updated data.
Unlocking outside
finally. One exception and the lock is held forever.Calling slow or external code while holding a lock. Network calls inside a critical section turn a lock into a queue.
Declaring everything
synchronized. It is correct but signals you have not thought about where the shared state is.Ignoring the multi-server case when the interviewer hints at it.
Practice it
Take the LRU cache problem and, once your single-threaded version works, make it thread-safe out loud: name the shared state, choose a lock and justify why get cannot use a read lock. Then redo the seat-booking example from memory, including the lock ordering, in under ten minutes.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Design an Elevator System: A Low-Level Design Walkthrough
Walk an elevator design end to end: requirements, entities, a state-pattern state machine, LOOK stop ordering, a cost-based dispatch strategy, extensions without a rewrite, and concurrency.
9 min read
- Low-Level Design Interviews: Modeling a System in Code
Turn a small real-world system into classes and interfaces with a seven-step flow, apply SOLID and four core patterns where they earn their place, and extend the design without rewriting it.
8 min read
