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

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

request 1ashaseesrequest 2leeseesserviceOrderServicecurrent usernonecopies1

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

    critical

    The decision was made on an old value.

    Wrong
    if n < places:    with lock: n += 1
    Right
    with lock:    if n < places: n += 1
  • Two safe calls in a row

    critical

    The gap lies between them.

    Wrong
    if key not in cache:    cache[key] = make(key)
    Right
    with lock:    if key not in cache: cache[key] = make(key)
  • Asking in a loop

    major

    Wasted work and a late answer.

    Wrong
    while not ready:    sleep(0.1)
    Right
    item = ready.get(timeout=5)
  • Permit before the thing

    major

    A guest with a permit finds an empty shelf.

    Wrong
    permits.release()shelf.put(pair)
    Right
    shelf.put(pair)permits.release()
  • Request data in a service field

    critical

    All requests share the one service.

    Wrong
    self.user = user
    Right
    def 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