Sub topic 15
Combining the techniques and weighing trade-offs
This chapter assumes you have read the earlier chapters on bounded queues, back pressure, load shedding, admission control, concurrency limits, client signals, and retries. It shows how those pieces fit into one request path and how to choose among them.
Each technique protects a different place
No single technique covers every overload case. Each one acts at a different point, so they work best layered.
| Technique | Where it acts | What it protects | Main cost |
|---|---|---|---|
| Token bucket | Edge, before work starts | Steady rate and burst size | Needs a good rate estimate |
| Concurrency limit | Before the handler | Work in flight | Rejects even when capacity is free but limit is low |
| Bounded queue | Between stages | Memory and wait time | Adds some delay |
| Back pressure | Between internal producer and consumer | No work is lost | Slow producers wait |
| Deadline check | Before each expensive step | Wasted work | Needs deadlines passed along |
| Retry budget | In the client | The server during recovery | Some failures are not retried |
A layered request path
A request passes through cheap checks first and expensive work last. Rejecting early costs little, so overload is turned away before it consumes resources.
Putting it together in code
This sketch combines a token bucket, an in-flight limit, and a bounded queue. It reuses the TokenBucket class from the admission control chapter. The in-flight check has no await between the check and the increment, so it is safe in one asyncio event loop.
import asyncio
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float) -> None:
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.updated = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
MAX_IN_FLIGHT = 50
bucket = TokenBucket(rate=100, capacity=20)
queue: asyncio.Queue = asyncio.Queue(maxsize=100)
in_flight = 0
async def handle(request, process, deadline: float):
global in_flight
if not bucket.allow():
return 429, {"Retry-After": "1"}
if in_flight >= MAX_IN_FLIGHT:
return 503, {"Retry-After": "1"}
try:
queue.put_nowait(request)
except asyncio.QueueFull:
return 503, {"Retry-After": "1"}
in_flight += 1
try:
item = await queue.get()
if time.monotonic() > deadline:
return 503, {} # nobody is waiting any more
return 200, await process(item)
finally:
in_flight -= 1Weighing the trade-offs
Pick the mechanism by asking who can slow down.
- Producer is under your control (an internal pipeline): use back pressure. Nothing is lost, and the producer simply waits.
- Producer is not under your control (public traffic): shed load. You cannot make users wait politely, so reject and signal.
- Work is cheap to retry: shed early and tell clients when to return.
- Work is expensive or has side effects: admit less and protect work already accepted.
Common errors when combining techniques:
- Limits set too high. If the queue or in-flight limit is larger than what you can finish within the deadline, it never triggers and latency grows anyway.
- Limits set too low. The service rejects traffic it could have served.
- Back pressure across a shared dependency. One slow consumer can stall unrelated producers. Give each path its own bounded queue.
- Shedding with aggressive client retries. The rejected load comes back immediately. Pair every shed response with backoff, jitter, and a retry budget.
- Tuning without measurement. Choose limits from observed latency and saturation metrics, then check them under load.
Exercise
A public API sits in front of an internal worker pool fed by a bounded queue. Where would you use back pressure, and where would you shed load?
Show answer
Shed load at the public edge with a token bucket or concurrency limit, because you cannot slow external clients and should return 429 or 503 with Retry-After. Use back pressure inside the service, between the API handler stage and the worker pool, where a full bounded queue makes the internal producer wait. If the internal wait grows too long, the handler's deadline check or a full queue should turn it into a shed response so waiting does not pile up at the edge.