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
See it run
See the shared field, name the kind, guard it, say it
Operations
Finger on the field
Scan a finished class.
Step 1 of 5
Four fields
| shared? | written? | rule | kind | |
|---|---|---|---|---|
| places | ||||
| on_ice | ||||
| pairs | ||||
| ready |
One class, written for one caller. Put your finger on each field.
Step 1: Four fields
class Rink: def __init__(self, places, pairs): self.places = places self.on_ice = 0 self.pairs = list(pairs) self.ready = []- When
- After the code
- You leave with
- A list of places
Cross off what is never written. The list gets short.
In the real world
The same concurrency in an lld round doing real jobs. Pick one and step through it.
One service object for all requests.
Step 1 of 5
One copy
The framework makes one service and gives it to every request.
Step 1: One copy
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Lock only the change
criticalThe decision was made on an old value.
Wrongif n < places: with lock: n += 1Rightwith lock: if n < places: n += 1Two safe calls in a row
criticalThe gap lies between them.
Wrongif key not in cache: cache[key] = make(key)Rightwith lock: if key not in cache: cache[key] = make(key)Asking in a loop
majorWasted work and a late answer.
Wrongwhile not ready: sleep(0.1)Rightitem = ready.get(timeout=5)Permit before the thing
majorA guest with a permit finds an empty shelf.
Wrongpermits.release()shelf.put(pair)Rightshelf.put(pair)permits.release()Request data in a service field
criticalAll requests share the one service.
Wrongself.user = userRightdef orders(self, user): ...
Interview tips
See
- Finger on each field
- Shared and written?
- Decide, then change?
Name
- Correctness: wrong
- Coordination: waiting
- Scarcity: not enough
Guard
- Remove sharing first
- Then the smallest lock
- In the owner of the rule
Say
- Share, rule, guard, price
- One unlucky order
- What is safe already