AlgoViz

Scarcity: limited resources

hard 50 min

When more threads want something than there is of it, a design must say who gets it, who waits, for how long, and how it comes back.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:03

Scarcity: limited resources

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

A scarce resource is something that fewer threads can use at once than want to: database connections, licences, memory, slots of a slow service. Scarcity control decides who uses it and what happens to the rest.

There are four tools. A pool lends objects, permits count rights, a quota divides them among customers, and backpressure limits how much work may wait. They are often stacked.

Why it exists

Without a limit the thing itself decides, usually by failing for everybody. With a limit but without a lease the limit shrinks until nothing is left. With a lease but without a line limit, everybody waits longer than it is worth.

It is also a question of justice. One customer, one night job or one large request can take everything, or never get anything. The rule has to be written down, and it is usually only a few lines.

A short history

  1. 1961

    John Little proves L = lambda x W, the law that connects arrivals, time and the number in the system.

  2. 1965

    Edsger Dijkstra's Cooperating Sequential Processes (EWD123) describes the general semaphore and a bounded buffer.

  3. 2004

    Java 5 brings Semaphore, with a choice between fair and unfair, and bounded blocking queues.

  4. 2015

    Reactive Streams appears: the receiver tells the sender how many items it may send. In 2017 its interfaces become part of Java 9 as java.util.concurrent.Flow.

  5. 2016

    Google's Site Reliability Engineering book describes per-customer limits, request criticality and client-side throttling in its chapter on handling overload.

Words to know

Pool
A set of objects that are lent, used and given back.
Lease
The right to use one object until it is given back, with a way to give back exactly once.
Permit
One unit of a count. Carries no object and, in a plain semaphore, no owner.
Quota
The most that one customer may hold.
Budget
A sum that requests of different size share.
Backpressure
The slow side makes the fast side slow down.
Load shedding
Refusing work on purpose so that the rest is done in time.
Bulkhead
A wall between kinds of work, so that one cannot use up what the other needs.
Leak
Something lent that never comes back.
Starvation
Somebody waits forever although resources come free.
Utilisation
The share of time in which a resource is in use.
Fencing token
A growing number that makes an older lease worthless.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Ask. With a deadline

Understand it

Start here

Three scanners, twenty people

A library lends three document scanners to anybody who wants to digitise old letters. Twenty people come. Some will wait, some may have to come back, and one will take the key home. Every limited resource in a program has the same four questions: who gets it, who waits, for how long, and how does it come back?

Three telescopes on the roof
no lamp, notelescope

Pool, permits, leak, lease, backpressure, quota: one roof, six words.

Four tools

  • Pool

    Keeps real objects and lends them: connections, scanners, buffers. It gives you a thing.

  • Permits

    Only counts. It gives you the right to do something, for example eight downloads at a time. See semaphore.

  • Quota

    A limit for each customer inside the total limit. It decides how much is yours.

  • Backpressure

    Slows or refuses whoever brings more work than can be done. It protects the line.

Which tool?

Whatever you choose, you end at the same box: limit the line. Limits per second belong to the rate limiter.

Why

What goes wrong without it

Python
class ScanDesk:    def __init__(self):        self.free = [Scanner(), Scanner(), Scanner()]    def scan(self, page):        while not self.free:            # burns a processor            pass        scanner = self.free.pop()       # two threads may see one scanner        result = scanner.scan(page)     # throws: the scanner is lost        self.free.append(scanner)        return result
Five problems in ten lines: a busy loop, a race between looking and taking, a leak on error, no limit on who waits, and no way to close.

The design that hurts

freeScanDesk+ free: List<Scanner>(no line, no limit)+ scan(page): loopsScanner+ scan(page)

1/2A public list

Everybody can take, and everybody must remember to bring back.

useshas (lives on)

The smell: taking and giving back are two separate acts, written in many places.

Six things that are missing

WithoutYou seeTool
A limitMemory, sockets or licences run outPool or permits
A leaseThe pool gets smaller every dayGive back on every way out
A deadlineThreads pile up behind one slow scannerTimeout in borrow
A line limitEverybody waits minutes and nobody is served in timeRefuse early
A quotaOne customer makes all others waitLimit per customer
OrderBig requests never get throughA line that cannot be overtaken

Numbers

How many are enough?

Little's law

L=λ×WL = \lambda \times W
L is how many are in use on average, lambda how many requests come per second, W how long each one uses it. 0.5 pages per second, 5 seconds each: 0.5 x 5 = 2.5 scanners in use.

Three scanners at 5 seconds do at most 3 / 5 = 0.6 pages per second. At 0.5 per second they are in use 2.5 / 3 = 83 percent of the time, and a line forms now and then. At 0.9 per second the line grows by 0.9 - 0.6 = 0.3 per second, without end.

Python
def line_after(minutes, arrive, scanners, seconds_each, limit=None):    """Average numbers, no randomness: arrivals and work per second."""    can = scanners / seconds_each    waiting = refused = 0.0    for _ in range(minutes * 60):        waiting += arrive        waiting -= min(waiting, can)        if limit is not None and waiting > limit:            refused += waiting - limit            waiting = limit    return round(waiting), round(waiting / can), round(refused)for minutes in (1, 10, 60):    print(minutes, "min, no limit:", line_after(minutes, 0.9, 3, 5))print("10 min, at most 6 wait:", line_after(10, 0.9, 3, 5, limit=6))
Run it. After 10 minutes 180 people wait, and the last of them will wait 300 seconds. With a limit of 6 nobody waits longer than 10 seconds, and 174 are told at once.
Edit and run it in your browser

0.9 pages per second, 0.6 possible

AfterWaiting, no limitWait of the last oneWaiting, limit 6Wait of the last one
1 minute1830 s610 s
10 minutes180300 s610 s
60 minutes1,0801,800 s610 s
The same number of pages is scanned in both cases: 0.6 per second. A longer line serves nobody faster. It only makes everybody late.

The idea

Borrow, use, give back

The design that works

Borrower+ with pool.borrow()ScannerPool- size: int- alive: int- closed: bool+ borrow(timeout): Lease+ close(timeout): bool- giveBack(s, broken)

1/3The borrower sees two verbs

Borrow, and whatever the language does at the end of a block.

usesowns (dies together)depends on

A lease and not the bare scanner: so it can be given back twice without harm, and cannot be forgotten.

A waiting borrower

The lease is new, the scanner is the same.

Life of a pooled object

Four states count against the size: making, free, lent and closing.

Choosing

Wait, refuse, or grow?

All scanners are in use. A request comes. What should happen?

BreaksMake one more
How
The pool grows when it is empty.
Limit
Then it is not a limit. The database, the licence or the memory fails instead, for everybody.
Choose when
Only when the resource is in truth not scarce.
WorksWait with a deadline
How
Sleep until something comes back, at most some seconds.
Limit
The line itself has no limit. Under overload all wait up to the deadline, and then all fail.
Choose when
Short bursts, few callers.
StrongShort line, then refuse
How
At most n wait, each with a deadline. Beyond that: a quick no with a hint when to come back.
Limit
Callers must be able to hear no.
Choose when
Every place where strangers decide how much comes in.

Limit it when

  • It costs money, memory or a licence
  • The other side breaks under too many
  • Making it is slow and using it is short
  • One customer can starve the others

Leave it when

  • Objects are cheap: the garbage collector is a fine pool
  • The library below already has a limit
  • There is one user
  • You cannot say what happens at the limit

Relatives

ToolHoldsWho may release?Typical error
LockOne ownerThe ownerHeld while waiting for something slow
PermitsA countAnybodyReleased twice: the limit grows silently
PoolObjectsThe lease, onceDirty or broken object comes back
BudgetA sumWhoever has an amountLarge request starves
QueueWorkThe worker that takes itNo limit

Summary

The whole topic in one minute.

Lend leases. Count what exists or is about to exist, make and close outside the lock, give back on every way out, once. Closing refuses new borrowers, wakes the sleeping ones and waits for the rest.

With different sizes the line needs a rule: blocked by your own quota you step aside, blocked by the common budget you hold the line. The granter takes the amount for the waiter, so nobody steals it.

Size from rate times time held. A line absorbs bursts, not overload: limit it to what callers will still want, refuse the rest at once with a hint, and count every refusal. Shorten the time held before you enlarge anything.

  • Four questions: who gets it, who waits, how long, how does it come back?
  • Lend a lease, not the thing. It gives back on every way out, once.
  • Look and take in one step. Make and close slow things outside the lock, with the place already counted.
  • L = lambda x W tells the size. Above capacity a line only delays the failure.
  • Quotas protect customers from each other. A line without overtaking protects large requests.
  • Refuse early, with a reason and a time to come back.

Sources