Sub topic 8
Choosing what to shed: priority, age, and fairness
Earlier chapters showed how to reject work on purpose and how deadlines stop a service from doing work nobody is waiting for. This chapter covers which requests to reject once you have decided that some must go. It assumes you can read short Python examples, know HTTP status codes, and understand the bounded queues and in-flight limits from earlier chapters.
Shedding is a choice, not just a threshold
A bare "queue is full, reject the newest request" rule is simple, but it ignores three differences between requests:
- Importance. A payment confirmation matters more than a prefetch for a thumbnail.
- Freshness. A request that has waited 8 seconds may have been abandoned by its caller. Finishing it earns nothing.
- Source. One noisy client can fill the queue and starve everyone else.
Each difference gives you a policy: priority, age, and fairness. They address different failure modes, and real systems usually combine them.
| Policy | Question it answers | Typical signal | Main risk |
|---|---|---|---|
| Priority | Which work is worth keeping? | Request class, route, or caller tier | Starvation of low classes, priority inflation |
| Age | Is anyone still waiting for this? | Time in queue, remaining deadline | Wasted work if the age limit is too loose |
| Fairness | Is one source taking everything? | Per-client in-flight or rate | Unfair to legitimate heavy users if caps are too tight |
Shedding by priority
Priority shedding assigns each request a class and rejects lower classes first. The simplest form uses a different queue-depth threshold for each class. Background work is rejected when the queue is half full, normal work at 80%, and critical work only when the queue is completely full.
import asyncio
from enum import IntEnum
class Priority(IntEnum):
CRITICAL = 0
NORMAL = 1
BACKGROUND = 2
# Fraction of queue capacity at which each class starts being rejected.
SHED_AT = {
Priority.BACKGROUND: 0.5,
Priority.NORMAL: 0.8,
Priority.CRITICAL: 1.0,
}
class Overloaded(Exception):
pass
def submit(queue: asyncio.Queue, request, priority: Priority) -> None:
limit = SHED_AT[priority] * queue.maxsize
if queue.qsize() >= limit:
raise Overloaded(f"shedding {priority.name}")
queue.put_nowait(request)This reserves headroom for important work. Even when background traffic floods the service, the top half of the queue stays free for critical requests.
Priority gotchas
- Starvation. If critical traffic alone can saturate the service, low classes get nothing. That is often acceptable, but decide it deliberately and alert on it.
- Priority inflation. If clients choose their own priority, every client will pick the highest one. Derive priority on the server from the route, the authenticated identity, or the customer tier, not from a header the caller controls.
- Hidden dependencies. A "low priority" call may be a dependency of a "critical" one. Shedding it fails the critical request anyway. Classify by the end-to-end user action, not by the individual endpoint.
- Too many classes. Two to four classes are easy to reason about and test. Ten are not.
Shedding by age
A request's value falls as it waits. If the caller's timeout is 5 seconds and the request has sat in the queue for 6, any work you do on it is wasted. Worse, doing that work delays the fresh requests behind it. This is how an overloaded service gets stuck, with every response arriving too late to count.
The fix is to check age when you dequeue, because that is when you know how long the request really waited.
import asyncio
import time
from dataclasses import dataclass
from typing import Any, Callable
@dataclass
class Job:
payload: Any
enqueued_at: float # time.monotonic() when queued
deadline: float # absolute time.monotonic() deadline
MAX_QUEUE_AGE = 2.0 # seconds a job may wait before it is considered stale
async def worker(queue: asyncio.Queue, process, on_shed: Callable[[Job], None]) -> None:
while True:
job = await queue.get()
now = time.monotonic()
if now - job.enqueued_at > MAX_QUEUE_AGE or now >= job.deadline:
on_shed(job) # cheap rejection: no real work done
continue
await process(job.payload)
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue(maxsize=10)
now = time.monotonic()
queue.put_nowait(Job("stale", now - 5.0, now + 1.0))
queue.put_nowait(Job("fresh", now, now + 5.0))
async def process(payload):
print("processed", payload)
task = asyncio.create_task(
worker(queue, process, lambda job: print("shed", job.payload))
)
await asyncio.sleep(0.1)
task.cancel()
asyncio.run(main())Running this prints shed stale and then processed fresh.
Two refinements are common:
- Use the remaining deadline, not a fixed age. If the caller propagates its deadline, shed any job whose remaining time is shorter than the typical processing time. It cannot finish anyway.
- Serve newest first under pressure. A FIFO queue serves the oldest requests first, which are the most likely to have been abandoned. Switching to LIFO when the queue is deep (adaptive LIFO) gives the freshest requests good latency and lets the stale tail time out. The cost is that some requests wait a very long time, so only do this when late answers are worthless.
Shedding by fairness
Priority and age ignore who sent the request. If one client sends 90% of the traffic, a shared queue fills with its requests and everyone else sees rejections. Fairness policies limit each source's share when resources are scarce.
A practical approach is to allow any client to burst freely while the service is lightly loaded, and to enforce a fair share once load passes a threshold. This avoids rejecting work when there is spare capacity.
class FairLimiter:
"""Cap total in-flight work and give each active client a fair share under load.
Safe in a single asyncio event loop because there is no await
between the checks and the updates.
"""
def __init__(self, total: int) -> None:
self.total = total
self.count = 0
self.in_flight: dict[str, int] = {}
def try_acquire(self, client: str) -> bool:
if self.count >= self.total:
return False
current = self.in_flight.get(client, 0)
active = len(self.in_flight) + (1 if current == 0 else 0)
fair_share = max(1, self.total // active)
# Below half load, anyone may use spare capacity.
if self.count >= self.total // 2 and current >= fair_share:
return False
self.in_flight[client] = current + 1
self.count += 1
return True
def release(self, client: str) -> None:
self.in_flight[client] -= 1
self.count -= 1
if self.in_flight[client] == 0:
del self.in_flight[client]With total=100 and four active clients, each can hold up to 25 slots once the limiter is half full. A fifth client arriving later still gets at least one slot, as long as the total has not been reached.
Fairness gotchas
- Identity. Fairness is only as good as the key. Keying on IP address punishes users behind a shared proxy. Keying on an unauthenticated header lets abusers mint new identities.
- Weights. Not all clients are equal. A paying enterprise tenant may deserve a larger share. Use weighted shares if tiers exist.
- Cost. Counting requests treats a cheap read and an expensive report the same. If costs vary widely, count a cost estimate instead, as the token bucket's
costparameter allows.
Putting the checks in order
Run the cheapest checks first, and as early in the request path as possible. A rejection that costs microseconds protects capacity better than one that happens after you parsed the body and opened a database connection.
Fairness rejections usually map to 429 because the client is the cause. Priority and capacity rejections usually map to 503 because the service is the cause. The next chapter covers these signals.
Common mistakes
- Shedding only at the queue. If a request is already deep in your system, rejecting it wastes all the work done so far. Shed at the edge.
- Not measuring what you shed. Count rejections per class, per reason, and per client. Without that, you cannot tell whether the policy protects critical traffic or just rejects at random.
- Static thresholds copied from another service. Thresholds depend on queue size, service time, and traffic mix. Tune them with a load test.
- Retries that undo the policy. Low-priority clients that retry aggressively after a rejection become extra load. Pair shedding with backoff and a retry budget.
Exercise
A service has a queue of 100 slots and uses the thresholds BACKGROUND 0.5, NORMAL 0.8, CRITICAL 1.0. The queue currently holds 60 items. Which of a BACKGROUND, a NORMAL, and a CRITICAL request does submit accept? Then explain why a worker that checks job age at dequeue still matters even though submit already rejects at the door.
Show answer
BACKGROUND is rejected because 60 is at or above 50. NORMAL is accepted because 60 is below 80. CRITICAL is accepted because 60 is below 100. The dequeue age check still matters because a job accepted at the door can wait a long time if the queue drains slowly. By the time a worker reaches it, the caller may have given up. Admission looks at queue depth, which is a proxy for delay. Only the dequeue check sees the actual wait, so it prevents wasted work on stale jobs.
Exercise
With FairLimiter(total=100), client A already holds 60 slots, and client B has none. Client B sends a request. Does it get a slot? Does client A get a 61st slot?
Show answer
Client B gets a slot. The total (60) is below 100, and with B counted as active there are two active clients, so the fair share is 50. B has 0 in flight, which is below its share. Client A does not get a 61st slot. The limiter is above half load (60 is at least 50), and A's 60 in-flight requests are at or above the fair share of 50 (100 divided by 2 active clients).