Sub topic 11
Trading latency against throughput: batching, concurrency limits and backpressure
This chapter assumes you know the basics of client-server request/response, common backend components (load balancers, services, databases), and can read short Python programs. It also assumes you have seen Little's law and the idea that latency rises as utilization approaches saturation, which earlier chapters covered.
Why the two goals pull apart
Latency is how long one request takes. Throughput is how many requests the system completes per unit of time. Many techniques raise throughput by making each request wait a little, so that work can be grouped, queued or smoothed. Those same techniques add to latency.
You rarely get both for free. A target set such as "p99 under 200 ms at 5,000 requests per second" is a statement about where you sit on this trade-off. This chapter covers three levers that move you along it:
- Batching: grouping several items so a fixed cost is paid once.
- Concurrency limits: capping how many requests are processed at once.
- Backpressure: telling producers to slow down when the system cannot keep up.
Batching: paying fixed costs once
Many operations have a fixed cost per call plus a small cost per item. A database insert has a network round trip, a commit and a log flush, and each row adds only a little on top. If you send rows one at a time, you pay the fixed cost for every row. If you send 100 rows together, you pay it once.
A simple cost model:
batch_time = fixed_ms + per_item_ms * batch_sizethroughput = batch_size / batch_time- Latency for an item includes the time it waits for the batch to fill, plus
batch_time.
fixed_ms = 5.0 # round trip, commit, flush
per_item_ms = 0.1 # marginal cost of one row
print("size batch_ms items_per_s")
for size in (1, 10, 100, 1000):
batch_ms = fixed_ms + per_item_ms * size
items_per_s = size / (batch_ms / 1000)
print(f"{size:>4} {batch_ms:>8.1f} {items_per_s:>11.0f}")Running this prints:
size batch_ms items_per_s
1 5.1 196
10 6.0 1667
100 15.0 6667
1000 105.0 9524Throughput climbs steeply from batch size 1 to 100, then flattens. The ceiling is 1 / per_item_ms, which is 10,000 items per second here. Going from 100 to 1000 items buys only about 43% more throughput, but the batch itself takes seven times as long.
The waiting cost
The model above ignores how long items wait for the batch to fill. With an arrival rate of 500 items per second, a batch of 100 takes 200 ms to fill. The first item in the batch waits the longest, so its latency is roughly 200 ms plus 15 ms of processing.
Production batchers therefore use two triggers, whichever fires first:
- Size limit: flush when the batch reaches N items.
- Time limit: flush when the oldest item has waited T milliseconds.
The time limit bounds the added latency. The size limit bounds memory and the time any single call takes.
import queue
import time
def collect_batch(q, max_size, max_wait_s):
"""Return up to max_size items, waiting at most max_wait_s
after the first item arrives."""
batch = [q.get()] # block until there is at least one item
deadline = time.monotonic() + max_wait_s
while len(batch) < max_size:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
batch.append(q.get(timeout=remaining))
except queue.Empty:
break
return batch
q = queue.Queue()
for i in range(5):
q.put(i)
print(collect_batch(q, max_size=3, max_wait_s=0.05)) # [0, 1, 2]
print(collect_batch(q, max_size=3, max_wait_s=0.05)) # [3, 4]The second call returns only two items because the queue empties and the 50 ms limit expires. At low load, the time limit dominates and batches are small. At high load, the size limit dominates and batches are full. This is a useful property: batching adds latency mostly when the system is busy enough to benefit from it.
Where batching shows up
| Place | What is batched | Latency cost |
|---|---|---|
| Database writes | Rows per transaction | Wait for commit of the whole group |
| Message producers | Records per network send | Linger time before send |
| Log shippers | Lines per upload | Delay before logs are visible |
| GPU inference | Inputs per forward pass | Wait for the batch to fill |
| Disk writes | Group commit of log entries | Wait for the shared flush |
Concurrency limits: protecting the system from itself
Concurrency is the number of requests in progress at once. Little's law ties it to the other two quantities: in_flight = arrival_rate * time_in_system.
A service has finite resources: CPU cores, database connections, memory. Past some level of concurrency, more simultaneous requests do not finish more work per second. They only make each request slower, and they can push throughput down because of contention, context switching and memory pressure.
A concurrency limit caps the number of requests in progress. Extra requests either wait in a queue or are rejected.
Choosing a limit with Little's law
Suppose a service must handle 2,000 requests per second at 50 ms average latency. Little's law says about 100 requests are in flight. A limit of exactly 100 leaves no room for variation. Bursts and slower requests will hit it constantly.
A common starting point is the expected in-flight count times a headroom factor, then check it against what the downstream resource can take:
import math
arrival_rate_per_s = 2000
avg_latency_ms = 50
headroom = 1.5
expected = arrival_rate_per_s * avg_latency_ms / 1000
limit = math.ceil(expected * headroom)
print(expected, limit) # 100.0 150
# Check against a downstream database with 120 connections
# shared by 3 service instances.
db_connections = 120
instances = 3
per_instance_db = db_connections // instances
print(per_instance_db) # 40The database allows 40 connections per instance, and the service needs about 33 in flight per instance (100 divided by 3). So the real constraint is the connection pool, not the arithmetic limit of 150 in total. The effective limit is whichever resource saturates first.
Queue or reject?
When the limit is reached, you have two choices.
- Queue the request. Throughput stays high and short bursts are absorbed. Latency rises by the queue wait. An unbounded queue hides overload until wait times exceed what clients will tolerate.
- Reject the request. The client gets an error quickly, typically HTTP 429 or 503. Latency for accepted requests stays low, and the failed request costs almost nothing.
A bounded queue combines both: a short queue absorbs bursts, and everything beyond it is rejected. Size the queue from your latency budget. If a request can spend at most 20 ms waiting and each slot serves a request in 50 ms, a queue deeper than a fraction of the worker count is already too long.
import threading
class Limiter:
def __init__(self, max_concurrent):
self._sem = threading.BoundedSemaphore(max_concurrent)
def try_acquire(self):
return self._sem.acquire(blocking=False)
def release(self):
self._sem.release()
limiter = Limiter(2)
print(limiter.try_acquire()) # True
print(limiter.try_acquire()) # True
print(limiter.try_acquire()) # False: reject, do not wait
limiter.release()
print(limiter.try_acquire()) # TrueStatic and adaptive limits
A fixed limit is simple but goes stale when the workload or the downstream service changes. Adaptive limiters measure latency and adjust. When latency rises above a baseline, they lower the limit. When it recovers, they raise it slowly. This resembles TCP congestion control. Adaptive limits cost more to build and need tuning, and a poorly tuned one can oscillate. Start with a static limit based on load tests, and move to adaptive only if the right value keeps changing.
Backpressure: pushing the limit upstream
A concurrency limit protects one component. Backpressure carries that signal back to whoever is sending the work, so that the whole path slows down together instead of piling work up in the middle.
Without backpressure, a fast producer feeding a slow consumer fills every buffer between them. Memory grows, latency grows, and eventually something crashes or drops data silently.
Common forms:
- Blocking: a full bounded queue makes the producer's
putcall wait. This works inside a process. - Explicit rejection: the service returns 429 or 503, often with a
Retry-Afterheader. Clients back off. - Credit or window protocols: the consumer tells the producer how many items it can accept. TCP windows and reactive streams work this way.
- Load shedding: the service drops low-priority work first when it is overloaded.
import queue
import threading
import time
q = queue.Queue(maxsize=5) # bounded: this is the backpressure
def producer():
for i in range(12):
q.put(i) # blocks while the queue is full
print(f"produced {i}, depth {q.qsize()}")
q.put(None)
def consumer():
while True:
item = q.get()
if item is None:
return
time.sleep(0.05) # slow consumer
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join(); t2.join()The queue depth never exceeds 5. The producer is paced to the speed of the consumer, which is what backpressure means.
How the pieces fit together
Read the diagram from left to right. The limit and queue protect the workers. The batcher raises database throughput at the cost of a short wait. The rejection path is the backpressure signal that reaches the clients.
Choosing where to sit on the trade-off
Decide by what the product needs, then express it as targets.
| Workload | Priority | Typical choices |
|---|---|---|
| Interactive API (user waits) | Low tail latency | Small or no batches, small bounded queue, reject early |
| Background ingestion | High throughput | Large batches, deep queue, long time limit |
| Analytics export | Throughput and cost | Very large batches, no latency target beyond a deadline |
| Mixed service | Both | Separate pools or queues per class so batch traffic cannot starve interactive traffic |
The last row is a common source of incidents. If bulk jobs and interactive requests share one worker pool, a burst of bulk work fills the slots and interactive p99 collapses. Give each class its own limit.
Common errors
- Setting the limit from average latency only. Slow requests hold slots much longer. Check the limit at p99 latency too.
- Batch time limit longer than the latency budget. If the budget for a stage is 30 ms, a 100 ms linger time breaks it however fast the processing is.
- Limits that exceed what downstream can take. A service limit of 500 with a database pool of 40 just moves the queue into the pool.
- No limit on retries and timeouts. Timeouts shorter than real latency cause retries, which raise load and latency further.
- Measuring throughput without latency. A throughput gain that doubles p99 may violate the SLO even though the dashboard looks better.
Writing the targets down
For a service with both interactive and bulk traffic, targets might read:
- Interactive: p99 under 200 ms at up to 1,500 requests per second, concurrency limit 120 per instance, queue depth 20, excess rejected with 429.
- Bulk: at least 8,000 items per second sustained, batch size 500, linger time 250 ms, no latency SLO beyond completion within 5 minutes.
Each number can be tested in a load test, which the next chapter covers.
Exercise
A service handles 800 requests per second with an average latency of 60 ms. Its database pool allows 40 connections in total, and each request holds one connection for 40 ms. (a) How many requests are in flight on average? (b) How many database connections are busy on average? (c) Is the pool of 40 enough, and what should you do about the margin?
Show answer
(a) In flight = 800 0.060 = 48 requests. (b) Busy connections = 800 0.040 = 32 on average. (c) 32 of 40 is 80% utilization on average, so bursts and slow queries will often exhaust the pool and requests will queue, which adds latency. Either raise the pool if the database allows it, reduce the time each request holds a connection, or set a bounded queue and reject beyond it. Also set the service concurrency limit with the pool in mind rather than from the 48 in-flight figure alone.
Exercise
A batcher flushes at 200 items or 100 ms after the first item, whichever comes first. Items arrive at 500 per second. What triggers the flush, and what is the worst-case added wait for an item? What changes if arrivals rise to 5,000 per second?
Show answer
At 500 per second, 200 items would take 400 ms to arrive, so the 100 ms time limit fires first with about 50 items. The first item waits up to 100 ms. At 5,000 per second, 200 items arrive in 40 ms, so the size limit fires first and the worst-case wait drops to about 40 ms, with full batches and higher efficiency.