Scarcity: limited resources
hard 50 minWhen 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
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
1961
John Little proves L = lambda x W, the law that connects arrivals, time and the number in the system.
1965
Edsger Dijkstra's Cooperating Sequential Processes (EWD123) describes the general semaphore and a bounded buffer.
2004
Java 5 brings Semaphore, with a choice between fair and unfair, and bounded blocking queues.
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.
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.
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?
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?
Why
What goes wrong without it
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 resultThe design that hurts
1/2A public list
Everybody can take, and everybody must remember to bring back.
useshas (lives on)
Six things that are missing
| Without | You see | Tool |
|---|---|---|
| A limit | Memory, sockets or licences run out | Pool or permits |
| A lease | The pool gets smaller every day | Give back on every way out |
| A deadline | Threads pile up behind one slow scanner | Timeout in borrow |
| A line limit | Everybody waits minutes and nobody is served in time | Refuse early |
| A quota | One customer makes all others wait | Limit per customer |
| Order | Big requests never get through | A line that cannot be overtaken |
Numbers
How many are enough?
Little's law
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.
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))0.9 pages per second, 0.6 possible
| After | Waiting, no limit | Wait of the last one | Waiting, limit 6 | Wait of the last one |
|---|---|---|---|---|
| 1 minute | 18 | 30 s | 6 | 10 s |
| 10 minutes | 180 | 300 s | 6 | 10 s |
| 60 minutes | 1,080 | 1,800 s | 6 | 10 s |
The idea
Borrow, use, give back
The design that works
1/3The borrower sees two verbs
Borrow, and whatever the language does at the end of a block.
usesowns (dies together)depends on
A waiting borrower
Life of a pooled object
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
| Tool | Holds | Who may release? | Typical error |
|---|---|---|---|
| Lock | One owner | The owner | Held while waiting for something slow |
| Permits | A count | Anybody | Released twice: the limit grows silently |
| Pool | Objects | The lease, once | Dirty or broken object comes back |
| Budget | A sum | Whoever has an amount | Large request starves |
| Queue | Work | The worker that takes it | No 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
- HikariCP: configuration
- HikariCP: about pool sizing
- Java: Semaphore
- Go: package database/sql
- PgBouncer: configuration
- PostgreSQL: connection settings
- Kubernetes: resource quotas
- nginx: limit_conn
- Resilience4j: bulkhead
- Envoy: circuit breaking
- RFC 9293: TCP, managing the window
- Google SRE book: handling overload
- Edsger Dijkstra: Cooperating Sequential Processes (EWD123)