Sub topic 6
Splitting a latency budget across the request path
This chapter assumes you can read simple Python, know the usual backend components (load balancer, gateway, service, database), and have seen latency percentiles such as p50 and p99. You should also know what an end-to-end target looks like, for example "99% of requests finish within 300 ms."
What a latency budget is
An end-to-end latency target says how long a user may wait. A request rarely runs in one place. It crosses the network, a gateway, one or more services and a database. Each step takes time, and the steps run one after another, so the delays add up.
A latency budget is a plan that divides the end-to-end target into a share for each component. Each team can then design, test and monitor its own piece against a number. Without a budget, every team assumes the others are fast, and the total misses the target with no obvious owner.
A budget is a planning tool. It is not a measurement. You build it before the system exists, then compare it with real data and change it.
Step 1: List the request path
Start by drawing the path of one representative request. Include only the steps the user waits for. Work done after the response is sent, such as writing an audit log through a queue, does not belong in the budget.
Note which calls are sequential and which are parallel. Sequential calls add. Parallel calls cost roughly the time of the slowest one, and that has its own risks, covered in the fan-out chapter.
Step 2: Fix the end-to-end target
Take the target from the requirement and the percentile you chose earlier. Suppose the product needs search results to feel responsive, and you set:
- End-to-end target: 300 ms at p99.
- Measured from the edge of your system to the response leaving it, or from the client, depending on what you can observe.
State where the clock starts and stops. A budget measured at the load balancer excludes the user's last-mile network and the browser's rendering time. If the requirement is about what the user perceives, subtract those parts before you divide the rest.
Step 3: Allocate shares
Give each component a share. Base the shares on three inputs:
- Known floors. A network round trip inside one region might take about 1 ms, but a call across continents takes 100 ms or more. Physics sets a minimum you cannot design away.
- Work done. A database query that scans an index and returns ten rows needs less than one that joins three tables.
- Variability. A component with a long tail, such as a shared database, needs a larger share at p99 than at p50.
Here is the allocation as code. It sums the shares and keeps the rest as headroom.
# Latency budget for a request that must finish within 300 ms at p99
budget_ms = 300
allocation_ms = {
"edge_and_network": 20,
"api_gateway": 10,
"application_service": 80,
"database": 120,
}
used = sum(allocation_ms.values())
headroom = budget_ms - used
print(used, headroom) # 230 70
assert headroom >= 0, "allocation exceeds the end-to-end budget"The allocations total 230 ms, which leaves 70 ms of headroom. That is about 23% of the budget. The headroom is deliberate. It absorbs the error in your estimates, retries, garbage collection pauses and the fact that the p99 values do not add up exactly. Do not hand it out to a component just because it is unused.
Why the sum is only approximate
The code above adds per-component p99 values. That is a simple planning rule, not a law. Two facts explain why.
- The slowest 1% of requests at one component are usually not the same requests that are slowest at another. If the gateway and the database each hit their p99 on different requests, no single request pays both. The real end-to-end p99 is then usually lower than the sum of the p99 values.
- Delays are sometimes correlated. A traffic spike or a garbage collection pause can slow several components at once. In that case the sum can understate the real latency.
So the sum of p99 values is a conservative first estimate in the independent case and an optimistic one in the correlated case. Keep headroom for both. When you have real traces, measure the end-to-end distribution directly and use the sum only to assign ownership.
A common alternative is to budget with different percentiles for different purposes: use p50 values to describe the typical request and p99 values to set limits. Adding p50 values gives roughly the median total. Adding p99 values gives a cautious bound on the tail.
Step 4: Check the budget against reality
Compare each share with what the component can actually do. Use measurements from a similar system, a prototype, or a vendor's published numbers, in that order of preference. Guesses come last.
A simple review table helps:
| Component | Budget (p99) | Measured or estimated (p99) | Status |
|---|---|---|---|
| Edge and network | 20 ms | 18 ms | Fits |
| API gateway | 10 ms | 6 ms | Fits |
| Application service | 80 ms | 95 ms | Over by 15 ms |
| Database | 120 ms | 90 ms | Fits with 30 ms to spare |
Here the application service is over its share, but the database has spare time. You have three options.
- Make the service faster, for example by caching a lookup or removing a redundant call.
- Move budget from the database to the service, since the database is under its share. This is legitimate only if the database team agrees and the new totals still fit.
- Use some of the headroom. This is the weakest choice, because it spends your safety margin before the system has run in production.
Each option should leave the total at or below the end-to-end target.
Budgeting for retries, timeouts and failures
Timeouts are part of the budget. A common mistake is to set a database timeout of 2 seconds in a system whose end-to-end target is 300 ms. A single slow call then breaks the target for that user and holds a thread for far longer than planned.
Follow these rules:
- Set each downstream timeout at or slightly above that component's p99 share, and never above the remaining end-to-end budget.
- Pass the remaining time down the call chain as a deadline. If the gateway has used 30 ms of a 300 ms budget, the service should know it has 270 ms left, and should skip optional work if the deadline is near.
- Count retries. A retry costs a full second attempt. If the first attempt times out at 120 ms, a retry cannot finish within a 120 ms share. Retries fit only when the timeout is short enough that both attempts fit, or when the retry is sent to a different replica in parallel.
import time
def remaining_ms(deadline_s):
"""Milliseconds left before an absolute deadline given in time.monotonic() seconds."""
return max(0.0, (deadline_s - time.monotonic()) * 1000)
def call_with_deadline(work, deadline_s, floor_ms=5):
left = remaining_ms(deadline_s)
if left < floor_ms:
raise TimeoutError("no time left in the request budget")
return work(timeout_ms=left)
start = time.monotonic()
deadline = start + 0.300 # 300 ms end-to-end budget
def fake_database(timeout_ms):
# Stand-in for a real call; pretends the query takes 90 ms.
time.sleep(min(0.090, timeout_ms / 1000))
return "rows"
print(call_with_deadline(fake_database, deadline)) # rows
print(round(remaining_ms(deadline))) # about 210The deadline is an absolute point in time, so each component can compute its own remaining budget without trusting the caller's arithmetic.
Edge cases
Fixed costs dominate small budgets. With a 50 ms target, a 20 ms cross-region hop uses 40% of the budget. When the floor is that large, you must change the architecture, such as placing a replica near the user, rather than squeeze the other components.
Shared components belong to several budgets. A database serves many request types. If one query type uses most of its capacity, the others see queueing delay. Budget the database for its worst-behaved client, or isolate the heavy workload.
Parallel calls change the arithmetic. If the service calls three backends in parallel, it waits for the slowest. The budget for that step is the p99 of the maximum of the three, which is worse than any single backend's p99. Give each backend a tighter target than the step as a whole.
Cold paths and cache misses. A cached response may take 5 ms and an uncached one 150 ms. If 5% of requests miss the cache, the p99 is set by the miss path, not the hit path. Budget for the miss.
Budgets drift. A new feature adds a call and the share quietly grows. Review the budget whenever the request path changes, and watch each hop in tracing so the drift shows up early.
Common errors
- Dividing the target equally among components. Components differ in work and variability, so equal shares waste time in some places and starve others.
- Leaving no headroom, so the plan fails at the first slow garbage collection.
- Forgetting network hops, serialization and TLS handshakes, which often add up to tens of milliseconds.
- Mixing percentiles, for example adding a p50 for one hop to a p99 for another, then reading the total as a p99.
- Setting timeouts independently of the budget.
- Treating the budget as final. It is a hypothesis that load testing and production traces will test.
Summary of the method
- Draw the request path the user waits on and mark sequential and parallel steps.
- Fix the end-to-end percentile target and where it is measured.
- Allocate shares using known floors, the work done and variability.
- Keep explicit headroom, around 20% to 30% at the start.
- Compare shares with measurements, and rebalance or redesign where they do not fit.
- Set timeouts and deadlines from the budget, and account for retries.
- Re-check whenever the path changes.
Exercise
A checkout request must finish within 400 ms at p99. Its path is: network and edge 30 ms, gateway 15 ms, order service 100 ms, payment provider 180 ms, all sequential. (a) How much headroom remains? (b) The payment provider's measured p99 is 230 ms. What are two ways to bring the plan back within the target without using all the headroom? (c) The order service calls inventory and pricing in parallel, and each has a p99 of 40 ms. Why might the parallel step take longer than 40 ms at p99?
Show answer
(a) The shares total 30 + 15 + 100 + 180 = 325 ms, so the headroom is 400 - 325 = 75 ms. (b) With payment at 230 ms the total is 375 ms, leaving 25 ms, which is nearly all the margin. Two options: reduce other shares, for example speed up the order service by caching so it needs 70 ms instead of 100 ms (total 345 ms); or change the payment call, for example by making it asynchronous so the user does not wait for the final confirmation, or by sending a hedged request to a second payment endpoint. Moving budget from a component that is under its share also works if its owner agrees. (c) A parallel step waits for the slower of the two calls. Each call is slow beyond 40 ms about 1% of the time, so the chance that at least one is slow is about 1 - 0.99^2, or roughly 2%. The step's own p99 is therefore above 40 ms, and each backend needs a tighter target than the step.
Exercise
A service has 250 ms left of its request deadline and calls a database with a 120 ms budget. The first attempt times out at 120 ms. Can the service retry the same call with another 120 ms timeout and still stay within its remaining time if the service needs 60 ms for its own work? Show the arithmetic.
Show answer
The first attempt uses 120 ms. The service's own work needs 60 ms. A retry with a 120 ms timeout adds another 120 ms. The total is 120 + 120 + 60 = 300 ms, which is more than the 250 ms left. The retry does not fit. Options are a shorter timeout for each attempt (for example 60 ms each, giving 60 + 60 + 60 = 180 ms), skipping the retry, or sending the second attempt to another replica in parallel after a short delay.