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, deadlines, client signals, and retries. You should know Little's law (L = λW) and be able to read short Python async code. Each technique works alone. A real service usually needs several of them at once, and they interact.
Why one technique is not enough
Each technique covers a different gap.
| Technique | What it protects | What it cannot do alone |
|---|---|---|
| Back pressure | Memory and downstream stages, when the producer can be slowed | Does nothing for callers you do not control, such as the public internet |
| Bounded queue | Memory, and the worst-case wait | A full queue of stale work still wastes capacity |
| Rate limiting (token bucket) | Fairness and a steady admission rate | Says nothing about how slow requests are right now |
| Concurrency limit | CPU, connections, and downstream load | Does not stop callers from piling up in front of it |
| Deadlines | Wasted work on abandoned requests | Does not reduce arrival rate |
| Client signals and retry budgets | Prevents retry amplification | Depends on clients cooperating |
The usual pattern is layered. Reject early and cheaply at the edge. Bound every queue inside. Drop work that has expired. Tell clients how to behave.
Order the checks from cheap to expensive
A request that will be rejected should cost almost nothing. Put the cheapest, most general checks first.
- Rate limit (a few arithmetic operations, no I/O).
- Concurrency or queue-space check (one comparison).
- Deadline check (one clock read).
- Real work.
A request rejected at step 1 never takes a queue slot, so it cannot displace a request that was already admitted.
A combined example
This service combines a token bucket, a bounded queue, a fixed worker pool as the concurrency limit, and a deadline check at dequeue time.
import asyncio
import time
class Overloaded(Exception):
def __init__(self, reason: str, retry_after: float) -> None:
super().__init__(reason)
self.reason = reason
self.retry_after = retry_after
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
class Service:
def __init__(self, workers: int = 4, queue_size: int = 20,
rate: float = 100.0, burst: float = 60.0) -> None:
self.workers = workers
self.bucket = TokenBucket(rate, burst)
self.queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
def submit(self, payload: str, deadline: float) -> asyncio.Future:
if not self.bucket.allow():
raise Overloaded("rate limit", retry_after=1.0)
future = asyncio.get_running_loop().create_future()
try:
self.queue.put_nowait((payload, deadline, future))
except asyncio.QueueFull:
raise Overloaded("queue full", retry_after=1.0) from None
return future
async def worker(self) -> None:
while True:
payload, deadline, future = await self.queue.get()
try:
if future.cancelled():
continue
if time.monotonic() >= deadline:
future.set_exception(Overloaded("deadline expired", 0.0))
continue
await asyncio.sleep(0.05) # simulate work
future.set_result(payload.upper())
finally:
self.queue.task_done()
async def main() -> None:
service = Service()
tasks = [asyncio.create_task(service.worker()) for _ in range(service.workers)]
results = {"ok": 0, "shed": 0, "expired": 0}
async def client(i: int) -> None:
try:
future = service.submit(f"req{i}", time.monotonic() + 0.15)
await future
results["ok"] += 1
except Overloaded as exc:
key = "expired" if exc.reason == "deadline expired" else "shed"
results[key] += 1
await asyncio.gather(*(client(i) for i in range(200)))
for task in tasks:
task.cancel()
print(results)
asyncio.run(main())Send 200 requests at once and the three counts add up to 200. The exact split depends on timing. Most requests are shed by the token bucket or the full queue. Some admitted requests may expire while waiting. The point is that every request gets a fast, explicit answer, and no worker spends time on a request whose deadline has passed.
Size the layers against each other
The numbers must agree, or one layer makes another useless. Use Little's law and the service rate.
In the example, 4 workers with 0.05 s of work each give a capacity of 4 / 0.05 = 80 requests per second. A queue of 20 therefore adds at most 20 / 80 = 0.25 s of waiting. Check that against the deadline:
- If the deadline is shorter than the worst-case queue wait, requests at the back of a full queue are doomed. They take a slot, wait, then expire. Shrink the queue or lengthen the deadline.
- If the token bucket rate is above 80 per second for long, the queue fills and the queue limit does the shedding. That is acceptable only if you want shedding to happen there, with the bucket acting as a burst filter.
- If the rate is well below capacity, the bucket sheds work the service could have done. This is intended for per-client fairness and wasteful otherwise.
A useful rule is that the worst-case queue wait should be a fraction of the client deadline, leaving room for the work itself and for network time.
Back pressure or shedding at each boundary
Choose per boundary, not once for the whole system.
- Internal pipeline stages you control: use back pressure. A blocking
put()slows the producer and loses nothing. - Edges facing callers you do not control: shed. You cannot make an unknown client wait politely, and blocking holds connections and memory.
- Work that cannot be redone, such as a payment event: prefer back pressure or a durable queue, and shed only after saving the work somewhere.
- Work that is cheap to redo or stale quickly, such as a dashboard refresh: shed freely, and prefer dropping the oldest items.
Back pressure propagates. If a stage blocks, the stage before it fills, and so on, until it reaches a boundary where something sheds. Make sure such a boundary exists. Otherwise the pressure travels back to a user-facing thread pool and stalls the whole service.
Trade-offs to weigh
| Choice | Benefit | Cost |
|---|---|---|
| Small queue | Low worst-case latency | Sheds during short bursts that the service could have absorbed |
| Large queue | Absorbs bursts | Higher latency, more stale work |
| Strict concurrency limit | Predictable resource use | Wastes capacity if the limit is set below real capacity |
| Static limits | Simple, easy to reason about | Go wrong when the workload or the dependency changes |
| Adaptive limits | Follow real capacity | Harder to debug, can oscillate |
| Shed oldest first | Serves the requests whose clients are still waiting | Starves old requests, and may break ordering |
| Shed newest first | Preserves ordering and is simple | Admitted work may already be stale |
| Per-client limits | Fair, isolates one noisy client | More state, and needs a trustworthy client identity |
There is no universally correct row. Pick the one that matches what a late or missing answer costs the user.
Failure modes when combining techniques
- Retry amplification through shedding. If clients retry every 503 immediately, shedding creates more traffic. Return
Retry-After, and make clients use backoff with jitter and a retry budget, for example no more than 10% extra requests. - Limits that disagree across tiers. If the load balancer allows 1,000 concurrent requests and the service allows 50, the service sheds and the balancer sees many errors. Know which tier is meant to reject.
- Shedding that hides a real fault. A service that sheds 30% of traffic because a dependency is slow looks "healthy" with fast 503s. Alert on shed rate and on dependency latency, not only on success latency.
- Priority inversion. If high-priority work waits in the same queue as low-priority work, shedding by queue position does not protect it. Use separate queues, or shed by priority.
- Thread safety. The token bucket and in-flight counter above rely on a single event loop. With threads, add a lock or use an atomic primitive.
- Slow shedding. If rejecting a request needs a database lookup or a log write, the rejection path becomes the bottleneck. Keep it cheap.
A decision checklist
- For every queue, state its bound and the maximum wait the bound implies.
- For every boundary, decide whether it blocks or sheds, and where the pressure ends.
- Make deadlines travel with the request, and check them before starting work.
- Return a distinguishable status: 429 for a client exceeding its share, 503 for the service being overloaded, both with
Retry-After. - Check that the worst case,
Retry-Afterplus backoff, does not bring clients back all at once. - Emit metrics for queue depth, queue age, shed count by reason, and in-flight count, so you can see which layer is acting.
Exercise
A service has 8 workers, each request takes 0.1 s, and the queue holds 40 requests. Clients time out after 0.5 s. What is the capacity, the worst-case queue wait, and what is wrong with this configuration?
Show answer
Capacity is 8 / 0.1 = 80 requests per second. A full queue of 40 takes 40 / 80 = 0.5 s to drain, so the worst-case wait equals the whole client timeout, before any work time is added. A request at the back of a full queue will time out while the service still processes it, wasting capacity. Reduce the queue to about 10 to 15 (0.125 to 0.19 s of wait), or add a deadline check at dequeue time so that expired requests are dropped without work. Doing both is better.