AlgoViz

Concurrency in an LLD round

medium 40 min

Sooner 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

0:00 / 5:07

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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

Step 1 of 4

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.

Saturday at the ice rink
on the ice6GATEGATE6, so 76, so 7779I waitDINGsize 38emptyemptyI wait

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

KindQuestion that finds itFirst toolWhat the tool gives you
CorrectnessCan two callers act on the same old value?A lock around look and changeOne at a time
CoordinationWho waits for whom, and who wakes them?A blocking queueWait without asking, hand over safely
ScarcityWhat runs out, and what happens then?A semaphore, or a poolAt most N inside, the rest wait or hear no
They mix. A job scheduler has all three: a job must not run twice, workers wait for jobs, and there are only so many workers.

Which kind is it?

Ask in this order. Correctness comes first, because a wrong result is worse than a slow one. Then ask the other two questions as well, since one spot can have two kinds.

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. 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. 2

    Is it written?

    After construction, does anybody change it? Constants and immutable objects drop out here.

  3. 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. 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. 5

    Who waits, and what runs out?

    Look for sleep in a loop, queues without a limit, and things with a fixed number: connections, machines, licences.

Where the threads meet

Rink- places: int- onIce: int- pairs: List<Pair>- ready: List<Pair>+ enter(): bool+ leave()+ rent(): Pair+ putReady(pair)+ takeReady(): Pair

1/5One object

The rink holds everything. With one caller it is fine, and it is what you should write first.

uses

A class diagram shows who can reach what. Two arrows into one changeable class: that is the place to look.

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.

1 of 6

Why it is built this way

  • TypeScript shows the rule for event loops: between two awaits nobody else runs. The gap opens at the await.
  • 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 seeHidden gapKind
if key not in map: map[key] = make()Two callers make two objectsCorrectness
count += 1, balance -= nRead, compute, writeCorrectness
if self._instance is None: ...Two instancesCorrectness
for x in self.items: while others addThe collection changes under the loopCorrectness
while not ready: sleep(0.1)Wasted work, late reactionCoordination
Thread(...).start() for each requestNo limit on threadsScarcity
queue = [] that only growsMemory is the limitScarcity
conn = pool.get() and no finallyA lost connection after an errorScarcity

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

Rink- gate: Gate- bench: Bench- skates: SkatesGate- lock: Lock- onIce: int+ enter(): bool+ leave()

1/4Correctness

Gate keeps the count and the lock together. Nobody can touch one without the other.

owns (dies together)

The guard lives beside the data it guards. This is encapsulation, applied to time.

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 -= 1

Line 6

The most useful line: which field, which lock, which rule. A reviewer can now check each method in seconds.

1 of 4

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. 1

    Share

    "Gate is shared: every gate thread calls it, and onIce is written."

  2. 2

    Rule

    "The rule is: never more than places. It breaks if two threads see the last place."

  3. 3

    Guard

    "So the check and the change are one step, under one lock that lives in Gate."

  4. 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

  1. Interviewer

    Is your parking lot thread-safe?

  2. 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.

  3. You

    park looks 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 inside Lot. The ticket is immutable, so it needs nothing.

  4. Interviewer

    Why not make every method synchronized?

  5. You

    It would work for Lot. But leave also 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.

  6. Interviewer

    And if we have fifty gates?

  7. 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

Draw this on the board. Six arrows convince more than the word race.

When

The right moment in 45 minutes

Where concurrency fits

The steps of the execution flow, with the one thing to do for concurrency at each step.

What to say at each step

StepSayDo 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?

"No locks, because one caller owns the board" is a good answer. Silence is not.

Practice

Three prompts, scanned

One pass over common prompts

PromptShared and writtenRuleKindGuard to offer
Parking lotFree spotsOne spot, one ticketCorrectnessLock in the lot or the floor
Movie ticketsSeats of one showOne seat, one bookingCorrectnessHold with an end time, per show
LoggerOpen fileLines stay whole and in orderCoordinationQueue and one writer thread
Job schedulerJob state, queue, workersA job starts onceAll threeClaim under a lock, queue, fixed pool
Rate limiterCounter per userAt most N in a windowCorrectnessOne lock per user
LRU cacheMap and listBoth hold the same keysCorrectnessOne lock: even reading moves nodes
ElevatorRequest set of one carNo request is lostCoordinationQueue into one control loop
Vending machineBalance and stockPay once, get oneCorrectnessOne event at a time
ChessThe boardTurns alternateNone in memorySay: 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
  • volatile as a cure for counting
  • Talks about servers when the scope is one process

Words

The same idea in four languages

What to reach for

NeedPythonJavaC++TypeScript
One at a timethreading.Locksynchronized, ReentrantLockstd::mutex with lock_guardNo await in between
CounterLock and += 1AtomicInteger, LongAdderstd::atomic<int>n++
Make once per keyLock and dictcomputeIfAbsentLock and mapMap of promises
Hand overqueue.QueueBlockingQueueMutex and condition variablePromise resolvers
At most Nthreading.SemaphoreSemaphorestd::counting_semaphore (C++20)A counter and a line
Result laterconcurrent.futuresCompletableFuturestd::futurePromise
Know your own column by heart. Say the idea first and the class name second.

Limits

Where the lock ends

How far does a guard reach?

An in-process lock knows nothing of the second server. If the interviewer moves there, say it and go to concurrency control.

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.

Sources