Sub topic 11
Trading latency against throughput: batching, concurrency limits and backpressure
This chapter assumes you know the basics of client-server request handling, can read simple Python, and have seen Little's law (in-flight requests = arrival rate × time in system) and the idea that latency rises as utilization nears 100%.
Why the two goals pull apart
Latency is how long one request takes. Throughput is how many requests finish per second. Many techniques that raise throughput do it by making individual requests wait: they group work, share resources, or keep workers busy. So a target for one often costs you some of the other. Your job is to pick the point on the curve that meets both targets, not to maximize either.
Batching
Batching groups several items into one operation, such as one database insert for 100 rows or one network call for 50 messages. It raises throughput because the fixed cost of each operation (a round trip, a commit, a disk sync) is paid once for the whole group.
Batching adds latency, because the first item in a batch waits for the batch to fill. Bound that wait with two limits: a maximum batch size and a maximum wait time. The batch is sent when either limit is reached.
import time
def collect_batch(queue, max_size=100, max_wait_s=0.010):
"""Take items from a list-like queue until the batch is full or time runs out."""
batch = []
deadline = time.monotonic() + max_wait_s
while len(batch) < max_size and time.monotonic() < deadline:
if queue:
batch.append(queue.pop(0))
else:
time.sleep(0.001)
return batch
queue = list(range(250))
print(len(collect_batch(queue))) # 100With max_wait_s of 10 ms, batching adds at most about 10 ms to a request. Count that cost against the latency budget for that component.
Concurrency limits
A concurrency limit caps how many requests a component works on at once. Without one, a traffic spike makes every request run at the same time, and they all slow down together. With one, some requests wait or are rejected, but the admitted ones finish quickly.
Little's law tells you where to set the limit. If the service must handle 2000 requests per second at 50 ms average latency, about 100 requests are in flight. A limit of 150 to 200 gives headroom for normal variation. A limit of 100 would turn every small burst into queueing.
A limit that is too high protects nothing. A limit that is too low rejects work the system could have handled. Start from the Little's law estimate, then adjust it with load test results.
Backpressure
Backpressure is a signal from an overloaded component telling its callers to slow down or stop. Without it, a queue in front of a slow component grows without bound. Each queued request waits longer, so latency rises for everyone, and memory use grows until the process fails.
Common forms of backpressure:
- A bounded queue that rejects new items when full.
- An HTTP 429 or 503 response, often with a
Retry-Afterheader. - Blocking the producer until the consumer has capacity.
- Load shedding, which drops low-priority requests first.
from collections import deque
class BoundedQueue:
def __init__(self, capacity):
self.items = deque()
self.capacity = capacity
def offer(self, item):
if len(self.items) >= self.capacity:
return False # caller should back off or return 503
self.items.append(item)
return True
q = BoundedQueue(capacity=2)
print([q.offer(i) for i in range(4)]) # [True, True, False, False]A fast rejection is usually better than a slow success. A request that is rejected in 1 ms lets the client retry elsewhere, but one that times out after 30 s has wasted resources on both sides.
Choosing a point on the trade-off
| Technique | Raises throughput by | Costs latency by | Main risk |
|---|---|---|---|
| Batching | Sharing fixed cost per operation | Waiting for the batch to fill | Wait time eats the latency budget |
| Larger concurrency limit | Keeping more workers busy | Queueing and contention at high load | Overload spreads to dependencies |
| Smaller concurrency limit | Nothing directly | Lower, because less queueing | Rejects work the system could serve |
| Deep queue | Absorbing bursts | Long waits in line | Hidden latency and memory growth |
Use the targets to decide. For an interactive request with a p99 of 300 ms, keep batch waits to a few milliseconds and queues short. For a background job that must process 1 million records per hour, use large batches and a deep queue, because no user waits on each record.
Common errors
- Setting a batch size without a maximum wait, so low traffic leaves items waiting for a batch that never fills.
- Using an unbounded queue and calling it "absorbing bursts". The queue turns overload into latency instead of removing it.
- Choosing a concurrency limit by guesswork rather than from arrival rate and latency.
- Measuring only throughput during a load test, and missing that p99 latency has already broken the target.
Exercise
A service receives 500 requests per second and each request takes 40 ms on average. Using Little's law, how many requests are in flight on average? Suggest a reasonable concurrency limit, and say what happens to a request that arrives when the limit and the queue are both full.
Show answer
In flight = 500 × 0.040 = 20 requests. A limit of about 30 to 40 leaves headroom for bursts without allowing unbounded overload. A request that arrives when the limit and the queue are full should be rejected quickly (for example with HTTP 503 or 429) so the caller can back off, instead of waiting and raising latency for everyone.
Exercise
A batcher flushes at 200 items or after 50 ms. The end-to-end p99 target is 100 ms, and the batcher's share of that budget is 20 ms. Is the configuration acceptable? What would you change?
Show answer
No. The 50 ms maximum wait alone exceeds the 20 ms allocation, before counting the time to process the batch. Reduce the maximum wait to well under 20 ms, for example 10 ms, and check with a load test that throughput is still sufficient at that batch size.