Concurrency in an LLD round
medium 40 minSooner or later the interviewer asks what happens when two users do it at the same time.
Video lesson · Chapter 1 of 6
Make a prediction
Concurrency in an LLD round
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
Concurrency means that several pieces of work are in progress during the same time. They may really run at the same moment on two processor cores, or take turns on one. For your design the danger is the same: between any two steps of one caller, steps of another caller may happen.
In a low-level design round the topic is small and sharp. The program usually runs in one process, with several threads (or several async handlers) that call the same objects. The question is which objects, which rules, and which guard.
All trouble falls into three kinds. Correctness: shared data ends up wrong. Coordination: one must wait for another. Scarcity: there are fewer things than takers. Each kind has standard tools, so naming the kind is half of the answer.
Why it exists
A race gives no error. The code passes its tests, works in the demo, and sells one seat twice on a busy evening. So interviewers look for people who see it while reading, and not for people who know many lock classes.
It also tests ownership. If you can say which class owns a rule, you know where the guard goes. If several classes share a rule, the guard has no home, and the design has a problem even with one thread.
And it tests restraint. Locks everywhere make code slow, hard to read and able to block itself. A strong answer guards the one place that needs it and says why the others do not.
A short history
1965
Edsger Dijkstra's notes Cooperating Sequential Processes state the problem of critical sections: at any moment at most one process may be inside. They also introduce the semaphore.
2004
The revised Java memory model, JSR-133, is released on 30 September. It says precisely what one thread may see of another thread's writes.
2013
Go 1.1 ships a race detector, announced on the Go blog on 26 June. Finding unprotected shared access becomes a command line flag.
2025
PEP 779 is resolved on 16 June: the free-threaded build of Python becomes officially supported in 3.14.
Words to know
- Thread
- One sequence of steps. Threads of a process share its memory.
- Shared state
- Data that more than one thread can reach.
- Race condition
- The result depends on an order that nobody controls.
- Critical section
- Steps that must not be mixed with another caller's steps.
- Atomic
- Seen from outside, it happens completely or not at all, with nothing in between.
- Invariant
- A rule that holds whenever nobody is in the middle of a change.
- Thread-safe
- Keeps its rules under any mix of callers, without extra work by them.
- Back pressure
- A full queue slows down those who fill it.
How it works
Step through the idea, or press Play.
See. Shared, written, rule, gap, wait
Understand it
Start here
A second gate opens
Most classes you design in the round are correct as long as one person uses them at a time. Then the interviewer asks one short question: "what if two requests arrive together?" This page is about that moment: how to see the trouble, how to name it, and how to say the fix in a few sentences. The deep pages are linked at each step.
The same rink, three different troubles. Each one has its own fix, so the first step is to name it.
Name it
Three kinds of trouble
Which one do you hear?
Correctness
Several threads read and change the same data. Words: last seat, balance, counter, unique, at most. Danger: a rule is broken without any error. Open the page.
Coordination
One thread needs something that another one produces. Words: queue, worker, when ready, notify, in order, background. Danger: busy waiting, or waiting for ever. Open the page.
Scarcity
There are fewer things than takers. Words: pool, limit, at most N at a time, connections, machines. Danger: overload, leaks, starvation. Open the page.
Same rink, three questions
| Kind | Question that finds it | First tool | What the tool gives you |
|---|---|---|---|
| Correctness | Can two callers act on the same old value? | A lock around look and change | One at a time |
| Coordination | Who waits for whom, and who wakes them? | A blocking queue | Wait without asking, hand over safely |
| Scarcity | What runs out, and what happens then? | A semaphore, or a pool | At most N inside, the rest wait or hear no |
Which kind is it?
See it
Five questions over a finished class
Write the class for one caller first. Then put your finger on each field and ask. You need about a minute.
Finger on the field
- 1
Is it shared?
Can two threads reach this object? Local variables and objects made inside one request are not shared. Services, repositories, caches and static fields are.
- 2
Is it written?
After construction, does anybody change it? Constants and immutable objects drop out here.
- 3
Which rule needs it?
Say the rule as a sentence: at most 200 on the ice. If a rule speaks about two fields, they need the same guard.
- 4
Where is the gap?
Look for a decision followed by a change:
if ... then change,get ... then put,x += 1, a loop over a collection that somebody else may change. - 5
Who waits, and what runs out?
Look for
sleepin a loop, queues without a limit, and things with a fixed number: connections, machines, licences.
Where the threads meet
1/5One object
The rink holds everything. With one caller it is fine, and it is what you should write first.
uses
Reading a class for trouble
Nothing here is badly written. Every mark below is a place where a second caller changes the result.
import timeclass Rink: def __init__(self, places, pairs): self.places = places self.on_ice = 0 self.pairs = list(pairs) self.ready = [] def enter(self): if self.on_ice >= self.places: return False self.on_ice += 1 return True def leave(self): self.on_ice -= 1 def rent(self): if not self.pairs: return None return self.pairs.pop() def put_ready(self, pair): self.ready.append(pair) def take_ready(self): while not self.ready: time.sleep(0.1) return self.ready.pop(0)Lines 5 to 9
Four fields. places never changes after this, so cross it off. The other three are written later: three places to look at.
Why it is built this way
- TypeScript shows the rule for event loops: between two
awaits nobody else runs. The gap opens at theawait. - Nothing in this class says how it may be used. One comment, "not thread-safe, one caller only", is already an improvement.
Shapes to recognise at a glance
| You see | Hidden gap | Kind |
|---|---|---|
if key not in map: map[key] = make() | Two callers make two objects | Correctness |
count += 1, balance -= n | Read, compute, write | Correctness |
if self._instance is None: ... | Two instances | Correctness |
for x in self.items: while others add | The collection changes under the loop | Correctness |
while not ready: sleep(0.1) | Wasted work, late reaction | Coordination |
Thread(...).start() for each request | No limit on threads | Scarcity |
queue = [] that only grows | Memory is the limit | Scarcity |
conn = pool.get() and no finally | A lost connection after an error | Scarcity |
Fix it
One small part for each kind
Do not put one big lock over everything. Give each kind its own small class with its own guard. The bodies below are short on purpose: libraries already contain the hard parts, and the pages behind the links explain them.
Three parts, three guards
1/4Correctness
Gate keeps the count and the lock together. Nobody can touch one without the other.
owns (dies together)
The rink with guards
One lock, one field, one rule, written above the class.
import queueimport threadingclass Gate: """Correctness. on_ice is guarded by _lock. Rule: on_ice <= places.""" def __init__(self, places): self._lock = threading.Lock() self._places = places self._on_ice = 0 def enter(self): with self._lock: if self._on_ice >= self._places: return False self._on_ice += 1 return True def leave(self): with self._lock: if self._on_ice == 0: raise ValueError("nobody is on the ice") self._on_ice -= 1Line 6
The most useful line: which field, which lock, which rule. A reviewer can now check each method in seconds.
Why it is built this way
- More ways to guard one value (atomics, confinement, immutable objects) are on the correctness page.
Say it
Four sentences
Interviewers cannot see what you noticed. Four sentences make it visible, and they take less than half a minute.
Share, rule, guard, price
- 1
Share
"
Gateis shared: every gate thread calls it, andonIceis written." - 2
Rule
"The rule is: never more than
places. It breaks if two threads see the last place." - 3
Guard
"So the check and the change are one step, under one lock that lives in
Gate." - 4
Price
"The price is that gates wait for each other, for a compare and an add. If that ever hurts, one lock per zone."
The same minute, word for word
Interviewer
Is your parking lot thread-safe?
You
Not yet, and I left one mark for it. Shared is the set of free spots: each gate thread calls
park. The rule is that a spot is never on two tickets.You
parklooks for a free spot and then takes it. Two gates can pick the same one. I make those two lines one step with a lock insideLot. The ticket is immutable, so it needs nothing.Interviewer
Why not make every method synchronized?
You
It would work for
Lot. Butleavealso calls the payment service, and I do not want to hold the lock while a network answers. So I lock only the parts that touch the spots.Interviewer
And if we have fifty gates?
You
The lock is held for a few memory operations. I would measure first. If it shows, one lock per floor, because the rule is per spot and a spot belongs to one floor.
The interviewer asks: "what if two users do this at the same time?" How do you answer?
Breaks"I would add synchronized"
- How
- Every method gets the keyword, or every field becomes a concurrent collection.
- Limit
- No rule was named, so nobody knows what is now safe. Two safe calls in a row still have a gap between them.
- Choose when
- Never as the whole answer.
WorksName the race and lock it
- How
- Show the two lines, give one unlucky order, put a lock around them.
- Limit
- Correct. It says nothing about waiting, about slow calls inside the lock, or about a better place for the guard.
- Choose when
- Junior and mid level, or with little time left.
StrongShare, rule, guard, price
- How
- Name the shared state, the rule, the smallest guard that keeps it, and the cost. Offer the next step and say when you would take it.
- Limit
- Takes half a minute, so do it for one or two places and not for all.
- Choose when
- Always the goal.
Show one unlucky order
When
The right moment in 45 minutes
Where concurrency fits
What to say at each step
| Step | Say | Do not |
|---|---|---|
| Scope | "Several users at once, in one process?" | Design for threads nobody asked for |
| Entities | "The shared one is the lot." | Put locks into every entity |
| Class design | "This rule is owned here, so its guard goes here." | Hand out the inner list |
| Implementation | "I write it for one caller and mark the critical part." | Start with lock code and lose the logic |
| Verification | "Two callers, last spot: here is the order." | Say thread-safe without an argument |
| Extension | "If it waits too long, I split by floor." | Offer lock-free code as a first step |
Do I need to talk about it at all?
Practice
Three prompts, scanned
One pass over common prompts
| Prompt | Shared and written | Rule | Kind | Guard to offer |
|---|---|---|---|---|
| Parking lot | Free spots | One spot, one ticket | Correctness | Lock in the lot or the floor |
| Movie tickets | Seats of one show | One seat, one booking | Correctness | Hold with an end time, per show |
| Logger | Open file | Lines stay whole and in order | Coordination | Queue and one writer thread |
| Job scheduler | Job state, queue, workers | A job starts once | All three | Claim under a lock, queue, fixed pool |
| Rate limiter | Counter per user | At most N in a window | Correctness | One lock per user |
| LRU cache | Map and list | Both hold the same keys | Correctness | One lock: even reading moves nodes |
| Elevator | Request set of one car | No request is lost | Coordination | Queue into one control loop |
| Vending machine | Balance and stock | Pay once, get one | Correctness | One event at a time |
| Chess | The board | Turns alternate | None in memory | Say: one caller per game |
Sounds senior
- Names the rule before the lock
- Shows one unlucky order
- Keeps slow calls outside the lock
- Says what is already safe, and why
- Knows where the process ends
Sounds nervous
- "I will use a concurrent map" and nothing more
- Locks on every getter
- Two locks, no order
volatileas a cure for counting- Talks about servers when the scope is one process
Words
The same idea in four languages
What to reach for
| Need | Python | Java | C++ | TypeScript |
|---|---|---|---|---|
| One at a time | threading.Lock | synchronized, ReentrantLock | std::mutex with lock_guard | No await in between |
| Counter | Lock and += 1 | AtomicInteger, LongAdder | std::atomic<int> | n++ |
| Make once per key | Lock and dict | computeIfAbsent | Lock and map | Map of promises |
| Hand over | queue.Queue | BlockingQueue | Mutex and condition variable | Promise resolvers |
| At most N | threading.Semaphore | Semaphore | std::counting_semaphore (C++20) | A counter and a line |
| Result later | concurrent.futures | CompletableFuture | std::future | Promise |
Limits
Where the lock ends
How far does a guard reach?
Five sentences that save you
On granularity
"One lock is correct and simple. I split it when a measurement shows waiting."
On slow calls
"I never call the outside while holding the lock: reserve, call, confirm."
On two locks
"Always in the same order, smaller id first." See deadlocks.
On many readers
"An immutable snapshot, swapped in one step." Or a read-write lock.
On the answer later
"I return a future, so the caller decides when to wait." See future and promise.
Summary
The whole topic in one minute.
Concurrency questions in this round are about one sentence: between two steps of mine, somebody else may act. Look for fields that are shared and written, for a decision followed by a change, for waiting in a loop, and for things that can run out.
Name the kind, then speak in four sentences: what is shared, which rule can break, which guard keeps it, what it costs. Show one unlucky order. Then stop, unless asked for more.
- Write it for one caller, then put a finger on every field: shared, written, rule, gap, wait.
- Name the kind: correctness (wrong result), coordination (waiting), scarcity (too few).
- Say four sentences: share, rule, guard, price.
- Show one unlucky order. Six arrows are enough.
- The guard lives in the class that owns the rule.
- Say what is safe already, and where your lock ends.